<?php
defined('IN_YUNYECMS') or exit('No permission');
/**
 * 模版编译类
 */
final class template_cache {
	public function __construct(){
	}
	/**
	 * @param $module
	 * @param $template
	 * @param string $style
	 * @return int|void
	 */
	public function cache_template_app($template,$module,$curtpl = 'default'){
		global $cfg;
		$ismobile = false;
		$landir=LAN;
		if(!empty($cfg['mobilecfg']["displaymode"])){
			if (is_mobile()) {
				$landir=LAN."_mobile";
				$ismobile = true;
			}
		}
		$tpl_file = YUNYECMS_ROOT.'theme/'.$curtpl . '/' .$landir.'/' . $module . '_' . $template . '.html';
		if (!file_exists($tpl_file)) {
			 messagebox("$tpl_file is not exists!");
		}
		if(!is_dir(CACHE_ROOT)) @mkdir(CACHE_ROOT, 0777, true);
		if(!is_dir(CACHE_ROOT . 'templates/')) @mkdir(CACHE_ROOT . 'templates/', 0777, true);
		if (!is_writable(CACHE_ROOT . 'templates/')) {
			 messagebox(CACHE_ROOT . 'templates/ 目录不可写');
		}
		$cache_path = CACHE_ROOT . 'templates/' . $curtpl. '/' .$landir. '/';
		if (!is_dir($cache_path)) {
			@mkdir($cache_path, 0777, true);
		 } elseif (!is_writable($cache_path)){
			exit($cache_path . ' 目录不可写');
		}
		$cache_file = $cache_path.$module .'_'.$template . '.php';
		$data = file_get_contents($tpl_file);
		$data = $this->template_parse($data);
		if(APP_DEBUG==1) {
			$data .= '<div class="remove_debug" style="position: relative;z-index: 99999;background-color: rgba(171, 166, 159, 0.66);color: #FFFDFD;">结束：<?php echo substr(str_replace(CACHE_ROOT,YUNYECMS_ROOT,__FILE__),0,-4).".html";?><span style="float: right;padding: 0px 10px;cursor: pointer;" onclick="remove_debug_div()">关闭</span></div><script>setTimeout(function(){$(".remove_debug").remove();},20000);</script>';
			$data = '<!DOCTYPE html><div class="remove_debug" style="position: relative;z-index: 99999;background-color: rgba(171, 166, 159, 0.66);color: #FFFDFD;">开始：<?php echo substr(str_replace(CACHE_ROOT,YUNYECMS_ROOT,__FILE__),0,-4).".html";?><span style="float: right;padding: 0px 10px;cursor: pointer;" onclick="remove_debug_div()">关闭</span></div>'.$data;
		}
		$strlen = @file_put_contents($cache_file, $data);
		chmod ( $cache_file, 0777 );
		if ($strlen == false) messagebox(str_replace(CACHE_ROOT, 'caches/', $cache_file) . ' is readonly!');
		return $strlen;
	}
	
