<?php
!defined("MONKEYMAO") && die("Accessed Defined!");


function parse_theme($file, $tpldir, $addon){
	global $lang;
	$nest = 5;
	$tplfile = MODEPATH."./$tpldir/$file.htm";
	$objfile = MODEPATH."./cache/themes/{$addon}_$file.tpl.php";
	if(!@$fp = fopen($tplfile, 'r')){		
		mexit("Current theme file './$tpldir/$file.htm' not found or have no access!");
	}elseif(!@include lang('themes', $tpldir)) {
		mexit("<br />Current template pack do not have a necessary language file 'themes.lang.php' or have syntax error!");
	}
		
	$code = fread($fp, filesize($tplfile));
	fclose($fp);

	$var_regexp = "((\\\$[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)(\[[a-zA-Z0-9_\-\.\"\'\[\]\$\x7f-\xff]+\])*)";
	$const_regexp = "([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)";
	$re=array(
		"/[\n\r\t]*\<title\>[\n\r]*(.+?)[\n\r]*\<\/title\>[\n\r\t]*/is", 
		"/([\n\r]+)\t+/s",
		"/\<\!\-\-\{(.+?)\}\-\-\>/s",
		"/\{lang\s+(.+?)\}/ies", 		
		"/\{(\\$[a-zA-Z0-9_\[\]''\$\.\x7f-\xff]+)\}/s",
		"/$var_regexp/es",
		"/\<\?\=\<\?\=$var_regexp\?\>\?\>/es",
		"/[\n\r\t]*\[list\s+(.+?)\][\n\r]*(.+?)[\n\r]*\[\/list\][\n\r\t]*/ies",
		"/[\n\r\t]*\[sort\][\n\r]*(.+?)[\n\r]*\[\/sort\][\n\r\t]*/ies",
		"/[\n\r\t]*\[subsort\][\n\r]*(.+?)[\n\r]*\[\/subsort\][\n\r\t]*/ies",
		"/[\n\r\t]*\[attach\][\n\r]*(.+?)[\n\r]*\[\/attach\][\n\r\t]*/ies",
		"/[\n\r\t]*\[links\s+(.+?)\][\n\r]*(.+?)[\n\r]*\[\/links\][\n\r\t]*/ies",
		"/[\n\r\t]*\{theme\s+(\S+)\s+(\S+)\s+(\S+)\}[\n\r\t]*/is",
		"/[\n\r\t]*\{theme\s+([a-z0-9_]+)\}[\n\r\t]*/is",
		"/[\n\r\t]*\{theme\s+(.+?)\}[\n\r\t]*/is",
		"/[\n\r\t]*\{ad\s+([a-z0-9_]+)\}[\n\r\t]*/is",
		"/[\n\r\t]*\{func\s+(.+?)\}[\n\r\t]*/ies",
		"/[\n\r\t]*\{echo\s+(.+?)\}[\n\r\t]*/ies",
		"/[\n\r\t]*\<\!\-\-php\s+(.+?)\-\-\>[\n\r\t]*/ies",
	);
	$p=array(
		"<title>\\1 - Powered by Piccms!</title>",
		"\1",
		"{\\1}",
		"langvar('\\1')",

		"<?=\\1?>",
		"addquote('<?=\\1?>')",
		"addquote('<?=\\1?>')",
			"listconvert('\\1','\\2')",
			"sortconvert('\\1')",
			"sortconvert('\\1',1)",
			"attach('\\1')",
			"linkconvert('\\1','\\2')",
			"\n<?php include theme('\\1','\\2','\\3'); ?>\n",
		"\n<?php include theme('\\1'); ?>\n",
		"\n<?php include theme('\\1'); ?>\n",
		"<script language=\"JavaScript\" type=\"text/javascript\" src=\"/go.php?aid=\\1\"></script>",	
		"stripvtags('\n<?php \\1 ?>\n','')",
		"stripvtags('<?php echo \\1; ?>','')",
		"stripvtags('\n<?php \\1 ?>\n','')",
		);
	$code = "<? !defined('MODEPATH') && exit('Access Denied'); ?>\n\n$code";
	$code = preg_replace("/([\n\r]+)\t+/s", "\\1", $code);
	$code = str_replace("\n\n", "\n", $code);
	$code = str_replace("\r\r", "\r", $code);
	$code = preg_replace($re, $p, $code);

	for($i = 0; $i < $nest; $i++) {
		$code = preg_replace("/[\n\r\t]*\<\!\-\-loop\s+(\S+)\s+(\S+)\-\-\>[\n\r]*(.+?)[\n\r]*\<\!-\-\/loop\-\-\>[\n\r\t]*/ies", "stripvtags('\n<? if(is_array(\\1)) { foreach(\\1 as \\2) { ?>','\n\\3\n<? } } ?>\n')", $code);
		$code = preg_replace("/[\n\r\t]*\<\!\-\-loop\s+(\S+)\s+(\S+)\s+(\S+)\-\-\>[\n\r\t]*(.+?)[\n\r\t]*\<\!\-\-\/loop\-\-\>[\n\r\t]*/ies", "stripvtags('\n<? if(is_array(\\1)) { foreach(\\1 as \\2 => \\3) { ?>','\n\\4\n<? } } ?>\n')", $code);
	}
	$code = preg_replace("/\{$const_regexp\}/s", "<?=\\1?>", $code);
	$code = preg_replace("/ \?\>[\n\r]*\<\? /s", " ", $code);
	if(!@$fp = fopen($objfile, 'w')) {
		mexit("Directory './cache/themes/' not found or have no access!");
	}
	flock($fp, 2);
	fwrite($fp, $code);
	fclose($fp);
}
function addquote($var) {
	return str_replace("\\\"", "\"", preg_replace("/\[([a-zA-Z0-9_\-\.\x7f-\xff]+)\]/s", "['\\1']", $var));
}
function stripvtags($expr, $statement) {
	//$expr = str_replace("\\\"", "\"", preg_replace("/\<\?\=(\\\$[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\"\'\[\]\$\x7f-\xff]*)\?\>/s", "\\1", $expr));
	$expr = str_replace("\\\"", "\"", preg_replace("/\<\?\=(\\\$.+?)\?\>/s", "\\1", $expr));
	$statement = str_replace("\\\"", "\"", $statement);
	return $expr.$statement;
}

