<?php


error_reporting (E_ALL & ~E_NOTICE & ~E_WARNING);
set_time_limit(0);

function template_complie($tplname,$mod='',$isprompt=0)
{
	global $LA;
	$LA['lang']=$LA['lang']?$LA['lang']:'cn';
	$project=$isprompt?'prompt':$LA['template'];

	$mod=str_replace(array('//'),array('/'),$mod);
	$mod=$mod?$mod.'/':'';

	$tplfile=TPL_ROOT.$LA['lang'].'/'.$project.'/'.$mod.$tplname.'.html';


	if(!is_file($tplfile))
	{
		fatal_error('该模板方案下的模板文件'.$tplfile.'不完整!','t1001');
	}

	$tplcon=file_get_contents($tplfile);

	if(!is_dir(TPL_CACHEPATH.$LA['lang'].'/'))
	{
		@mkdir(TPL_CACHEPATH.$LA['lang'].'/',0777);
	}

	if(!is_dir(TPL_CACHEPATH.$LA['lang'].'/'.$project.'/'))
	{
		@mkdir(TPL_CACHEPATH.$LA['lang'].'/'.$project.'/',0777);
	}

	if(!is_dir(TPL_CACHEPATH.$LA['lang'].'/'.$project.'/'.dirname($mod)))
	{
		@mkdir(TPL_CACHEPATH.$LA['lang'].'/'.$project.'/'.dirname($mod),0777);
	}

	if(!is_dir(TPL_CACHEPATH.$LA['lang'].'/'.$project.'/'.$mod))
	{
		@mkdir(TPL_CACHEPATH.$LA['lang'].'/'.$project.'/'.$mod,0777);
	}

	$compliedfile=TPL_CACHEPATH.$LA['lang'].'/'.$project.'/'.$mod.$tplname.'.tlp.php';
	$tplcon=template_parse($tplcon);

	$strlen=@file_put_contents($compliedfile,$tplcon);
	@chmod($compliedfile,0777);
	return $strlen;
}