	public function cache_template_addons($template,$module,$isadmin=0,$curtpl = 'default'){
		global $cfg;
		$ismobile = false;
		$landir=LAN;
		if(!empty($cfg['mobilecfg']["displaymode"])){
			if (is_mobile()) {
				$landir=LAN."_mobile";
				$ismobile = true;
			}
		}
		if($isadmin){
					$tpl_file = YUNYECMS_ROOT.'addons/'.ROUTE_M . '/tpl/'. ROUTE_C.'_'. $template . '.html';
				   }else{
					$tpl_file = YUNYECMS_ROOT.'addons/'.ROUTE_M . '/tpl/'.$landir . '/'. ROUTE_C.'_'. $template . '.html';
				   }
		if (!file_exists($tpl_file)) {
			 messagebox("$tpl_file is not exists!");
		}
		if(!is_dir(CACHE_ROOT . 'addons/'))mkdir(CACHE_ROOT . 'addons/', 0777, true);
		if (!is_writable(CACHE_ROOT . 'addons/')) {
			 messagebox(CACHE_ROOT . 'addons/ 目录不可写');
		}
		$cache_path = CACHE_ROOT . 'addons/' . ROUTE_M. '/' ;
		if(!$isadmin)$cache_path=$cache_path.$landir. '/';
		if (!is_dir($cache_path)) {
			mkdir($cache_path, 0777, true);
		 } elseif (!is_writable($cache_path)){
		   exit($cache_path . ' 目录不可写');
		}
		$cache_file = $cache_path.ROUTE_C .'_'.$template . '.php';
		$data = file_get_contents($tpl_file);
		$data = $this->template_parse($data);
		if(APP_DEBUG==1) {
			$data .= '<div class="remove_debug" style="position: relative;z-index: 99999;background-color: rgba(171, 166, 159, 0.66);color: #FFFDFD;">结束：<?php echo substr(str_replace(CACHE_ROOT,YUNYECMS_ROOT,__FILE__),0,-4).".html";?><span style="float: right;padding: 0px 10px;cursor: pointer;" onclick="remove_debug_div()">关闭</span></div><script>setTimeout(function(){$(".remove_debug").remove();},20000);</script>';
			$data = '<!DOCTYPE html><div class="remove_debug" style="position: relative;z-index: 99999;background-color: rgba(171, 166, 159, 0.66);color: #FFFDFD;">开始：<?php echo substr(str_replace(CACHE_ROOT,YUNYECMS_ROOT,__FILE__),0,-4).".html";?><span style="float: right;padding: 0px 10px;cursor: pointer;" onclick="remove_debug_div()">关闭</span></div>'.$data;
		}
		$strlen = @file_put_contents($cache_file, $data);
		chmod ( $cache_file, 0777 );
		if ($strlen == false) messagebox(str_replace(CACHE_ROOT, 'caches/', $cache_file) . ' is readonly!');
		return $strlen;
	}
	
	
	/**
	 * 更新模板缓存
	 *
	 * @param $tplfile	模板原文件路径
	 * @param $compiledtplfile	编译完成后，写入文件名
	 * @return $strlen 长度
	 */
	public function template_refresh($tplfile, $compiledtplfile) {
		$str = @file_get_contents ($tplfile);
		$str = $this->template_parse ($str);
		$strlen = file_put_contents ($compiledtplfile, $str );
		chmod ($compiledtplfile, 0777);
		return $strlen;
	}
		
	
	
