<?php
class tag_parse {
	private $db;
	private $lang;
	public function __construct() {
		global $lang;
		$this->db = core::load_model("model_tag");
		$this->lang = $lang;
	}
	public function list_tag($data) {
		if(empty($data['catid'])) {
		   echo("list标签解析错误:catid为空");
		}else{
		   $catid = intval($data['catid']);
		}
		if(!empty($data['page'])){
		    $page = $data['page'];
		}
		$catid=getreal_catid($catid,$this->lang['id'],'category',$this->db);
		$modelid=getmodelid($catid);
		if(empty($modelid)){
			 echo("list标签解析错误:模型不存在，请检查栏目ID（{$catid}）是否存在");			
		}else{
			 $curmodel=getmodel($modelid);
		     $tablename="m_".$curmodel['tablename'];
			 $sqlquery="select * from `#yunyecms_{$tablename}`  ";
			 $catidstr= getcatin($catid);
			 $where=" where catid in($catidstr)  ";
			 $limit="";
			 if(!empty($data['where'])){
			   $where=$where.trim($data['where']);
			 }
			if(isset($data['pic'])){
				$pic=intval($data['pic']);
				if(!empty($pic)) $where=$where." and pic !='' ";
			}
			//推荐
			 if($curmodel["modeltype"]==1){
				 $where=$where." and status=1 ";
				if(isset($data['isgood'])){
					$isgood=intval(usafestr(trim($data['isgood'])));
					if(is_numeric($isgood)) $where=$where." and isgood =$isgood ";
				}
				//置顶
				if(isset($data['istop'])){
					$istop=intval(usafestr(trim($data['istop'])));
					if(is_numeric($istop)) $where=$where." and istop =$istop ";
				}
				//头条
				if(isset($data['ishead'])){
					$ishead=intval(usafestr(trim($data['ishead'])));
					if(is_numeric($ishead)) $where=$where." and ishead =$ishead ";
				}
			}
			 $modeltype=getmodeltype($modelid);
			 if($modeltype=="singlepage"){
                 $pathurl='singlepage';
			 }else{
                 $pathurl='show';
			 }
			if(!empty($data['order'])){
			   $orderstr = trim($data['order']);
			   $order=" order by $orderstr ";
			}else{
			   $order=" order by `addtime` desc ";
			}
			if(!empty($page)){
					$sqlcnt=" select count(*) from `#yunyecms_{$tablename}` ";
						if(!empty($data['num'])){
						   $num = intval($data['num']);
						   $pagesize=$num;
						   }else{
						   $pagesize=20;
						  }	
					$pagearr=$this->db->pagelist($sqlcnt,$sqlquery,$where,$order,$pagesize);
					if(isset($pagearr["query"])){
					foreach($pagearr["query"] as $key=>$var){
						  if(strlen(RD)>0&&stripos($pagearr["query"][$key]["pic"],RD)===FALSE){
								$pagearr["query"][$key]["pic"]=!empty($var['pic'])?RD.$var['pic']:''; 
								$pagearr["query"][$key]["picfile"]=!empty($var['picfile'])?RD.$var['picfile']:''; 
						   };
							 $pagearr["query"][$key]["url"]=!empty($var['exlink'])?$var['exlink']:geturl($var['catid'],$var['id'],$modeltype);
							 if(!empty($var['content']))$pagearr["query"][$key]["content"]=uhtmlspecialchars_decode($var["content"]);
					   }
					}
					return $pagearr;
			  }else{
				if(!empty($data['num'])){
				   $num = intval($data['num']);
				   $limit=" limit 0, $num";
				}
				$strsql=$sqlquery.$where.$order.$limit;
				$return = $this->db->select($strsql);
				if(isset($return)){
				foreach($return as $key=>$var){
						  if(strlen(RD)>0&&stripos($return[$key]["pic"],RD)===FALSE){
								$return[$key]["pic"]=!empty($var['pic'])?RD.$var['pic']:''; 
								$return[$key]["picfile"]=!empty($var['picfile'])?RD.$var['picfile']:''; 
						   };
							  $return[$key]["url"]=!empty($var['exlink'])?$var['exlink']:geturl($var['catid'],$var['id'],$modeltype);
							  if(!empty($var['content']))$return[$key]["content"]=uhtmlspecialchars_decode($var["content"]);
					    }
				  }
				return $return;
			 }
		 }

	}
	/**
	 * 单条信息标签
	 * @param $data
	 */
	 public function find_tag($data) {
		if(!empty($data['catid'])){
		    $catid = intval($data['catid']);
		    $catid=getreal_catid($catid,$this->lang['id'],'category',$this->db);
		    $modelid=getmodelid($catid);
				if(!$modelid){
				   $outstr="find标签解析错误:模型不存在，请检查栏目ID（{$catid}）是否存在";
				   echo($outstr);	
				}
		    $catidstr= getcatin($catid);
		    $where=" where catid in($catidstr)";
		}else{
			$modelid=$data['modelid'];
			if(empty($modelid)){
				 $outstr="find标签解析错误:模型不存在，请检查模型ID（{$modelid}）是否存在";
				 echo($outstr);	
			}
		 }
		if(!empty($modelid)){
			if(!empty($data['id'])){
			  $id=$data['id'];
		      $where=" where id=$id ";
			}
			$curmodel=getmodel($modelid);
			if($curmodel){
				$tablename="m_".$curmodel['tablename'];
			$modelfields_all=$this->db->select("select * from `#yunyecms_modelfields`  where modelid={$modelid}  and issys=0 ");			
			$sqlquery="select * from `#yunyecms_{$tablename}`  ";
			if(!empty($data['where'])){
			   $where=$where.trim($data['where']);
			}
			if(isset($data['pic'])){
				$pic=intval($data['pic']);
				if(!empty($pic)) $where=$where." and pic !='' ";
			}
			//推荐
			if($curmodel["modeltype"]==1){
					if(isset($data['isgood'])){
						 /* if(!$this->db->field_exists('isgood',$tablename)){
							exit("find标签解析错误:字段isgood不存在");
							}*/
						$isgood=intval(usafestr(trim($data['isgood'])));
						if(is_numeric($isgood)) $where=$where." and isgood =$isgood ";
					}
					//置顶
					if(isset($data['istop'])){
						$istop=intval(usafestr(trim($data['istop'])));
						if(is_numeric($istop)) $where=$where." and istop =$istop ";
					}
					//头条
					if(isset($data['ishead'])){
						$ishead=intval(usafestr(trim($data['ishead'])));
						if(is_numeric($ishead)) $where=$where." and ishead =$ishead ";
					}			
			}
			$limit=" limit 0, 1";
			if(!empty($data['order'])){
			   $orderstr = trim($data['order']);
			   $order=" order by $orderstr ";
			}else{
			   $order=" order by `addtime` desc ";
			}	
			$strsql=$sqlquery.$where.$order.$limit;
			$return = $this->db->find($strsql);
				 if(strlen(RD)>0&&stripos($return["pic"],RD)===FALSE){
					 $return["pic"]=!empty($return["pic"])?RD.$return["pic"]:''; 
					 $return[$key]["picfile"]=!empty($return['picfile'])?RD.$return['picfile']:''; 
				 };
					 if(isset($return['content']))$return["content"]=uhtmlspecialchars_decode($return["content"]);
					  foreach($modelfields_all as $key=>$var){
						 $fdname=$var['fdname'];
						  if(isset($return[$fdname])){
							 $return[$fdname]=uhtmlspecialchars_decode($return[$fdname]);
						  }
					   }
			    return $return;
				
			}else{
				$outstr="find标签解析错误:模型不存在，请检查模型ID（{$modelid}）是否存在";
				echo($outstr);	
			}
		 }
	}	
/**
	 * 直接执行sql标签
	 * @param $data
	 */
	public function query_tag($data) {
		if(empty($data['sql'])) {
			echo("sql标签解析错误:sql参数为空");
		}else{
			 if(!empty($data['page'])){
				$page = $data['page'];
			   }
			$where="";
			$order="";
			 global $yunyecms_dbconfig;
			 $sqlquery=$data['sql'];
			 $sqlquery=str_ireplace('#yunyecms_',$yunyecms_dbconfig['tablepre'],trim($sqlquery));
			 if(!empty($page)){
					$list=$this->db->select($sqlquery);
					$sqlcnt=count($list);
						if(!empty($data['num'])){
						   $num = intval($data['num']);
						   $pagesize=$num;
						   }else{
						   $pagesize=20;
						  }
					$pagearr=$this->db->pagelist($sqlcnt,$sqlquery,$where,$order,$pagesize);
					if(isset($pagearr["query"])){
						foreach($pagearr["query"] as $key=>$var){
							  if(strlen(ROOT)>1){ $picpath=substr(ROOT, 0, -1); $pagearr["query"][$key]["pic"]=!empty($var['pic'])?$picpath.$var['pic']:''; }
									 $pagearr["query"][$key]["url"]=!empty($var['exlink'])?$var['exlink']:url('show',array('id'=>$var['id']));
									 if(!empty($var['content']))$pagearr["query"][$key]["content"]=uhtmlspecialchars_decode($var["content"]);
						   }
						}
					return $pagearr;
			  }else{
				if(!empty($data['num'])){
				   $num = intval($data['num']);
				   $limit=" limit 0, $num";
				}
				$strsql=$sqlquery.$limit;
				$return = $this->db->select($strsql);
				if(isset($return)){
				foreach($return as $key=>$var){
							if(strlen(ROOT)>1){ $picpath=substr(ROOT, 0, -1); $return[$key]["pic"]=!empty($var['pic'])?$picpath.$var['pic']:''; }
								  if(!empty($var['catid'])){
	  $return[$key]["url"]=!empty($var['exlink'])?$var['exlink']:url('show',array('id'=>$var['id'],'catid'=>$var['catid']));								  
								  }else{
	  $return[$key]["url"]=!empty($var['exlink'])?$var['exlink']:url('show',array('id'=>$var['id']));								  

								  }
								  if(!empty($var['content']))$return[$key]["content"]=uhtmlspecialchars_decode($var["content"]);
					  }
				  } 
				return $return;
			 }
		}
	}
		/**
	 * 导航信息标签
	 * @param $data
	 */
	public function cat_tag($data) {
		global $lang;
		$pid=empty($data['pid'])?0:$data['pid'];
		$level=empty($data['level'])?0:$data['level'];
		$num=empty($data['num'])?0:$data['num'];
		$catid=empty($data['catid'])?'':$data['catid'];
		$isfoot=empty($data['foot'])?0:$data['foot'];
		 if(!is_numeric($pid)){
			echo("error pid");
		  }else{
			$return=getcat($pid,$level,$num,$lang['id'],$isfoot,$catid);
			return $return;
		 }
	 }
	/**
	 * 面包屑导航信息标签
	 * @param $data
	 */
	public function breadcumb_tag($data) {
		  $catid=empty($data['catid'])?0:$data['catid'];
		  if(!is_numeric($catid)){
			 echo("error catid");
		  }else{
			$parent=getbreadcumb($catid);
			return $parent; 
		  }

	}	
	/**
	 * 导航信息标签
	 * @param $data
	 */
	public function lang_tag($data) {
		$return=getlang();
		return $return;
	}		
	/**
	 * 相关文章标签
	 * @param $data
	 */
	public function relation_tag($data) {
		if(!empty($data['catid'])){
		    $catid = intval($data['catid']);
		}
		$catid=getreal_catid($catid,$this->lang['id'],'category',$this->db);
		if(!empty($data['modelid'])){
		   $modelid = intval($data['modelid']);
		}else{
		   $modelid=getmodelid($catid);
		}
		if(empty($modelid)){
			 echo("relation标签解析错误:模型不存在，请检查栏目ID（{$catid}）是否存在");			
		}else{
			$curmodel=getmodel($modelid);
		    $tablename="m_".$curmodel['tablename'];
			$sqlquery="select * from `#yunyecms_{$tablename}`  ";
	      if(!empty($data['order'])){
		   $orderstr = trim($data['order']);
		   $order=" order by $orderstr ";
		}else{
		   $order=" order by `addtime` desc ";
		}	
		$limit = $data['id'] ? $data['num']+1 : $data['num'];
		$limit=" limit 0,{$limit}";
		$returnarray1=array();
		$returnarray2=array();
		if(!empty($data['relation'])) {
		    $where=" where status=1 ";
			$relations = explode('|',trim($data['relation'],'|'));
			$relations = array_diff($relations, array(null));
			$relations = implode(',',$relations);
			$where =$where. " and `id` IN ($relations)";
			$returnarray1 = $this->db->select($sqlquery.$where.$order.$limit);
		   }elseif(!empty($data['keywords'])) {
			$keywords = str_replace(array('%',"'"), '',$data['keywords']);
			$keywords_arr = explode(' ',$keywords);
			$key_array = array();
			$number = 0;
			$i =1;
			$catidstr= getcatin($catid);
		    $where2 =" where 1 ";
		    //$where2 =" where catid in($catidstr) ";
			if(!empty($relations)){
		    $where2 .="  and `id` NOT IN ($relations) ";
			}
			 if(!empty($keywords_arr)){
				$sqlkey=" and ( ";
				foreach ($keywords_arr as $_k) {
					if($i==1){
						$sqlkey = $sqlkey."  `seokeywords` LIKE '%$_k%' ";
					 }else{
						$sqlkey = $sqlkey." or `seokeywords` LIKE '%$_k%' ";
					}
					$i=$i+1;
			    }
				$sqlkey= $sqlkey. " ) ";
                $where2=$where2.$sqlkey.(isset($data['id']) && intval($data['id']) ? " AND `id` != '".abs(intval($data['id']))."'" : '');
			 }
			$returnarray2 = $this->db->select($sqlquery.$where2.$order.$limit);
		}
		$return=array_merge($returnarray1,$returnarray2);
		if(isset($return)){
		foreach($return as $key=>$var){
					if(strlen(ROOT)>1){ $picpath=substr(ROOT, 0, -1); $return[$key]["pic"]=!empty($var['pic'])?$picpath.$var['pic']:''; }
						  $return[$key]["url"]=!empty($var['exlink'])?$var['exlink']:url('show',array('catid'=>$var['catid'],'id'=>$var['id']));
						  if(!empty($var['content']))$return[$key]["content"]=uhtmlspecialchars_decode($var["content"]);
			  }
		  }	
		  return $return;
		 }	
	}
	/**
	 * 表单信息标签
	 * @param $data
	 */
	public function form_tag($data) {
		if(!empty($data['catid'])){
		    $catid = intval($data['catid']);
		    $modelid=getmodelid($catid);
		}
		$catid=getreal_catid($catid,$this->lang['id'],'category',$this->db);
		if(empty($modelid)){
			 echo("form标签解析错误:模型不存在,请检查栏目ID（{$catid}）是否存在！");			
		}else{
			$curmodel=getmodel($modelid);
		    $tablename="m_".$curmodel['tablename'];
			$modelfields_all=$this->db->select("select * from `#yunyecms_modelfields`  where modelid={$modelid}  and isadd=1 ");
			return $modelfields_all;
		 }
		
	}
	