function langvar($var) {
		return isset($GLOBALS['lang'][$var]) ? $GLOBALS['lang'][$var] : "!$var!";
}
function listconvert($tags='',$htmls=''){
	if(!$tags) {
		return false;
	}
		list($id,$num,$cuttitle,$order,$listpage)=explode(',',$tags);
		$id = intval($id);
		$num = intval($num);
		$cuttitle = intval($cuttitle);
		$order = intval($order);
		$listpage = intval($listpage);
		$sql = $text = '';
		
		$text .= $listpage ? '<!-- [pagesize:'.$num.'] -->'."\n" : '';
		$text .= '<?php ';
		$text .= '$sql = \'\';'."\n";		
		if($id) {
			$sql = " AND p.id='$id' ";
		}else{

			$text .= 'if($id || $sort[\'id\']) {'."\n"
				  //.'$sql = $sort[\'id\'] ? " AND p.id=\'".$sort[\'id\']."\' " : " AND p.id=\'$id\' ";'."\n"
				  .'$sql = $sort[\'id\'] ? Getpicsort($sort[\'id\']) : Getpicsort($id);'."\n"
				  .'$sql = " AND $sql ";'."\n"
				  .' } '."\n";
		}
		if(!$num) {
			$num = 10;
		}
		
		switch($order) {
			case 1:
				$sql .=" ORDER BY p.views DESC";
			break;
			case 2:
				$sql .="AND p.digest='1' ORDER BY p.postime DESC";
			break;
			case 3:
				$sql .="AND p.digest='1' ORDER BY p.views DESC";
			break;
			case 4:
				$sql .=" ORDER BY rand() DESC";
			break;
			case 5:
				$sql .=" ORDER BY ding DESC";
			break;
			
			default:
				$sql .=" ORDER BY p.postime DESC";
			break;
		}

		if($listpage) {		
			$text .='$page = ispage($page) ? $page : 1;'."\n"
			.'$start_limit = ($page-1) * '.$num.';'."\n"
			.'$infoquery = $db -> query("SELECT COUNT(*) FROM {$tablepre}pic p WHERE 1 $sql '.$sql.'");'."\n"
			.'$lines = $db -> result($infoquery, 0);'."\n"
			.'$nextpage = $backpage = $lastpage=\'#\';'."\n"
			.'if($pages > $page) {'."\n"
			.'$lastpage = \'list_\'.$pages.\'.html\';'."\n"
			.'$nextpage = \'list_\'.($page+1).\'.html\';'."\n"
			.'}'."\n"
			.'if($page > 1) {'
			.'$backpage = \'list_\'.($page-1).\'.html\';'
			.'}';

			$sql .=' LIMIT $start_limit, '.$num;
		}else{
			$sql .= ' LIMIT '.$num;
		}
	//[list 分类，数量，标题字数，排列方式，分页数量][/list]

	$text .='$infoquery = $db -> query("SELECT p.*,s.sortname,s.folderdir FROM {$tablepre}pic p LEFT JOIN {$tablepre}picsort s ON s.id=p.id WHERE 1 $sql '.$sql.'");'."\n"
	.'while($info = $db -> fetch_array($infoquery)) {'."\n";
	if($cuttitle) {
		$text.='$info[\'pname\'] =textcut($info[\'pname\'],'.$cuttitle.');'."\n";
	}
	$text.='$info[\'postime\'] =gmdate("$dateformat",$info[\'postime\'] + $timeoffset * 3600);'."\n";
	$text.='?>';
	$tagarray = array('pid', 'id', 'pname', 'face', 'views', 'digest', 'postime', 'attachment', 'about','sortname');

	foreach($tagarray AS $tag) {
		$htmls = str_replace('['.$tag.']','<?=$info[\''.$tag.'\']?>',$htmls);
	}
	$htmls = str_replace('[htmlurl]','<?=$info[\'folderdir\']?>',$htmls);
	$htmls = stripslashes($htmls);
	$text .= $htmls;
	$text .= '<?php }?>'."\n";


//[pid]文章ID
//[id]所属分类ID
//[pname]文章名称
//[sortname]所属分类名称
//[htmlurl]HTML存放目录
//[face]缩略图
//[views] 点击次数
//[digest]是否推荐
//[postime]发表时间
//[about] 简介内容



//exit($text);
	return $text;
}