	public function cache_dir_template($dirs = ''){
		if (empty($dirs)) $dirs = YUNYECMS_ROOT . "theme";
		if (is_dir($dirs)) {
			$dirs = glob($dirs . "/*");
			foreach ($dirs as $_dir) {
				self::cache_dir_template($_dir);
			}
		} else {
			$file_str = str_replace(YUNYECMS_ROOT . 'theme', '', $dirs);
			if (substr($file_str, -5) != '.html') return true;
			$file_str = str_replace("\\", '/', $file_str);
			$file_str = ltrim($file_str, '/');
			$file_strs = explode('/', $file_str);
			$m = $template = $style = '';
			foreach ($file_strs as $_i => $_sr) {
				if ($_i > 0 && strpos($_sr, '.html') === false) {
					$m .= $_sr . '/';
				}
			}
			$m = rtrim($m, '/');
			$template = str_replace('.html', '', array_pop($file_strs));
			$style = $file_strs[0];

			$this->cache_template($m, $template, $style);
		}
		return TRUE;
	}
	/**
	 * 解析模板
	 *
	 * @param $template	模板内容
	 * @return ture
	 */
	public function template_parse($template) {
		$template = preg_replace ( "/\{tpl\s+(.+)\}/", "<?php include tpl(\\1); ?>", $template );
		$template = preg_replace ( "/\{tpl_addons\s+(.+)\}/", "<?php include tpl_addons(\\1); ?>", $template );
		$template = preg_replace ( "/\{tpl_admin\s+(.+)\}/", "<?php include tpl_adm(\\1); ?>", $template );
		$template = preg_replace ( "/\{include\s+(.+)\}/", "<?php include \\1; ?>", $template );
		$template = preg_replace ( "/\{php\s+(.*?)\s*\}/", "<?php \\1?>", $template );
		$template = preg_replace ( "/\<php.*?>(.*?)<\/php>/is", "<?php \\1?>", $template );
		$template = preg_replace ( "/\{if\s+(.+?)\}/", "<?php if(\\1) { ?>", $template );
		$template = preg_replace ( "/\{else\}/", "<?php } else { ?>", $template );
		$template = preg_replace ( "/\{elseif\s+(.+?)\}/", "<?php } elseif (\\1) { ?>", $template );
		$template = preg_replace ( "/\{\/if\}/", "<?php } ?>", $template );
		$template = preg_replace("/\{for\s+(.+?)\}/","<?php for(\\1) { ?>",$template);
		$template = preg_replace("/\{\/for\}/","<?php } ?>",$template);
		//++ --
		$template = preg_replace("/\{\+\+(.+?)\}/","<?php ++\\1; ?>",$template);
		$template = preg_replace("/\{\-\-(.+?)\}/","<?php --\\1; ?>",$template);
		$template = preg_replace("/\{(.+?)\+\+\}/","<?php \\1++; ?>",$template);
		$template = preg_replace("/\{(.+?)\-\-\}/","<?php \\1--; ?>",$template);
/*		$template = preg_replace ( "/\{loop\s+(\S+)\s+(\S+)\}/", "<?php \$n=1;if(is_array(\\1)) foreach(\\1 AS \\2) { ?>", $template );
		$template = preg_replace ( "/\{loop\s+(\S+)\s+(\S+)\s+(\S+)\}/", "<?php \$n=1; if(is_array(\\1)) foreach(\\1 AS \\2 => \\3) { ?>", $template );
		$template = preg_replace ( "/\{\/loop\}/", "<?php \$n++;}unset(\$n); ?>", $template );*/
		
		//数组
		$template=preg_replace('/\{\$(\w+)\s*\.\s*(\w+)\s*\}/is','<?php echo $\\1["\\2"] ;?>',$template);
		$template=preg_replace('/\{\$(\w+)\s*\.\s*(\w+)\s*\.\s*(\w+)\s*\}/is','<?php echo $\\1["\\2"]["\\3"] ;?>',$template);
		$template = preg_replace ( "/\{([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff:]*\(([^{}]*)\))\}/", "<?php echo \\1;?>", $template );
		$template = preg_replace ( "/\{\\$([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff:]*\(([^{}]*)\))\}/", "<?php echo \\1;?>", $template );
		$template = preg_replace ( "/\{(\\$[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\}/", "<?php echo \\1;?>", $template );
		$template = preg_replace ( "/\{([A-Z_\x7f-\xff][A-Z0-9_\x7f-\xff]*\s*)\}/s", "<?php echo \\1;?>", $template );
		if (version_compare(PHP_VERSION, '5.5.0', '<')) {
			$template = preg_replace("/\{(\\$[a-zA-Z0-9_\[\]\'\"\$\x7f-\xff]+)\}/es", "\$this->addquote('<?php echo \\1;?>')",$template);
			$template = preg_replace("/\{yy:(\w+)\s*\}/ie", "self::yunyecms_tag('$1')", $template);
			$template = preg_replace("/\{yy:(\w+)\s+([^}]+)\}/ie", "self::yunyecms_tag('$1','$2','$0')", $template);
			$template = preg_replace("/\{\/yy\}/ie", "self::end_yunyecms_tag()", $template);
			$template = preg_replace("/\{loop\}/ie", "self::loop_tag()", $template);
			$template = preg_replace("/\{loop\s*([^}]+)\}/ie", "self::loop_tag('$1','$2')", $template);
			$template = preg_replace("/\{\/loop\}/ie", "self::end_loop_tag()", $template);
			$template = preg_replace("/\{form\}/ie", "self::form_tag()", $template);
			$template = preg_replace("/\{form\s*([^}]+)\}/ie", "self::form_tag('$1')", $template);
			$template = preg_replace("/\{\/form\}/ie", "self::end_form_tag()", $template);	
			$template = preg_replace("/\{home\}/ie", "self::home_tag()", $template);
			$template = preg_replace("/\{home\s*([^}]+)\}/ie", "self::home_tag('$1')", $template);
			$template = preg_replace("/\{\/home\}/ie", "self::end_home_tag()", $template);
			$template = preg_replace("/\{addons\}/ie", "self::addons_tag()", $template);
			$template = preg_replace("/\{addons\s*([^}]+)\}/ie", "self::addons_tag('$1')", $template);
			$template = preg_replace("/\{\/addons\}/ie", "self::end_addons_tag()", $template);	
		} else {
			$template = preg_replace("/\{(\\$[a-zA-Z0-9_\[\]\'\"\$\x7f-\xff]+)\}/s", "<?php echo \\1;?>", $template);
			$template = preg_replace_callback("/\{yy:(\w+)\s*\}/i", "self::yunyecms_tag", $template);
			$template = preg_replace_callback("/\{yy:(\w+)\s+([^}]+)\}/i", "self::yunyecms_tag", $template);
			$template = preg_replace_callback("/\{\/yy\}/i", "self::end_yunyecms_tag", $template);
			$template = preg_replace_callback("/\{loop\}/i", "self::loop_tag", $template);
			$template = preg_replace_callback("/\{loop\s*([^}]+)\}/i", "self::loop_tag", $template);
			$template = preg_replace_callback("/\{\/loop\}/i", "self::end_loop_tag", $template);
			$template = preg_replace_callback("/\{form\}/i", "self::form_tag", $template);
			$template = preg_replace_callback("/\{form\s*([^}]+)\}/i", "self::form_tag", $template);
			$template = preg_replace_callback("/\{\/form\}/i", "self::end_form_tag", $template);
			$template = preg_replace_callback("/\{home\}/i", "self::home_tag", $template);
			$template = preg_replace_callback("/\{home\s*([^}]+)\}/i", "self::home_tag", $template);
			$template = preg_replace_callback("/\{\/home\}/i", "self::end_home_tag", $template);
			$template = preg_replace_callback("/\{addons\}/i", "self::addons_tag", $template);
			$template = preg_replace_callback("/\{addons\s*([^}]+)\}/i", "self::addons_tag", $template);
			$template = preg_replace_callback("/\{\/addons\}/i", "self::end_addons_tag", $template);
		}		
		$template = "<?php defined('IN_YUNYECMS') or exit('No permission.'); ?>" . $template;
		return $template;
	  }	
/**
	 * 转义 // 为 /
	 *
	 * @param $var	转义的字符
	 * @return 转义后的字符
	 */
	public function addquote($var) {
		return str_replace ( "\\\"", "\"", preg_replace ( "/\[([a-zA-Z0-9_\-\.\x7f-\xff]+)\]/s", "['\\1']", $var ) );
	}
	