function template_parse($str)
{
	global $usermodule;
	$str=preg_replace('/\{tlp\s+(.+)\}/i','<?php include template(\'\\1\');?>',$str); 
	$str=preg_replace('/\{include\s+(.+)\}/i','<?php include(\\1);?>',$str);
	$str=preg_replace('/\{mydc:([0-9a-z_]+)\}/i','<?php echo $r[\'\\1\'];?>',$str);
	$str=preg_replace('/mydc:([0-9a-z_]+)/i','$r[\'\\1\']',$str);
	$str=preg_replace('/\{myad:([0-9]+)\}/i','<script language="javascript" src="'.LA_PATH.'api/adv.php?id=\\1"></script>',$str);
	$str=preg_replace('/\{code\s+(.+)\}/','<?php \\1?>',$str);

	$str=preg_replace('/\{(\$[a-z0-9_\+\'\"\[\]\x7f-\xff\$]+)\}/i','<?php echo \\1;?>',$str);
	$str=preg_replace('/\{if\s+([^\}]+)\}/i','<?php if(\\1) { ?>',$str);
	$str=preg_replace('/\{else\s*if\s+([^\}]+)\}/i','<?php }elseif(\\1){ ?>',$str);
	$str=preg_replace('/\{else\}/i','<?php }else{ ?>',$str);
	$str=preg_replace('/\{\/if\}/i','<?php }?>',$str);
	$str=preg_replace('/\{loop\s+(\S+)\s+(\S+)\}/i','<?php $no=1;if(is_array(\\1))foreach(\\1 as \\2){?>',$str);
	$str=preg_replace('/\{loop\s+(\S+)\s+(\S+)\s+(\S+)\}/i','<?php $no=1;if(is_array(\\1))foreach(\\1 as \\2=>\\3){?>',$str);
	$str=preg_replace('/\{\/loop\}/i','<?php $no++;}?>',$str);
	$str=preg_replace('/\{([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff:]*\(([^{}]*)\))\}/','<?php echo \\1;?>',$str);
	
	$str=preg_replace('/\{NIUBI:category\s+([^\}]+)\}/ie',"la_call_user_func('get_category_tag','\\1')",$str);
	$str=preg_replace('/\{\/NIUBI:category\}/i',"<?php }unset(\$_DATA);?>",$str);

	$str=preg_replace('/\{NIUBI:nav\s+([^\}]+)\}/ie',"la_call_user_func('get_nav_tag','\\1')",$str);
	$str=preg_replace('/\{\/NIUBI:nav\}/i',"<?php }unset(\$_DATA);?>",$str);

	$str=preg_replace('/\{NIUBI:page\s+([^\}]+)\}/ie',"la_call_user_func('get_page_tag','\\1')",$str);
	$str=preg_replace('/\{\/NIUBI:page\}/i',"<?php }unset(\$_DATA);?>",$str);

	$str=preg_replace('/\{NIUBI:content\s+([^\}]+)\}/ie',"la_call_user_func('get_tag','\\1')",$str);
	$str=preg_replace('/\{\/NIUBI:content\}/i',"<?php }unset(\$_DATA); ?>",$str);

	$str=preg_replace('/\{NIUBI:comment\s+([^\}]+)\}/ie',"la_call_user_func('get_comment_tag','\\1')",$str);
	$str=preg_replace('/\{\/NIUBI:comment\}/i',"<?php }unset(\$_DATA); ?>",$str);

	$str=preg_replace('/\{NIUBI:list\s+([^\}]+)\}/ie',"la_call_user_func('get_list_tag','\\1')",$str);
	$str=preg_replace('/\{\/NIUBI:list\}/i',"<?php } \$dir_page=\$_DATA['pagestring'];unset(\$_DATA); ?>",$str);
	
	$str=preg_replace('/\{NIUBI:pagelist\s+listsize=[\'\"]?([0-9]+)[\'\"]?\}/i',"<?php \$_DATA=listpage(\$typeid,\$moduleid,\\1,\$page);@extract(\$_DATA); ?>",$str);
	$str=preg_replace('/\{\/NIUBI:pagelist\}/i',"<?php unset(\$_DATA); ?>",$str);

	/*
		导入模块模板解析文件
	*/

	if($usermodule && is_array($usermodule))
	{
		foreach($usermodule as $mod)
		{
			if(function_exists('parse_'.$mod['folder'].'_template'))
			{
				$str=call_user_func('parse_'.$mod['folder'].'_template',$str);
			}
		}
	}

	$str=preg_replace('/\{NIUBI:([0-9a-z_]+)\s+([^\}]+)\}([^\{]+)\{\/NIUBI:([0-9a-z_]+)\}/is',"<p style='text-align:center'>该模块已被卸载/禁用</p>",$str);
	return $str;
}

function get_comment_tag($para)
{
	/*
		设置区块默认参数
	*/
	$args=array(
				'contentid'=>'0',
				'moduleid'=>'0',
				'limit'=>'0',
				'row'=>'0');
	foreach($para as $key => $arg)
	{
		if(isset($args[$key]))
		{
			$args[$key]=$arg;
		}
	}
	extract($args);
	$mod=!$mod?0:array_map('intval',explode(',',$mod));
	$type=in_array($type,array('top','son','self'))?$type:'top';
	$row=intval($row)>0?intval($row):10;
	return '<?php $_DATA=get_comment_data('.$limit.','.$contentid.','.$moduleid.','.$row.');foreach($_DATA as $no => $r)if(is_array($r)){?>';
}