function sortconvert($htmls,$issub=0){
	//id  upid  sortname  folders  folderdir  ordermode 
	$text = $add='';
	$text.='<?php $sql = \'\';?>';
	if($issub) {		
		$text.='<?php if($id || $sort[\'id\']) {'
		.'	$sql = $sort[\'id\'] ? "WHERE upid=\'$sort[id]\' " : "WHERE upid=\'$id\' ";'
		.'}else{'
		.'	$sql = "WHERE upid=\'0\' ";'
		.'}?>';
		
	}else{
		$add = "WHERE upid='0' ";
	}
	$text.='<?php $query = $db -> query("SELECT * FROM {$tablepre}picsort '.$add.' $sql ORDER BY ordermode");'."\n"
	.'while($sort = $db -> fetch_array($query)) { ?>'."\n";
	$tags = array('[id]', '[upid]', '[sortname]', '[folders]', '[folderdir]', '[ordermode]');
	$values = array('<?=$sort[\'id\']?>', '<?=$sort[\'upid\']?>', '<?=$sort[\'sortname\']?>', '<?=$sort[\'folders\']?>', '<?=$sort[\'folderdir\']?>', '<?=$sort[\'ordermode\']?>');	
	$text.=stripslashes(str_replace($tags, $values, $htmls));
	$text.='<?php } ?>';
	return $text;
}

function attach($htmls) {
	//uid  pid  mid  type  filename  filesize  filetype  face  refile  attachment  description  uptime  
		$text = '';
	$text .='<?php foreach($attachs AS $key => $attach) { ?>';
	$tags = array('[uid]', '[pid]', '[mid]', '[type]', '[filename]', '[filesize]', '[filetype]', '[face]', '[attachment]', '[description]', '[uptime]');

	$values = array('<?=$attach[\'uid\']?>', '<?=$attach[\'pid\']?>', '<?=$attach[\'mid\']?>', '<?=$attach[\'type\']?>', '<?=$attach[\'filename\']?>', '<?=$attach[\'filesize\']?>', '<?=$attach[\'filetype\']?>', '<?=$attach[\'face\']?>', '<?=$attach[\'attachment\']?>', '<?=$attach[\'description\']?>', '<?=$attach[\'uptime\']?>');
	$text.=stripslashes(str_replace($tags, $values, $htmls));
	$text .='<?php }?>';
	return $text;

}

function linkconvert($type,$htmls){
	$text = '';
	$tags = array('[lid]', '[type]', '[linksite]', '[linkurl]', '[linknote]', '[logo]', '[ordermode]', '[postime]');
	$values = array('<?=$link[\'lid\']?>', '<?=$link[\'type\']?>', '<?=$link[\'linksite\']?>', '<?=$link[\'linkurl\']?>', '<?=$link[\'linknote\']?>', '<?=$link[\'logo\']?>', '<?=$link[\'ordermode\']?>', '<?=$link[\'postime\']?>');
	$htmls=stripslashes(str_replace($tags, $values, $htmls));
	$text.= '<?php $query = $db -> query("SELECT * FROM {$tablepre}links WHERE type=\'1\' ORDER BY ordermode");';
	$text.= 'while($link = $db -> fetch_array($query)) {';
		if($type == 'logo') {
			$text.='if($link[\'logo\']){?> '.$htmls.' <?php }';
		}else{
			$text.='if(!$link[\'logo\']){?> '.$htmls.' <?php }';
		}

	
	$text .='}?>';
	//lid  type  linksite  linkurl  linknote  logo  ordermode  postime  
	return $text;
}
?>