	public static function loop_tag($data=""){
		if (is_array($data)) {
			$data = empty($data[1])?"":$data[1];
		}
		preg_match_all("/([a-z]+)\=[\"]?([^\"]+)[\"]?/i", stripslashes($data), $matches, PREG_SET_ORDER);
		$tools = array('name', 'item', 'offset', 'length', 'key');
		$tag = array();
		foreach ($matches as $v) {
			$tag[$v[1]] = $v[2];
		}
        $name   =   !empty($tag['name'])?'$'.$tag['name']:'$data';
        $item   =   !empty($tag['item'])?$tag['item']:'v';
        $empty =    isset($tag['empty'])?$tag['empty']:'';
        $index   =    !empty($tag['index'])?$tag['index']:'i';
        $key   =    !empty($tag['key'])?$tag['key']:'key';
        $mod   =    isset($tag['mod'])?$tag['mod']:'2';
		$parseStr   =  '<?php ';
        $parseStr  .=  'if(is_array('.$name.')): $'.$index.' = -1;';
		if(isset($tag['length']) && '' !=$tag['length'] ) {
			$parseStr  .= ' $__DATA__ = array_slice('.$name.','.$tag['offset'].','.$tag['length'].',true);';
		}elseif(isset($tag['offset'])  && '' !=$tag['offset']){
            $parseStr  .= ' $__DATA__ = array_slice('.$name.','.$tag['offset'].',null,true);';
        }else{
            $parseStr .= ' $__DATA__ = '.$name.';';
        }
        $parseStr .= 'if(count($__DATA__)==0 )  echo "'.$empty.'" ;';
        $parseStr .= 'foreach($__DATA__ as $'.$key.'=>$'.$item.'): ';
        $parseStr .= '$mod = ($'.$index.' % '.$mod.' );';
        $parseStr .= '++$'.$index.';?>';
        if(!empty($parseStr)) {
            return $parseStr;
        }
	}
	