function get_comment_data($limit,$contentid,$moduleid,$row)
{
	global $cacheobj,$db,$siteidobj,$conobj;
	
	$result=$_DATA=array();
	$contentid=intval($contentid)?intval($contentid):0;
	$limit=intval($limit)?intval($limit):0;
	$row=intval($row)?intval($row):99;
	$moduleid=intval($moduleid)?intval($moduleid):0;

	if(SITETYPE && $_SESSION['siteid'])
	{
		$where='siteid IN('.implode(',',$siteidobj->getchildid($_SESSION['siteid'])).') AND status=1';
	}
	else
	{
		$where='status=1';
	}
	
	$where.=$moduleid?' AND moduleid='.$moduleid:'';

	$where.=$contentid?' AND contentid='.$contentid:'';
	
	$sql="SELECT * FROM `".LA_PRE."comment` WHERE $where ORDER BY `".LA_PRE."comment`.`id` ASC LIMIT $limit,$row";

	$data=$cacheobj->get($sql);
	if(!$data)
	{
		$data=$db->fetch_all($sql);
		if($data)
		{
			$cacheobj->set($sql,$data);
		}
	}
	return $data;
}

function get_nav_tag($para)
{
	/*
		设置区块默认参数
	*/
	$args=array(
				'typeid'=>'1',
				'parentid'=>'0',
				'limit'=>'0',
				'row'=>'0');
	foreach($para as $key => $arg)
	{
		if(isset($args[$key]))
		{
			$args[$key]=$arg;
		}
	}
	extract($args);
	$row=intval($row)>0?intval($row):20;
	return '<?php $_DATA=get_nav_data('.$typeid.','.$parentid.','.$limit.','.$row.');foreach($_DATA as $no => $r)if(is_array($r)){?>';
}

function get_nav_data($typeid,$parentid,$limit,$row)
{
	global $cacheobj,$db,$siteidobj,$conobj,$LA;
	
	$result=$_DATA=array();
	$typeid=intval($typeid)?intval($typeid):1;
	$parentid=intval($parentid)?intval($parentid):0;
	$limit=intval($limit)?intval($limit):0;
	$row=intval($row)?intval($row):99;

	if(SITETYPE && $_SESSION['siteid'])
	{
		$where='siteid IN('.implode(',',$siteidobj->getchildid($_SESSION['siteid'])).') AND (template=\'\' OR template=\''.$LA['template'].'\')';
	}
	else
	{
		$where='(template=\'\' OR  template=\''.$LA['template'].'\')';
	}
	
	$where.=$typeid?' AND typeid='.$typeid:'';

	$where.=$parentid?' AND parentid='.$parentid:' AND parentid=0';
	
	$sql="SELECT * FROM `".LA_PRE."nav` WHERE $where ORDER BY `".LA_PRE."nav`.`orderby` ASC LIMIT $limit,$row";

	$data=$cacheobj->get($sql);
	if(!$data)
	{
		$data=$db->fetch_all($sql);
		if($data)
		{
			$cacheobj->set($sql,$data);
		}
	}
	return $data;
}

function get_page_tag($para)
{
	/*
		设置区块默认参数
	*/
	$args=array(
				'typeid'=>'1',
				'limit'=>'0',
				'row'=>'0');
	foreach($para as $key => $arg)
	{
		if(isset($args[$key]))
		{
			$args[$key]=$arg;
		}
	}
	extract($args);
	$row=intval($row)>0?intval($row):20;
	return '<?php $_DATA=get_page_data('.$typeid.','.$limit.','.$row.');foreach($_DATA as $no => $r)if(is_array($r)){?>';
}

function get_page_data($typeid,$limit,$row)
{
	global $cacheobj,$db,$siteidobj,$conobj;
	
	$result=$_DATA=array();
	$typeid=intval($typeid)?intval($typeid):0;
	$limit=intval($limit)?intval($limit):0;
	$row=intval($row)?intval($row):99;

	
	if(SITETYPE && $_SESSION['siteid'])
	{
		$where='siteid IN('.implode(',',$siteidobj->getchildid($_SESSION['siteid'])).')';
	}
	else
	{
		$where='1';
	}
	
	$where.=$typeid?' AND typeid='.$typeid:'';
	
	$sql="SELECT * FROM `".LA_PRE."page` WHERE $where ORDER BY `".LA_PRE."page`.`id` ASC LIMIT $limit,$row";

	$data=$cacheobj->get($sql);
	if(!$data)
	{
		$data=$db->fetch_all($sql);
		if($data)
		{
			$cacheobj->set($sql,$data);
		}
	}
	return $data;
}