	public function home_tag($data) {
		if(!empty($data['modeltype'])) {
		   $modeltype = intval($data['modeltype']);
		 }
		if(!empty($data['modelid'])) {
		   $modelid = intval($data['modelid']);
		 }
		     $tablename="homeset";
			 $sqlquery="select * from `#yunyecms_{$tablename}`  ";
			 $where=" where  status=1 and lang={$this->lang['id']} and isdisplay=1 ";
			 $limit="";
			 if(!empty($data['where'])){
			   $where=$where.trim($data['where']);
			 }
			if(isset($data['pic'])){
				$pic=intval($data['pic']);
				if(!empty($pic)) $where=$where." and pic !='' ";
			}
			if(isset($data['mode'])){
				$mode=trim($data['mode']);
				if(!empty($mode)) $where=$where." and mode ='{$mode}' ";
			}
			if(isset($data['style'])){
				$style=trim($data['style']);
				if(!empty($style)) $where=$where." and style ='{$style}' ";
			}
		    if(!empty($data['order'])){
			   $orderstr = trim($data['order']);
			   $order=" order by $orderstr ";
			}else{
			   $order=" order by `ordernum` asc,`addtime` desc ";
			}
			if(!empty($data['num'])){
			   $num = intval($data['num']);
			   $limit=" limit 0, $num";
			}
				$strsql=$sqlquery.$where.$order.$limit;
				$return = $this->db->select($strsql);
				if(isset($return)){
				foreach($return as $key=>$var){
					  if(strlen(RD)>0&&stripos($return[$key]["pic"],RD)===FALSE){
							$return[$key]["pic"]=!empty($var['pic'])?RD.$var['pic']:''; 
							$return[$key]["picfile"]=!empty($var['picfile'])?RD.$var['picfile']:''; 
					   };
			if($var["modeltype"]==1){
				$return[$key]["url"]=!empty($var['url'])?$var['url']:url('lists',array('catid'=>$var['catid']));
			}elseif($var["modeltype"]==2){
				$return[$key]["url"]=!empty($var['url'])?$var['url']:url('singlepage',array('catid'=>$var['catid']));
			}
			if(!empty($var['content']))$return[$key]["content"]=uhtmlspecialchars_decode($var["content"]);
					  }
				  }
			return $return;
	}	
	
	//插件调用标签
	public function addons_tag($data) {
		if(!empty($data['cat'])) {
		     $addon_cat = intval($data['modeltype']);
		 }
		if(!empty($data['modelid'])) {
		   $modelid = intval($data['modelid']);
		 }
		     $tablename="addons";
			 $sqlquery="select * from `#yunyecms_{$tablename}`  ";
			 $where=" where  `status`=1   ";
		     if(isset($data['name'])){
				$name=uhtmlspecialchars(trim($data['name']));
				if(!empty($name)) $where=$where." and addons_dir ='{$name}' ";
			}
			$strsql=$sqlquery.$where." limit 1";
			$return = $this->db->find($strsql);
			if($return){
				$addons_dir=YUNYECMS_ADDONS;
				$strurl='addons/'.$return['addons_dir'].'/home/index';
				$addons_url=url($strurl);
				$all_url=getweburl($addons_url);
				$addonshtml=curl_post($all_url);
			    echo $addonshtml;
			  }else{
			    //echo("插件标签解析错误:插件（{$name}）不存在！");			
			 }
		     return $return;
	  }	


}