	public static function end_loop_tag(){
		    $parseStr = '<?php  endforeach;  endif; ?>';
			return $parseStr;
	}
	
	public static function form_tag($data=""){
		if (is_array($data)) {
			$data = empty($data[1])?"":$data[1];
		}
		$matches=array();
	   if(!empty($data)){
		   preg_match_all("/([a-z]+)\=[\"]?([^\"]+)[\"]?/i", stripslashes($data), $matches, PREG_SET_ORDER);
	    }	
		$arr = array('action','num', 'return','catid');
		$datas = array();
		if($matches){
			foreach ($matches as $v) {
			if(in_array($v[1], $arr)) {
				$$v[1] = $v[2];
			}
			$datas[$v[1]] = $v[2];
		  }
		}
		if(empty($datas["class"])) $datas["class"]="form-horizontal";
		$str = '';
		$return = isset($return) && trim($return) ? trim($return) : 'data';
		$str .= '$form_parse = core::load_class(\'tag_parse\');';
		$str .= '$dataparm ='.self::arr_to_html($datas).';';
		if(!empty($datas["onsubmit"])){
			$str .='$onsubmit=\'onsubmit="\'.$dataparm["onsubmit"].\'"\';';
		} else{
		$str .= '$onsubmit =\'\';';
		}
		$str .='$tokenstr="<script language=\"javascript\" src=\"".ROOT."index.php?m=api&c=index&a=get_token\"></script>";';
		$str .= '$'.$return.'=$form_parse->form_tag('.self::arr_to_html($datas).');';
		$str .= 'echo \'<form action="\'.url(\'content/index/formadd\').\'"  class="\'.$dataparm["class"].\'"  name="form\'.$dataparm["catid"].\'"   id="form\'.$dataparm["catid"].\'" method="post" enctype="multipart/form-data"   \'.$onsubmit.\'  >\';';
		if(!empty($datas["class"]))
		$str .= 'echo \'<input type="hidden" name="catid" id="catid" value="\'.$dataparm["catid"].\'">\';';
		$str .= 'echo $tokenstr;';
		return "<"."?php ".$str."?".">";
	}
	public static function end_form_tag(){
		    $parseStr = '</form>';
			return $parseStr;
	}	
	
	
	public static function home_tag($data=""){
		if (is_array($data)) {
			$data = empty($data[1])?"":$data[1];
		}
		$matches=array();
	   if(!empty($data)){
		   preg_match_all("/([a-z]+)\=[\"]?([^\"]+)[\"]?/i", stripslashes($data), $matches, PREG_SET_ORDER);
	    }	
		$arr = array('action','num', 'return','catid');
		$datas = array();
		if($matches){
			foreach ($matches as $v) {
			if(in_array($v[1], $arr)) {
				$$v[1] = $v[2];
			}
			$datas[$v[1]] = $v[2];
		  }
		}
		$str = '';
		$return = isset($return) && trim($return) ? trim($return) : 'data';
		$str .= '$home_parse = core::load_class(\'tag_parse\');';
		$str .= '$dataparm ='.self::arr_to_html($datas).';';
		$str .= '$'.$return.'=$home_parse->home_tag('.self::arr_to_html($datas).');';
		return "<"."?php ".$str."?".">";
	}
	public static function end_home_tag(){
		    $parseStr = '';
			return $parseStr;
	}	
	