function get_category_tag($para)
{
	/*
		设置区块默认参数
	*/
	$args=array(
				'catid'=>'0',
				'moduleid'=>'0',
				'limit'=>'0',
				'parentid'=>'0',
				'row'=>'0',
				'type'=>'top');
	foreach($para as $key => $arg)
	{
		if(isset($args[$key]))
		{
			$args[$key]=$arg;
		}
	}
	extract($args);
	$mod=!$mod?0:array_map('intval',explode(',',$mod));
	$type=in_array($type,array('top','son','self'))?$type:'top';
	$row=intval($row)>0?intval($row):10;
	return '<?php $_DATA=get_category_data('.$limit.','.$catid.','.$moduleid.','.$parentid.',\''.$type.'\','.$row.');foreach($_DATA as $no => $r)if(is_array($r)){?>';
}

function get_category_data($limit,$catid,$moduleid,$parentid,$type,$row)
{
	global $cacheobj,$db,$siteidobj,$conobj;
	
	$result=$_DATA=array();
	$catid=intval($catid)?intval($catid):0;
	$parentid=intval($parentid)?intval($parentid):0;
	$limit=intval($limit)?intval($limit):0;
	$row=intval($row)?intval($row):99;
	$moduleid=intval($moduleid)?intval($moduleid):0;

	if(SITETYPE && $_SESSION['siteid'])
	{
		$where='siteid IN('.implode(',',$siteidobj->getchildid($_SESSION['siteid'])).')';
	}
	else
	{
		$where='1';
	}
	
	$where.=$moduleid?' AND moduleid='.$moduleid:'';

	if($type=='top')
	{
		$where.=' AND parentid=0';
	}
	else if($type=='self')
	{
		$where.=' AND parentid='.$conobj->typeparentid($parentid);
	}
	else if($type=='son')
	{
		$where.=' AND parentid='.$parentid;
	}
	
	$sql="SELECT * FROM `".LA_PRE."type` WHERE $where ORDER BY `".LA_PRE."type`.`orderby` ASC LIMIT $limit,$row";

	$data=$cacheobj->get($sql);
	if(!$data)
	{
		$data=$db->fetch_all($sql);
		if($data)
		{
			$cacheobj->set($sql,$data);
		}
	}
	return $data;
}

function get_list_tag($para)
{
	/*
		设置区块默认参数
	*/
	$args=array('catid'=>'$typeid',
				'moduleid'=>'$moduleid',
				'modelid'=>'$modelid',
				'row'=>'10',
				'orderby'=>'\'updatetime\'',
				'orderbyway'=>'\'desc\'',
				'ismore'=>'0',
				'page'=>'$page',
				'siteid'=>'0',
				'userid'=>'all');
	unset($para['catid'],$para['page']);
	foreach($para as $key => $arg)
	{
		if(isset($args[$key]))
		{
			$args[$key]=strpos($arg,'$')===false && !is_numeric($arg) ?'\''.$arg.'\'':$arg;
		}
	}
	$args=implode(',',$args);
	return '<?php $_DATA=call_user_func(\'get_list_tag_data\','.$args.');foreach($_DATA as $no => $r)if(is_array($r)){?>';
}

function get_list_tag_data($catid,$moduleid='0',$modelid='0',$row="10",$orderby="updatetime",$orderbyway='desc',$ismore="0",$page=0,$siteid=0,$userid="all")
{
	global $db,$cacheobj,$siteidobj,$modelobj;
	$row=intval($row)?intval($row):1;
	$page=max(intval($page),1);

	$orderbyarr=explode(" ",trim($orderby));

	$orderby=$orderbyarr[0];
	$orderbyway=isset($orderbyarr[1]) && $orderbyarr[1]?$orderbyarr[1]:$orderbyway;
	
	$orderby=' ORDER BY '.$orderby.' '.$orderbyway;

	if(SITETYPE && $_SESSION['siteid'])
	{
		$where='a.siteid IN('.implode(',',$siteidobj->getchildid($_SESSION['siteid'])).') AND a.status=1 AND a.isdeleted=0 AND a.ishidden=0';
	}
	else
	{
		$where='a.status=1 AND a.isdeleted=0 AND a.ishidden=0';
	}

	cache_write('type-listsize'.$catid.'.cache.php',array($catid=>$row),SYSTEM_ROOT.'data/tmp/');
	if(intval($catid))
	{
		$catid=intval($catid)?intval($catid):0;
		$where.=' AND a.typeid IN('.implode(',',array_unique(getchildtypeid($catid))).')';
	}

	$where.=$userid!='all'?' AND a.userid ='.intval($userid):'';

	if($modelid && $ismore)
	{
		$modelinfo=$modelobj->info($modelid);
		if($modelinfo)
		{
			$sql="SELECT * FROM ".LA_PRE."content a ,".LA_PRE.$modelinfo['tbname']." c WHERE a.contentid=c.id AND ".$where.$orderby;
		}
		else
		{
			$sql="SELECT * FROM ".LA_PRE."content a WHERE ".$where.$orderby;
		}	
	}
	else
	{
		$sql="SELECT * FROM ".LA_PRE."content a WHERE ".$where.$orderby;
	}

	$count_sql=preg_replace("/^SELECT([^(]+)\s*FROM(.+)(ORDER BY.+)$/i", "SELECT COUNT(*) AS `count` FROM\\2", $sql);

	$count=get_cache_counts($count_sql); 
	$pagecount=max(ceil($count/$row),1);
	$page=$page>$pagecount?$pagecount:$page;
	$offset=($page-1)*$row;
	$offset=!$offset&&$limit?$limit:$offset;
	$sql.=' LIMIT '.$offset.','.$row;
	$data=$db->fetch_all($sql);
	return $data;
}

function get_tag($para)
{
	/*
		设置区块默认参数
	*/
	$args=array('catid'=>'$typeid',
				'siteid'=>'0',
				'modelid'=>'$modelid',
				'istopic'=>'-1',
				'istop'=>'-1',
				'isfocus'=>'-1',
				'moduleid'=>'0',
				'row'=>'10',
				'limit'=>'0',
				'withthumb'=>'0',
				'orderby'=>'\'updatetime\'',
				'orderbyway'=>'\'desc\'',
				'keyword'=>'\'\'',
				'ismore'=>'0',
				'userid'=>'\'all\'');
	foreach($para as $key => $arg)
	{
		if(isset($args[$key]))
		{
			$args[$key]=strpos($arg,'$')===false && !is_numeric($arg) ?'\''.$arg.'\'':$arg;
		}
	}
	$args=implode(',',$args);
	return '<?php $_DATA=call_user_func(\'get_tag_data\','.$args.');foreach($_DATA as $no => $r)if(is_array($r)){$r[\'lianiren\']=$r[\'contactuser\'];?>';
}