	public static function addons_tag($data=""){
		if (is_array($data)) {
			$data = empty($data[1])?"":$data[1];
		}
		$matches=array();
	   if(!empty($data)){
		   preg_match_all("/([a-z]+)\=[\"]?([^\"]+)[\"]?/i", stripslashes($data), $matches, PREG_SET_ORDER);
	    }	
		$arr = array('name','num', 'return','catid');
		$datas = array();
		if($matches){
			foreach ($matches as $v) {
			if(in_array($v[1], $arr)) {
				$$v[1] = $v[2];
			}
			$datas[$v[1]] = $v[2];
		  }
		}
		$str = '';
		$return = isset($return) && trim($return) ? trim($return) : 'data';
		$str .= '$addons_parse = core::load_class(\'tag_parse\');';
		$str .= '$dataparm ='.self::arr_to_html($datas).';';
		$str .= '$'.$return.'=$addons_parse->addons_tag('.self::arr_to_html($datas).');';
		return "<"."?php ".$str."?".">";
	}
	public static function end_addons_tag(){
		    $parseStr = '';
			return $parseStr;
	}		
	
	
	
	/**
	 * 解析YUNYECMS标签
	 * @param string $op 操作方式
	 * @param string $data 参数
	 * @param string $html 匹配到的所有的HTML代码
	 */
	public static function yunyecms_tag($matchdata, $data='', $html='') {
        if (!is_array($matchdata)) {
			$op = $matchdata;
		} else {
			$op = empty($matchdata[1])?"":$matchdata[1];
			$data =empty($matchdata[2])?"":$matchdata[2];
			$html = $matchdata[0];
		}		
	   $matches=array();
	   if(!empty($data)){
		   preg_match_all("/([a-z]+)\=[\"]?([^\"]+)[\"]?/i", stripslashes($data), $matches, PREG_SET_ORDER);
	    }	
		$arr = array('action','num','cache','page', 'pagesize', 'urlrule', 'return', 'start');
		$tools = array('json', 'xml', 'block', 'query', 'list', 'find','cat','breadcumb','relation','lang','home');
		$datas = array();
		$tag_id = md5(stripslashes($html));
		//可视化条件
		$str_datas = 'op='.$op.'&tag_md5='.$tag_id;
		if($matches){
			foreach ($matches as $v) {
			$str_datas .= $str_datas ? "&$v[1]=".($op == 'block' && strpos($v[2], '$') === 0 ? $v[2] : urlencode($v[2])) : "$v[1]=".(strpos($v[2], '$') === 0 ? $v[2] : urlencode($v[2]));
			if(in_array($v[1], $arr)) {
				$$v[1] = $v[2];
			}
			$datas[$v[1]] = $v[2];
		  }
		}
		$str = '';
		$num = isset($num) && intval($num) ? intval($num) : 20;
		$cache = isset($cache) && intval($cache) ? intval($cache) : 0;
		$return = isset($return) && trim($return) ? trim($return) : 'data';
		if (!isset($urlrule)) $urlrule = '';
		if (!empty($cache) && !isset($page)) {
			$str .= '$'.$return.' = "";$tag_cache_name = md5(implode(\'&\','.self::arr_to_html($datas).').\''.$tag_id.'\');if(!$'.$return.' = tpl_cache($tag_cache_name,'.$cache.')){';
		}
		if (in_array($op,$tools)) {
			switch ($op) {
				case 'json':
						if (isset($datas['url']) && !empty($datas['url'])) {
							$str .= '$json = @file_get_contents(\''.$datas['url'].'\');';
							$str .= '$'.$return.' = json_decode($json, true);';
						}
					break;
				case 'xml':
						$str .= '$xml = core::load_class(\'xml\');';
						$str .= '$xml_data = @file_get_contents(\''.$datas['url'].'\');';
						$str .= '$'.$return.' = $xml->xml_unserialize($xml_data);';
					break;
				case 'query':
						$str .= '$tag_parse = core::load_class(\'tag_parse\');';
						$str .= '$'.$return.'="";';
						if (isset($datas['page'])) {
						  $str .= '$page=""; ';
					      $str .= '$pagelist=$tag_parse->query_tag('.self::arr_to_html($datas).');';
					      $str .= '$'.$return.'=$pagelist[\'query\'];';
					      $str .= '$page=$pagelist[\'page\'];';
						}else{
					      $str .= '$'.$return.'=$tag_parse->query_tag('.self::arr_to_html($datas).');';
						}
					break;	
				case 'block':
					$str .= '$block_tag = core::load_app_class(\'block_tag\', \'block\');';
					$str .= 'echo $block_tag->yy_tag('.self::arr_to_html($datas).');';
					break;
				case 'list':
						$str .= '$tag_parse = core::load_class(\'tag_parse\');';
						$str .= '$'.$return.'="";';
						if (isset($datas['page'])) {
						  $str .= '$page=""; ';
					      $str .= '$pagelist=$tag_parse->list_tag('.self::arr_to_html($datas).');';
					      $str .= 'if(isset($pagelist[\'query\'])) { $'.$return.'=$pagelist[\'query\']; } else{ $'.$return.'=""; }';
					      $str .= 'if(isset($pagelist[\'page\'])) { $page=$pagelist[\'page\']; }';
						}else{
					      $str .= '$'.$return.'=$tag_parse->list_tag('.self::arr_to_html($datas).');';
						}
					break;
				case 'find':
					$str .= '$find_parse = core::load_class(\'tag_parse\');';
					$str .= '$'.$return.'=$find_parse->find_tag('.self::arr_to_html($datas).');';
					break;
				case 'cat':
					$str .= '$tag_parse = core::load_class(\'tag_parse\');';
					$str .= '$'.$return.'=$tag_parse->cat_tag('.self::arr_to_html($datas).');';
					break;	
				case 'breadcumb':
					$str .= '$tag_parse = core::load_class(\'tag_parse\');';
					$str .= '$'.$return.'=$tag_parse->breadcumb_tag('.self::arr_to_html($datas).');';
					break;	
				case 'relation':
					$str .= '$tag_parse = core::load_class(\'tag_parse\');';
					$str .= '$'.$return.'=$tag_parse->relation_tag('.self::arr_to_html($datas).');';
					break;
				case 'lang':
					$str .= '$tag_parse = core::load_class(\'tag_parse\');';
					$str .= '$'.$return.'=$tag_parse->lang_tag('.self::arr_to_html($datas).');';
					break;
				case 'home':
					$str .= '$tag_parse = core::load_class(\'tag_parse\');';
					$str .= '$'.$return.'=$tag_parse->home_tag('.self::arr_to_html($datas).');';
					break;				 }
		} else {
			if (!isset($action) || empty($action)) return false;
			if (file_exists(APP_PATH.$op.DIRECTORY_SEPARATOR.'classes'.DIRECTORY_SEPARATOR.$op.'_tag.class.php')) {
				$str .= '$'.$op.'_tag = core::load_app_class("'.$op.'_tag", "'.$op.'");if (method_exists($'.$op.'_tag, \''.$action.'\')) {';
				if (isset($start) && intval($start)) {
					$datas['limit'] = intval($start).','.$num;
				} else {
					$datas['limit'] = $num;
				}
				if (isset($page)) {
                          $str .= '$pagelist=$'.$op.'_tag->'.$action.'('.self::arr_to_html($datas).');';
					      $str .= '$'.$return.'=$pagelist[\'query\'];';
					      $str .= '$page=$pagelist[\'page\'];';					
				}else{
				$str .= '$'.$return.' = $'.$op.'_tag->'.$action.'('.self::arr_to_html($datas).');';
				}
				$str .= '}';
			}
		}
		if (!empty($cache) && !isset($page)) {
			$str .= 'if(!empty($'.$return.')){setcache($tag_cache_name, $'.$return.', \'tpl_data\');}';
			$str .= '}';
		}
		return "<"."?php ".$str."?".">";
	}
	
	/**
	 * YY标签结束
	 */
	static private function end_yunyecms_tag() {
		return '';
	}
	
	/**
	 * 转换数据为HTML代码
	 * @param array $data 数组
	 */
	private static function arr_to_html($data) {
		if (is_array($data)) {
			$str = 'array(';
			$k=0;
			foreach ($data as $key=>$val) {
				$k++;
				if (is_array($val)) {
					$str .= "'$key'=>".self::arr_to_html($val).",";
				} else {
					if($k!=count($data)){
						$comma=",";
					}else{$comma="";}
					if (strpos($val, '$')===0) {
						$str .= "'$key'=>$val".$comma;
					} else {
						$str .= "'$key'=>'".uaddslashes($val)."'$comma";
					}
				}
			}
			return $str.')';
		}
		return false;
	}
}
?>