function get_tag_data($catid,$siteid="0",$modelid="0",$istopic="-1",$istop="-1",$isfocus="-1",$moduleid="0",$row="10",$limit=0,$withthumb="0",$orderby="updatetime",$orderbyway='desc',$keyword="",$ismore="0",$userid="all")
{
	global $db,$cacheobj,$siteidobj,$modelobj;
	$limit=intval($limit);
	$offset=$limit?$limit:0;
	$row=intval($row)?intval($row):1;
	$moduleid=intval($moduleid)?intval($moduleid):0;

	$modelid=intval($modelid)?intval($modelid):0;
	$siteid=intval($siteid)?intval($siteid):0;
	
	$orderbyarr=explode(" ",trim($orderby));
	$orderby=$orderbyarr[0];
	$orderbyway=(isset($orderbyarr[1]) && $orderbyarr[1])?$orderbyarr[1]:$orderbyway;

	if($orderby=='rand')
	{
		$orderby=' ORDER BY RAND()';
	}
	else
	{
		$orderby=' ORDER BY '.$orderby.' '.$orderbyway;
	}
	if(SITETYPE && $_SESSION['siteid'])
	{
		$where='a.siteid IN('.implode(',',$siteidobj->getchildid($_SESSION['siteid'])).') AND a.status=1 AND a.isdeleted=0 AND a.ishidden=0';
	}
	else
	{
		$where='a.status=1 AND a.isdeleted=0 AND a.ishidden=0';
	}
	
	$where.=$moduleid?' AND a.moduleid='.intval($moduleid):'';
	
	if($istopic==-1)
	{
		$where.='';
	}
	else if($istopic==0)
	{
		$where.=' AND (a.istopic='.intval($istopic).' OR a.istopic<'.TIME.')';
	}
	else
	{
		$where.=' AND a.istopic>='.TIME;
	}

	if($istop==-1)
	{
		$where.='';
	}
	else if($istop==0)
	{
		$where.=' AND (a.istop='.intval($istop).' OR a.istop<'.TIME.')';
	}
	else
	{
		$where.=' AND a.istop>='.TIME;
	}

	if($isfocus==-1)
	{
		$where.='';
	}
	else if($isfocus==0)
	{
		$where.=' AND (a.isfocus='.intval($isfocus).' OR a.isfocus<'.TIME.')';
	}
	else
	{
		$where.=' AND a.isfocus>='.TIME;
	}

	$where.=$userid!='all'?' AND a.userid ='.intval($userid):'';
	$where.=intval($withthumb)?' AND a.thumb!=\'\'':'';

	if($keyword)
	{
		$keyword=str_replace('，',',',str_replace(' ',',',$keyword));
		$kw=explode(",",$keyword);
		$kw=$kw?$kw[mt_rand(0,sizeof($kw))]:'';
		$where.=$kw?' AND a.keywords LIKE \'%'.strip_tags($kw).'%\'':'';
	}

	if($catid!='all' && trim($catid))
	{
		$catid=str_replace('，',',',$catid);
		if(strpos($catid,','))
		{
			$recatid=$catid=array_map('intval',explode(',',$catid));
			foreach($catid as $_catid)
			{	
				$r=getchildtypeid($_catid);
				foreach($r as $value)
				{
					$value=intval($value);
					if($value)
					{
						$recatid[]=$value;
					}
				}
			}

			$catid=implode(',',array_unique($recatid));
			$where.=' AND a.typeid IN ('.$catid.')';
		}
		else
		{
			$catid=intval($catid)?intval($catid):0;
			$where.=' AND a.typeid IN('.implode(',',array_unique(getchildtypeid($catid))).')';
		}
	}

	
	if($modelid && $ismore)
	{
		$modelinfo=$modelobj->info($modelid);
		if($modelinfo)
		{
			$sql="SELECT * FROM ".LA_PRE."content a ,".LA_PRE.$modelinfo['tbname']." c WHERE a.contentid=c.id AND ".$where.$orderby;
		}
		else
		{
			$sql="SELECT * FROM ".LA_PRE."content a WHERE ".$where.$orderby;
		}	
	}
	else
	{
		$sql="SELECT * FROM ".LA_PRE."content a WHERE ".$where.$orderby;
	}
	$sql.=' LIMIT '.$offset.','.$row;

	$data=$cacheobj->get($sql);
	if(!$data)
	{
		$data=$db->fetch_all($sql);
		if($data)
		{
			$cacheobj->set($sql,$data);
		}
	}
	return $data;
}
?>
