<?php
/*******************************************************************************************
' Software name: DJCMS Content Management System
' Version:3.0
' Web: http://www.djcms.net
' Author: 心情(qq:1130731)
' Copyright (C) 2009-2010 DJCMS官方 版权所有
' 法律申明：DJCMS程序所有代码100%原创、未引入任何网上代码,对一切抄袭行为、坚决严肃追究法律责任
'*******************************************************************************************/
defined('IN_DJCMS') or exit('Access Denied');

function alertMsg($str, $url) {
	$urlstr='';
	if (!empty($url)) $urlstr="location.href='$url';";
	if (!empty($str)) $str="alert('$str');";
	echo "<script>$str$urlstr</script>";
}

function echoMsgAndGo($str, $timenum, $bhome) {
	echo $str.", <font color=\"red\">".$timenum."</font> 秒后自动返回...<script language=\"javascript\">setTimeout(\"goLastPage()\",".($timenum*1000).");function goLastPage(){history.go(-1);}</script>";
	if ($bhome) echo "&nbsp;&nbsp;<a href='/' target='_self'>进入网站首页</a> Powered By ".siteName;
	exit;
}

function selectMsg($str, $url1, $url2) {
	echo("<script>if(confirm('".$str."')){location.href='".$url1."'}else{location.href='".$url2."'}</script>");
}

function last() {
	echo("<script>history.go(-1)</script>");
}

function new_htmlspecialchars($string) {
	return is_array($string) ? array_map('new_htmlspecialchars', $string) : htmlspecialchars($string, ENT_QUOTES);
}

function new_addslashes($string, $force = 1) {
	if(is_array($string)) {
		foreach($string as $key => $val) {
			unset($string[$key]);
			$string[addslashes($key)] = new_addslashes($val, $force);
		}
	} else {
		$string = addslashes($string);
	}
	return $string;
}

function new_stripslashes($string) {
	if(is_array($string)) {
		foreach($string as $key => $val) {
			$string[$key] = new_stripslashes($val);
		}
	} else {
		$string = stripslashes($string);
	}
	return $string;
}

function getFileFormat($str) {
	$str = trim($str);$ext = "";
	if (!empty($str)) {
		if (strpos(" ".$str, "?") > 0) {
		    $strt = explode('?', $str);
		    $str = $strt[0];
		}
		$ps = preg_split("/\./", $str);
		$ext = '.'.$ps[count($ps)-1];
	}
	return $ext;
}

function getruleval($content,$str)
{
	if(!empty($content) && !empty($str)){
		$labelRule = buildregx("<".$str."(.*?)>(.*?)</".$str.">","is");
		preg_match_all($labelRule,$content,$ar);
		return $ar[0];
	}
}

function ExecTime() {
	$time = explode(" ", microtime());
	$usec = (double)$time[0];
	$sec = (double)$time[1];
	return $sec + $usec;
}

function echoErr($str, $id, $des) {
	$cssstr = "<style>body{text-align:center}#msg{background-color:white;border:1px solid #1B76B7;margin:0 auto;width:400px;text-align:left}.msgtitle{padding:3px 3px;color:white;font-weight:700;line-height:21px;height:25px;font-size:12px;border-bottom:1px solid #1B76B7; text-indent:3px; background-color:#1B76B7}#msgbody{font-size:12px;padding:40px 8px 50px;line-height:25px}#msgbottom{text-align:center;height:20px;line-height:20px;font-size:12px;background-color:#1b76b7;color:#FFFFFF}</style>" ;
	$errstr = $cssstr."<div id='msg'><div class='msgtitle'>提示：***【".$str."】***</div><div id='msgbody'>错误号：<b>".$id."</b><br>错误描述：<b>".$des."</b></div><div id='msgbottom'>Powered By ".siteName."</div></div>" ;
	die($errstr);
}

function getRunTime(){
	global $db,$pageRunStr,$starttime;
	$endtime=ExecTime();      
	return $pageRunStr[0].number_format(($endtime-$starttime), 4).$pageRunStr[1].$db->querynum.$pageRunStr[2];
}

function return_bytes($val) {
    $val = trim($val);
    $last = strtolower($val{strlen($val)-1});
    switch($last) {
        case 'g': $val *= 1024;
        case 'm': $val *= 1024;
        case 'k': $val *= 1024;
    }
    return $val;
}

function dsetcookie($key, $value, $life = 0, $httponly = false) {
	(!defined('COOKIEPATH')) && define('COOKIEPATH', '/');
	(!defined('COOKIEDOMAIN')) && define('COOKIEDOMAIN', '');

	if($value == '' || $life < 0) {
		$value = '';
		$life = -1;
	}
		
	$life = $life > 0 ? time() + $life : ($life < 0 ? time() - 31536000 : 0);
	$path = $httponly && PHP_VERSION < '5.2.0' ? COOKIEPATH."; HttpOnly" : COOKIEPATH;
	$secure = $_SERVER['SERVER_PORT'] == 443 ? 1 : 0;
	if(PHP_VERSION < '5.2.0') {
		setcookie($key, $value, $life, $path, COOKIEDOMAIN, $secure);
	} else {
		setcookie($key, $value, $life, $path, COOKIEDOMAIN, $secure, $httponly);
	}
}

function getcookie($key) {
	return isset($_COOKIE[$key]) ? $_COOKIE[$key] : '';
}

function dhtmlspecialchars($string) {
	if(is_array($string)) {
		foreach($string as $key => $val) {
			$string[$key] = dhtmlspecialchars($val);
		}
	} else {
		$string = preg_replace('/&amp;((#(\d{3,5}|x[a-fA-F0-9]{4}));)/', '&\\1',
		str_replace(array('&', '"', '<', '>'), array('&amp;', '&quot;', '&lt;', '&gt;'), $string));
	}
	return $string;
}

function getForm($k, $type='GP') {
	$type = strtolower($type);
	switch($type) {
		case 'get': $var = &$_GET; break;
		case 'post': $var = &$_POST; break;
		case 'cookie': $var = &$_COOKIE; break;
		default:
			if(isset($_GET[$k])) {
				$var = &$_GET;
			} else {
				$var = &$_POST;
			}
			break;
	}
	return isset($var[$k]) ? $var[$k] : NULL;
}

function dimplode($array) {
	if (!empty($array)) {
		return implode(',', is_array($array) ? $array : array($array));
	} else {
		return 0;
	}
}

//获取文件内容
function loadFile($filename) {
	if (!file_exists($filename)) {
		exit("文件".$filename."不存在! ");
	}
	$content = '';
	if(function_exists('file_get_contents')) {
		@$content = file_get_contents($filename);
	} else {
		if(@$fp = fopen($filename, 'r')) {
			@$content = fread($fp, filesize($filename));
			@fclose($fp);
		}
	}
	return $content;
}

function loadFileOnCache($fileFlag,$filePath) {
	$cacheName=$fileFlag.$filePath;
	if (cacheStart == 1) {
		if (!$loadFileOnCache = memory('get', $cacheName)) {
			$loadFileOnCache=loadFile($filePath);
			memory('set', $cacheName, $loadFileOnCache);
        }
	} else {
		$loadFileOnCache=loadFile($filePath);
	}
	return $loadFileOnCache;
}

function getKeywordsList($key, $span)
{
	$keyWordsStr = '';
	$keystr = str_replace("，",",",$key);
	if (strpos($keystr, ",") > 0) {
		$keyWordsArray = explode(",", $keystr);
	} else {
		$keyWordsArray = explode(" ", $keystr);
	}
	$len = count($keyWordsArray);
	for ($i = 0;$i < $len;$i++) {
		$keyWordsStr .= "<a href='/".sitePath."search.php?searchword=".$keyWordsArray[$i]."'>".$keyWordsArray[$i]."</a>".$span;
	}
	return $keyWordsStr;
}

function getDataCount($countType)
{
	switch ($countType)
	{
		case "all":
		    $number = getcount("data");
		break;
		case "day":
		    $number = getcount("data","DATE_FORMAT(FROM_UNIXTIME(m_addtime),'%Y-%m-%d') = DATE_FORMAT(NOW(),'%Y-%m-%d')");
		break;
	}
	return $number;
}

function getcount($tablename, $condition) {
	if(empty($condition)) {
		$where = '1';
	} elseif(is_array($condition)) {
		$where = DB::implode_field_value($condition, ' AND ');
	} else {
		$where = $condition;
	}
	$row = DB::fetch_first("SELECT COUNT(*) AS num FROM ".DB::table($tablename)." WHERE $where");
	return $row['num'];
}

function replaceStr($str, $finStr, $repStr)
{
	if (empty($str)) $str = "";
	return str_replace($finStr, $repStr, $str);
}

function buildregx($regstr, $regopt)
{
	return '/'.replaceStr($regstr, '/', '\/').'/'.$regopt;
}

function getPageSize($str, $ptype)
{
	$labelRule = buildregx("{djcms:".$ptype."list(.*?)size=([0-9]+)(.*?)}", "is");
	preg_match_all($labelRule, $str, $pzar);
	$getPageSize = trim(preg_replace("/[ \r\n\t\f]{1,}/"," ", $pzar[2][0]));
	if (empty($getPageSize)) $getPageSize = 10;
	return $getPageSize;
}

function getPageSizeOnCache($templatePath,$Flag,$Flag2)
{
	$cacheName=$Flag."_pagesize_".$Flag2;
	if (cacheStart == 1){
		if (!$pSize = memory('get', $cacheName)) {
            $pSize = getPageSize(loadFile($templatePath),$Flag);
			memory('set', $cacheName, $pSize);
        }
    }else{
		$pSize=getPageSize(loadFile($templatePath),$Flag);
	}
    return $pSize;
}

function filterStr($str,$filtertype){
	if (empty($str)) return "";
	switch($filtertype){
		case "html":
			$rulestr="(<[a-zA-Z!].*?>)|(<[\/][a-zA-Z].*?>)|(&\w+?;)";
		break;
		case "jsiframe":
			$rulestr="(<(script|iframe).*?>)|(<[\/](script|iframe).*?>)";
		break;
    }
	$outstr=preg_replace("/$rulestr/i","",$Str);
	return $outstr;
}

function getAgent()
{
	return $_SERVER['HTTP_USER_AGENT'];
}

function getRefer()
{
	$ref=getForm("REFERER","both");
	if (empty($ref)){
		$ref=$_SERVER['HTTP_REFERER'];
	}
	return $ref;
}

function getServername()
{
	return $_SERVER['SERVER_NAME'];
}

function isOutSubmit()
{
	$server1 = getRefer();
	$server2 = getServername();
	if (substr($server1, 7, strlen($server2)) <> $server2) {
		return true;
	} else {
		return false;
	}
}

function getIp() {
	$ip = $_SERVER['REMOTE_ADDR'];
	if (isset($_SERVER['HTTP_CLIENT_IP']) && preg_match('/^([0-9]{1,3}\.){3}[0-9]{1,3}$/', $_SERVER['HTTP_CLIENT_IP'])) {
		$ip = $_SERVER['HTTP_CLIENT_IP'];
	} elseif(isset($_SERVER['HTTP_X_FORWARDED_FOR']) AND preg_match_all('#\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}#s', $_SERVER['HTTP_X_FORWARDED_FOR'], $matches)) {
		foreach ($matches[0] AS $xip) {
			if (!preg_match('#^(10|172\.16|192\.168)\.#', $xip)) {
				$ip = $xip;
				break;
			}
		}
	}
	return $ip;
}

//写入文件
function createTextFile($content, $path)
{
	$path=replaceStr($path, "..", "");
	$path=replaceStr($path, sitePath, "");
	if (!file_exists($dirname = dirname(DJ_ROOT.$path))) {
		mkdirs($dirname);
	}
	$strlen = file_put_contents(DJ_ROOT.$path, $content);
	@chmod(DJ_ROOT.$path, 0777);
	if (file_exists(DJ_ROOT.$path)) return true; else return false;
}

function mkdirs($path, $mode = 0777)
{
	if (!is_dir(dirname($path))) {
		mkdirs(dirname($path), $mode);
	}
	if (!file_exists($path)) {
		return @mkdir($path, $mode);
	}
}

function isExistFile($fileDir)
{
	if (empty($fileDir)) return false;
	if (file_exists($fileDir)) return true; else return false;
}

function isExistFolder($folderDir)
{
	if (is_dir($folderDir)) return true; else return false;
}

//删除目录
function delFolder($path)
{
	if (isExistFile($path)) {
		if (is_file($path)) {
			delFile($path);
		} else {
			$handle = opendir($path);
			while ($file = readdir($handle)) {
				if (($file != ".") && ($file != "..") && ($file != "")) {
					if (isExistFolder("$path/$file")) {
						delFolder("$path/$file");
					} else {
						delFile("$path/$file");
					}
				}
			}
			closedir($handle);
			rmdir($path);
		}
	}
}

function delFile($filename)
{
	if (isExistFile($filename)) {
		@unlink($filename);
	}
}

function moveFolder($oldFolder, $newFolder)
{
	if ($oldFolder != $newFolder) {
		$voldFolder = $oldFolder;
		$vnewFolder = $newFolder;
		if (!file_exists($vnewFolder) && file_exists($voldFolder)) {
			rename($voldFolder, $vnewFolder);
		}
	}
}

function computeStrLen($str){
    $count = 0;
    $len = strlen($str);
    for($i=0; $i<$len; $i++,$count++)
       if(ord($str[$i])>=128)
    {
    $i*2;//or i*2
    }
    return $count;
}

function getStrByLen($str, $strlen){
	$str=trim($str);
	if (empty($str)) return '';
	$charCount=strlen($str);  
	$vStrlen=0  ;
	for($i=1; $i<$charCount; $i++){
		if (ord(substr($str,$i,1)) < 0 || ord(substr($str,$i,1)) >=127){
			$vStrlen=$vStrlen + 2;
        }else{   
			$vStrlen=$vStrlen + 1;
        }
		if ($vStrlen >= $strlen) return msubstr($str,$i);
    }
	return msubstr($str,$charCount);
}

function msubstr($str, $length, $start=0, $suffix = false, $charset = 'gbk')
{
    if (function_exists('mb_substr')) {
        $slice = mb_substr($str, $start, $length, $charset);
    } else if (function_exists('iconv_substr')) {
        $slice = iconv_substr($str, $start, $length, $charset);
    } else {
        $re['utf-8']  = '/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/';
        $re['gb2312'] = '/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/';
        $re['gbk']	  = '/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/';
        $re['big5']	  = '/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/';
        preg_match_all($re[$charset], $str, $match);
        $slice = join('', array_slice($match[0], $start, $length));
    }
    return $suffix ? $slice.'……' : $slice;
}

function escape($str) {
	preg_match_all("/[\x80-\xff].|[\x01-\x7f]+/",$str,$r);
	$ar = $r[0];
	foreach($ar as $k=>$v) {
		if(ord($v[0]) >= 128)
			//$ar[$k] = rawurlencode($v);
		//else
			$ar[$k] = "%u".bin2hex(mb_convert_encoding($v,"UCS-2","GB2312"));
	}
	return join("",$ar);
}

function unescape($str) {
  $str = rawurldecode($str);
  preg_match_all("/(?:%u.{4})|.+/U",$str,$r);
  $ar = $r[0];
  foreach($ar as $k=>$v) {
    if(substr($v,0,2) == "%u" && strlen($v) == 6)
		$ar[$k] = mb_convert_encoding(pack("H4",substr($v,-4)),"GB2312","UCS-2");
  }
  return join("",$ar);
}

function encodeHtml($str)
{
	if (strlen($str)==0 || trim($str) == "") return "";
		$str = str_replace("<", "&lt;", $str);
		$str = str_replace(">", "&gt;", $str);
		$str = str_replace(chr(34), "&quot;", $str);
		$str  =str_replace(chr(39), "&apos;", $str);
		return $str;
}

function decodeHtml($str)
{
	if (strlen($str) == 0 || trim($str) == "") return "";
		$str = str_replace("&lt;", "<", $str);
		$str = str_replace("&gt;", ">", $str);
		$str = str_replace("&quot;", chr(34), $str);
		$str = str_replace("&apos;", chr(39), $str);
		return $str;
}

function safe_replace($string)
{
	$string = str_replace('%20','',$string);
	$string = str_replace('%27','',$string);
	$string = str_replace('*','',$string);
	$string = str_replace('"','&quot;',$string);
	$string = str_replace("'",'',$string);
	$string = str_replace("\"",'',$string);
	$string = str_replace('//','',$string);
	$string = str_replace(';','',$string);
	$string = str_replace('<','&lt;',$string);
	$string = str_replace('>','&gt;',$string);
	$string = str_replace('(','',$string);
	$string = str_replace(')','',$string);
	$string = str_replace("{",'',$string);
	$string = str_replace('}','',$string);
	return $string;
}

function diconv($str, $in_charset, $out_charset = 'gbk', $ForceTable = FALSE) {
	$in_charset = strtoupper($in_charset);
	$out_charset = strtoupper($out_charset);

	if(empty($str) || $in_charset == $out_charset) {
		return $str;
	}

	$out = '';

	if(!$ForceTable) {
		if(function_exists('iconv')) {
			$out = iconv($in_charset, $out_charset.'//IGNORE', $str);
		} elseif(function_exists('mb_convert_encoding')) {
			$out = mb_convert_encoding($str, $out_charset, $in_charset);
		}
	}

	if($out == '') {
		require_once libfile('chinese');
		$chinese = new Chinese($in_charset, $out_charset, true);
		$out = $chinese->Convert($str);
	}

	return $out;
}

function codeTextarea($str, $enType)
{
	switch ($enType) {
		case "en":
			return replaceStr(replaceStr($str, chr(10),""), chr(13), "<br>");
		break;
		case "de":
			return replaceStr($str, "<br>", chr(13).chr(10));
		break;
	}
}

function getPageLink($page,$linkType){
	switch ($linkType) {
		case "channel":
			$getPageLink=getChannelPagesLink(djcms::$currentTypeId,$page);
		break;
		case "search":case "newssearch":
		    global $searchType,$searchword;
			$getPageLink="?page=".$page."&searchword=".urlencode($searchword)."&searchtype=".$searchType;
		break;
		case "topicindex":
			$getPageLink=getTopicIndexLink($page);
		break;
		case "topicpage":
			$getPageLink=getTopicPageLink(djcms::$currentTopicId,$page,"");
		break;
		case "newspage":
			$getPageLink=getNewsPartLink(djcms::$currentTypeId,$page);
		break;
		case "newssubpage":
		    global $currentId,$currentEnname,$currentDatetime;
			$getPageLink=formatArticleLink(djcms::$currentTypeId, $currentId, $currentEnname, $currentDatetime, "",$page);
		break;
		case "customvideo":
			$getPageLink=getCustomLink($page);
		break;
	}
	return $getPageLink;
}

function makePagenumberLoop($curPage,$pageline,$maxpage,$linkType,$loopstr){
	$curPage=intval($curPage);$ret = "";
	$j = (($pageline % 2) == 0) ? ($pageline / 2) : (ceil($pageline / 2) - 1);
	if  ($urPage < 1){  
	    $curPage=1; 
	}else if ($curPage > $maxpage){ 
		$curPage=$maxpage;
	}
	if ($pageline > $maxpage) $pageline=$maxpage;
	if ($curPage - $j < 1){
		$iStart=1;$iEnd=$pageline;
	}elseif ($curPage - $j + $pageline > $maxpage){
		$iStart=$maxpage - $pageline + 1;$iEnd=$maxpage;
	}else{
		$iStart=$curPage - $j;$iEnd=$curPage - $j + $pageline - 1;
	}
	for ($i = $iStart;$i <= $iEnd;$i++) {
		$tmp=replaceStr($loopstr,"[pagenumber:link]",getPageLink($i,$linkType));
		$tmp=replaceStr($tmp,"[pagenumber:page]",$i);
		$ret.=$tmp;
	}
	return $ret;
}

function makePageNumber($curPage,$pageline,$maxpage,$linkType){
	$ret = "";
	$curPage=intval($curPage);
	$j = (($pageline % 2) == 0) ? ($pageline / 2) : (ceil($pageline / 2) - 1);
	if  ($curPage < 1){  
	    $curPage=1; 
	}else if ($curPage > $maxpage){ 
		$curPage=$maxpage;
	}
	if ($pageline > $maxpage) $pageline = $maxpage;
	if ($curPage - $j < 1){
		$iStart = 1;$iEnd = $pageline;
	}elseif ($curPage - $j + $pageline > $maxpage){
		$iStart=$maxpage - $pageline + 1;$iEnd=$maxpage;
	}else{
		$iStart=$curPage - $j;$iEnd=$curPage - $j + $pageline - 1;
	}
	for ($i = $iStart;$i <= $iEnd;$i++) {
		if (intval($i) == intval($curPage)){
			if ($linkType == "search" || $linkType == "newssearch" || $linkType=="channel" || $linkType=="newspagelist" || $linkType=="topicpage"){
				$ret .= "<em>".$i."</em>";
			}else{
				$ret .= "<span><font color=red>".$i."</font></span>";
			}
		}else{
			$ret .= "<a href='".getPageLink($i,$linkType)."'>".$i."</a>";
		}
	}
	return $ret;
}

function pageNumberLinkInfo($curPage,$pageline,$maxpage,$linkType,$recordcount){
	$pageNumber = makePageNumber($curPage,$pageline,$maxpage,$linkType);
	switch (trim($linkType)) {
		case "search":case "newssearch":
			global $searchType,$searchword;
			$searchword = urlencode($searchword);
			if ($curPage == 1) {
				$ftPage = "<em class='nolink'>首页</em>" ; $ltPage = "<em class='nolink'>上一页</em>";
			} else {
				$ftPage = "<a href='?page=1&searchword=".$searchword."&searchtype=".$searchType."'>首页</a>" ; $ltPage = "<a href='?page=".($curPage-1)."&searchword=".$searchword."&searchtype=".$searchType."'>上一页</a>";
			}
			if ($curPage == $maxpage) {
				$ntPage = "<em class='nolink'>下一页</em>" ; $lastPage = "<em class='nolink'>尾页</em>";
			} else {
				$ntPage = "<a href='?page=".($curPage+1)."&searchword=".$searchword."&searchtype=".$searchType."'>下一页</a>" ; $lastPage = "<a href='?page=".$maxpage."&searchword=".$searchword."&searchtype=".$searchType."'>尾页</a>";
			}
			$pagesStr="<span><input type='input' name='page' size=4/><input type='button' value='跳转' onclick=\"goSearchPage(".$maxpage.",'page','?page=<page>&searchword=".$searchword."&searchtype=".$searchType."')\" class='btn' /></span>";
			$ret = "<span>共".$recordcount."条数据 页次:".$curPage."/".$maxpage."页</span>".$ftPage.$ltPage.$pageNumber.$ntPage.$lastPage.$pagesStr;
		break;
		case "channel":
			if ($curPage == 1) {
				$ftPage="<em class='nolink'>首页</em>" ; $ltPage="<em class='nolink'>上一页</em>";
			} else {
				$ftPage="<a href='".getChannelPagesLink(djcms::$currentTypeId,1)."'>首页</a>" ; $ltPage="<a href='".getChannelPagesLink(djcms::$currentTypeId,$curPage-1)."'>上一页</a>";
			}
			if ($curPage == $maxpage) {
				$ntPage="<em class='nolink'>下一页</em>" ; $lastPage="<em class='nolink'>尾页</em>";
			} else {
				$ntPage="<a href='".getChannelPagesLink(djcms::$currentTypeId,$curPage+1)."'>下一页</a>" ; $lastPage="<a href='".getChannelPagesLink(djcms::$currentTypeId,$maxpage)."'>尾页</a>";
			}
			$pagesStr="<span><input type='input' name='page' size=4/><input type='button' value='跳转' onclick=\"getPageGoUrl(".$maxpage.",'page','".getChannelPagesLink(djcms::$currentTypeId,"<page>")."')\" class='btn' /></span>";
			$ret="<span>共".$recordcount."条数据 页次:".$curPage."/".$maxpage."页</span>".$ftPage.$ltPage.$pageNumber."".$ntPage.$lastPage.$pagesStr;
		break;
		case "topicpage":
		    if ($curPage == 1) {
				$ftPage="<em class='nolink'>首页</em>" ; $ltPage="<em class='nolink'>上一页</em>";
			} else {
				$ftPage="<a href='".getTopicPageLink(djcms::$currentTopicId,1,"")."'>首页</a>" ; $ltPage="<a href='".getTopicPageLink(djcms::$currentTopicId,$curPage-1,"")."'>上一页</a>";
			}
			if ($curPage == $maxpage) {
				$ntPage="<em class='nolink'>下一页</em>" ; $lastPage="<em class='nolink'>尾页</em>";
			} else {
				$ntPage="<a href='".getTopicPageLink(djcms::$currentTopicId,$curPage+1,"")."'>下一页</a>" ; $lastPage="<a href='".getTopicPageLink(djcms::$currentTopicId,$maxpage,"")."'>尾页</a>";
			}
			$pagesStr="<span><input type='input' name='page' size=4/><input type='button' value='跳转' onclick=\"getPageGoUrl(".$maxpage.",'page','".getTopicPageLink(djcms::$currentTopicId,"<page>","")."')\" class='btn'></span>";
			$ret="<span>共".$recordcount."条数据 页次:".$curPage."/".$maxpage."页</span>".$ftPage.$ltPage.$pageNumber."".$ntPage."".$lastPage.$pagesStr;
		break;
		case "topicindex":
			if ($curPage == 1) {
				$ftPage="<em class='nolink'>首页</em>" ; $ltPage="<em class='nolink'>上一页</em>";
			} else {
				$ftPage="<a href='".getTopicIndexLink(1)."'>首页</a>" ; $ltPage="<a href='".getTopicIndexLink($curPage-1)."'>上一页</a>";
			}
			if ($curPage == $maxpage) {
				$ntPage="<em class='nolink'>下一页</em>" ; $lastPage="<em class='nolink'>尾页</em>";
			} else {
				$ntPage="<a href='".getTopicIndexLink($curPage+1)."'>下一页</a>" ; $lastPage="<a href='".getTopicIndexLink($maxpage)."'>尾页</a>";
			}
			$pagesStr="<span><input type='input' name='page' size=4/><input type='button' value='跳转' onclick=\"getPageGoUrl(".$maxpage.",'page','".getTopicIndexLink("<page>")."')\" class='btn'></span>";
			$ret="<span>共".$recordcount."条数据 页次:".$curPage."/".$maxpage."页</span>".$ftPage.$ltPage.$pageNumber.$ntPage.$lastPage.$pagesStr;
		break;
		case "newspage":
		    if ($curPage == 1) {
				$ftPage="<em class='nolink'>首页</em>" ; $ltPage="<em class='nolink'>上一页</em>";
			} else {
				$ftPage="<a href='".getNewsPartLink(djcms::$currentTypeId,1)."'>首页</a>";$ltPage="<a href='".getNewsPartLink(djcms::$currentTypeId,$curPage-1)."'>上一页</a>";
			}
			if ($curPage == $maxpage) {
				$ntPage="<em class='nolink'>下一页</em>";$lastPage="<em class='nolink'>尾页</em>";
			} else {
				$ntPage="<a href='".getNewsPartLink(djcms::$currentTypeId,$curPage+1)."'>下一页</a>" ; $lastPage="<a href='".getNewsPartLink(djcms::$currentTypeId,$maxpage)."'>尾页</a>";
			}
			$pagesStr="<span><input type='input' name='page' size=4 /><input type='button' value='跳转' onclick=\"getPageGoUrl(".$maxpage.",'page','".getNewsPartLink(djcms::$currentTypeId,"<page>")."')\" class='btn'></span>";
			$ret="<span>共".$recordcount."条数据 页次:".$curPage."/".$maxpage."页</span>".$ftPage.$ltPage.$pageNumber.$ntPage.$lastPage.$pagesStr;
		break;
		case "customvideo":
			if ($curPage == 1) {
				$ftPage="<em class='nolink'>首页</em>" ; $ltPage="<em class='nolink'>上一页</em>";
			} else {
				$ftPage="<a href='".getCustomLink(1)."'>首页</a>" ; $ltPage="<a href='".getCustomLink($curPage-1)."'>上一页</a>";
			}
			if ($curPage == $maxpage) {
				$ntPage="<em class='nolink'>下一页</em>" ; $lastPage="<em class='nolink'>尾页</em>";
			} else {
				$ntPage="<a href='".getCustomLink($curPage+1)."'>下一页</a>" ; $lastPage="<a href='".getCustomLink($maxpage)."'>尾页</a>";
			}
			$pagesStr="<span><input type='input' name='page' size=4/><input type='button' value='跳转' onclick=\"getPageGoUrl(".$maxpage.",'page','".getCustomLink("<page>")."')\" class='btn' /></span>";
			$ret="<span>共".$recordcount."条数据 页次:".$curPage."/".$maxpage."页</span>".$ftPage.$ltPage.$pageNumber."".$ntPage."".$lastPage.$pagesStr;
		break;
		case "newssubpage":
		    global $currentId,$currentEnname,$currentDatetime;
			if ($maxpage<2) return '';
			if ($curPage==1){
				$ftPage="<em class='nolink'>首页</em>";$ltPage="<em class='nolink'>上一页</em>";
	        }else{
				$ftPage="<a href='".formatArticleLink(djcms::$currentTypeId, $currentId, $currentEnname, $currentDatetime, "",1)."'>首页</a>";$ltPage="<a href='".formatArticleLink(djcms::$currentTypeId, $currentId, $currentEnname, $currentDatetime, "",$curPage-1)."'>上一页</a>";
	        }
			if ($curPage == $maxpage){
				$ntPage="<em class='nolink'>下一页</em>";$lastPage="<em class='nolink'>尾页</em>";
	        }else{
				$ntPage="<a href='".formatArticleLink(djcms::$currentTypeId, $currentId, $currentEnname, $currentDatetime, "",$curPage+1)."'>下一页</a>";$lastPage="<a href='".formatArticleLink(djcms::$currentTypeId, $currentId, $currentEnname, $currentDatetime, "",$maxpage)."'>尾页</a>";
	        }
			$ret=$ftPage.$ltPage.$pageNumber."".$ntPage."".$lastPage;
		break;
	}
	return $ret;
}

function formatChannelLink($id, $page, $linkType){
	$page=strval($page);
	switch (trim(runMode)) {
		case "dynamic":
		    $x = channelDirName1."/?";
		    if (paramset == 0) { 
		        $x .= $id.ifthen($page==1,"","-".$page).fileSuffix;
		    } else { 
			    $x .= paramid."=".$id.ifthen($page==1,"","&".parampage."=".$page);
			}
		break;
		case "static":
		    switch (trim(makeMode)) {
				case "dir1":case "dir3":case "dir5":case "dir7":
				    $x = getTypePathOnCache($id,"");
					if ($linkType != "link" || $page != 1) $x .= channelPageName2.ifthen($page=="1","",$page).fileSuffix;
				break;
				case "dir2":case "dir4":
				    $x = channelDirName3."/".channelPageName3.$id.ifthen($page==1,"","_".$page).fileSuffix;
				break;
				case "dir6":case "dir8":
				    $typename = explode(",", getTypeNameTemplateArrayOnCache(intval($id)));
				    $x = channelDirName3."/".channelPageName3.$typename[3].ifthen($page==1,"",$page).fileSuffix;
				break;
	        }
		break;
		case "forgedStatic":
		    $x=channelDirName4."/".channelPageName4.$id.ifthen($page==1,"","-".$page).fileSuffix;
		break;
    }
	return "/".sitePath.$x;
}

function formatContentLink($typeid,$id,$enname,$sDate,$linkType){
	switch (trim(runMode)) {
		case "dynamic":
		    $x=contentDirName1."/?";
			if (paramset == 0) $x .= $id.fileSuffix;else $x .= paramid."=".$id;
		break;
		case "static":
			switch (trim(makeMode)) {
				case "dir1":
				    if (md5Content == 1) { $id=substr(md5($id),8,16);}
					$x = getTypePathOnCache($typeid,"").$id."/";
					if ($linkType<>"link") $x .= contentPageName2.fileSuffix;
				break;
				case "dir3":
				    if (md5Content == 1) { $id=substr(md5($id),8,16);}
				    $x = getTypePathOnCache($typeid,"").date('Y-m')."/".$id.fileSuffix;
				break;
				case "dir5":
				    $x = getTypePathOnCache($typeid,"").$enname."/";if ($linkType != "link") $x .= contentPageName2.fileSuffix;
				break;
				case "dir7":
				    $x = getTypePathOnCache($typeid,"").date('Y-m')."/".$enname.fileSuffix;
				break;
				case "dir2":
				    if (md5Content == 1) { $id = substr(md5($id),8,16);}else{ $id = contentPageName3.$id;}
				    $x = contentDirName3."/".$id.fileSuffix;
				break;
				case "dir4":
				    if (md5Content == 1) { $id = substr(md5($id),8,16);}else{ $id = contentPageName3.$id;}
					$x = contentDirName3."/".date('Y-m')."/".$id.fileSuffix;
				break;
				case "dir6":
				    $x = contentDirName3."/".contentPageName3.$enname.fileSuffix;
				break;
				case "dir8":
				    $x = contentDirName3."/".date('Y-m')."/".contentPageName3.$enname.fileSuffix;
				break;
			}
		break;
		case "forgedStatic":
		    $x = contentDirName4."/".contentPageName4.$id.fileSuffix;
		break;
	}
	return "/".sitePath.$x;
}

function formatPlayLink($typeid,$id,$enname,$sDate,$fileSuffix){
	$y = runMode;$z = $fileSuffix;
	if ($y != "forgedStatic") {
		if (ismakeplay == 0) {
			$y = "dynamic";
        }else if (ismakeplay == 2) {
			$z = ".php";
        }
	}
	switch ($y) {
		case "dynamic":$x = playDirName1."/";break;
		case "static":
			switch (trim(makeMode)) {
				case "dir1":
				    if (md5Content == 1) { $id=substr(md5($id),8,16);}
					$x = getTypePathOnCache($typeid,"").$id."/".playPageName2.$z;
				break;
				case "dir3":
				    if (md5Content == 1) { $id=substr(md5($id),8,16);}
				    $x = getTypePathOnCache($typeid,"").date('Y-m')."/".$id."/".playPageName2.$z;
				break;
				case "dir5":
				    $x = getTypePathOnCache($typeid,"").$enname."/".playPageName2.$z;
				break;
				case "dir7":
				    $x = getTypePathOnCache($typeid,"").date('Y-m')."/".$enname."/".playPageName2.$z;
				break;
				case "dir2":
				    if (md5Content == 1) {
					    $x = playDirName3."/".substr(md5($id),8,16).$z;
					} else { 
					    $x = playDirName3."/".playPageName3.$id.$z;
			        }
				break;
				case "dir4":
				    if (md5Content == 1) {
						$x = playDirName3."/".date('Y-m')."/".substr(md5($id),8,16).$z;
					} else {
						$x = playDirName3."/".date('Y-m')."/".playPageName3.$id.$z;
					}
				break;
				case "dir6":
				    $x = playDirName3."/".$enname."/".ifthen(playPageName3 != "",playPageName3,"index").$z;
				break;
				case "dir8":
				    $x = playDirName3."/".date('Y-m')."/".$enname."/".ifthen(playPageName3 != "",playPageName3,"index").$z;
				break;
			}
		break;
		case "forgedStatic":
		    $x = playDirName4."/";
		break;
	}
	return "/".sitePath.$x;
}

function getChannelPagesLink($typeId,$page){
	return formatChannelLink($typeId,$page,"");
}

function getTypeLink($typeId){
	return formatChannelLink($typeId,1,"link");
}

function getContentLink($typeid,$id,$enname,$sDate,$linkType){
	return formatContentLink($typeid,$id,$enname,$sDate,$linkType);
}

function getPlayLink($typeid,$id,$enname,$sDate){
	return formatPlayLink($typeid,$id,$enname,$sDate,fileSuffix);
}

function getPlayLink2($typeid,$id,$enname,$sDate,$From,$index){
	if (ismakeplay==3 && runMode=="static"){
		$x = "-".$From."-".$index.fileSuffix;$x = formatPlayLink($typeid,$id,$enname,$sDate,$x);
	}else if (runMode=="forgedStatic"){
		$x = getPlayLink($typeid,$id,$enname,$sDate).$id."-".$From."-".$index.fileSuffix;
	} else {
		$x = getPlayLink($typeid,$id,$enname,$sDate);
		if (paramset == 0) $x .= "?".$id."-".$From."-".$index;else $x .= "?".paramid."=".$id."&".parampage."=".$From."&".paramindex."=".$index;
		if (runMode != "static" && paramset != 1 || ismakeplay==0) $x .= fileSuffix;
	}
	return $x;
}

function formatPartLink($id,$page,$linkType){
	$page=strval($page);
	switch (newsrunMode) {
		case "dynamic":
		    $x = partDirName1."/?";
			if (newsparamset == 0) {
			    $x .= $id.ifthen($page == 1,"","-".$page).newsFileSuffix;
	        } else {
			    $x .= newsparamid."=".$id.ifthen($page == 1,"","&".newsparampage."=".$page);
	        }
		break;
		case "static":
		    switch (newsMakeMode) {
				case "dir1":case "dir3":case "dir5":case "dir7":
				    $x = newsDirName2."/".getTypePathOnCache($id,"news");
				    if ($linkType != "link" || $page != 1) $x .= partPageName2.ifthen($page == 1,"",$page).newsFileSuffix;
				break;
				case "dir2":case "dir4":
				    $x = newsDirName3."/".partDirName3."/".partPageName3.$id.ifthen($page == 1,"","_".$page).newsFileSuffix;
				break;
				case "dir6":case "dir8":
				    $typename = explode(",", getTypeNameTemplateArrayOnCache(intval($id)));
				    $x = newsDirName3."/".partDirName3."/".partPageName3.$typename[3].ifthen($page == 1,"",$page).newsFileSuffix;
				break;
	        }
		case "forgedStatic":
		    $x = newsDirName4."/".partDirName4."/".partPageName4.$id.ifthen($page == 1,"","-".$page).newsFileSuffix;
		break;
	}
	return "/".sitePath.$x;
}

function formatArticleLink($typeid,$id,$enname,$sDate,$linkType,$page){
	switch (newsrunMode) {
		case "dynamic":
		    $x=articleDirName1."/?";
			if (newsparamset==0) $x .= $id.ifthen($page=="1","","-".$page).newsFileSuffix;else $x .= newsparamid."=".$id.ifthen($page=="1","","&".newsparampage."=".$Page);
		break;
		case "static":
			switch (newsMakeMode) {
				case "dir1":
				    if (newsmd5Content == 1) $id=substr(md5($id),8,16);
					$x = newsDirName2."/".getTypePathOnCache($typeid,"news").$id."/";
					if ($linkType != "link" || $page!="1") $x .= articlePageName2.ifthen($page=="1","",$page).newsFileSuffix;
				break;
				case "dir3":
				    if (newsmd5Content == 1) $id=substr(md5($id),8,16);
					$x = newsDirName2."/".getTypePathOnCache($typeid,"news").date('Y-m')."/".$id.ifthen($page=="1","","-".$page).newsFileSuffix;
				break;
				case "dir5":
				    $x = newsDirName2."/".getTypePathOnCache($typeid,"news").$enname."/";
					if ($linkType != "link") $x .= articlePageName2.ifthen($page=="1","",$page).newsFileSuffix;
				break;
				case "dir7":
				    $x = newsDirName2."/".getTypePathOnCache($typeid,"news").date('Y-m')."/".$enname.ifthen($page=="1","",$page).newsFileSuffix;
				break;
				case "dir2":
				    if (newsmd5Content==1) $id = substr(md5($id),8,16);else $id = articlePageName3.$id;
					$x = newsDirName3."/".articleDirName3."/".$id.ifthen($page=="1","",$page).newsFileSuffix;
				break;
				case "dir4":
				    if (newsmd5Content==1) $id = substr(md5($id),8,16);else $id = articlePageName3.$id;
					$x = newsDirName3."/".articleDirName3."/".date('Y-m')."/".$id.ifthen($page=="1","",$page).newsFileSuffix;
				break;
				case "dir6":
				    $x = newsDirName3."/".articleDirName3."/".articlePageName3.$enname.ifthen($page=="1","",$page).newsFileSuffix;
				break;
				case "dir8":
				    $x = newsDirName3."/".articleDirName3."/".date('Y-m')."/".articlePageName3.$enname.ifthen($page=="1","",$page).newsFileSuffix;
				break;
			}
		break;
		case "forgedStatic":
		    $x = newsDirName4."/".articleDirName4."/".articlePageName4.$id.newsFileSuffix;
		break;
	}
	return "/".sitePath.$x;
}

function getNewsArticleLink($typeid,$id,$enname,$sDate,$linkType){
	return formatArticleLink($typeid,$id,$enname,$sDate,$linkType,1);
}

function getNewsPartLink($id,$page){
	return formatPartLink($id,$page,"");
}

function getNewsTypeLink($typeId){
	return formatPartLink($typeId,1,"link");
}

function getNewsIndexLink(){
	if (newsrunMode == "dynamic"){
		$getNewsIndexLink = "/".sitePath.newsDirName1."/";
	} else if (newsrunMode == "static"){
		if (strpos("#dir2#dir4#dir6#dir8",newsMakeMode) > 0){
			$getNewsIndexLink = "/".sitePath.newsDirName3."/".newsPageName2.newsFileSuffix;
	    }else{
			$getNewsIndexLink = "/".sitePath.newsDirName2."/".newsPageName3.newsFileSuffix;
		}
	} else if (newsrunMode == "forgedStatic"){
		$getNewsIndexLink = "/".sitePath.newsDirName4."/".newsPageName4.newsFileSuffix;
	}
	return $getNewsIndexLink;
}

function getTopicPageLink($id,$page,$enname){
	$page=strval($page);
	switch (runMode) {
		case "dynamic":
		    $x = topicPageDirName."/?";
			if (paramset == 0){
			    $x .= $id.ifthen($page == 1,"","-".$page).fileSuffix;
			}else{
			    $x .= paramid."=".$id.ifthen($page == 1,"","&".parampage."=".$page);
			}
		break;
		case "static":
		    if ($enname == ""){
				$x = DB::result_first("SELECT m_enname FROM ".DB::table('topic')." WHERE m_id=".$id);
			}else{
			    $x = $enname;
			}
			$x = topicPageDirName."/".$x.ifthen($page==1,"","-".$page).fileSuffix;
		break;
		case "forgedStatic":
		    $x = topicpageDirName4."/".$id.ifthen($page==1,"","-".$page).fileSuffix;
		break;
	}
	return "/".sitePath.$x;
}

function getTopicIndexLink($page){
	$page=strval($page);
	if (runMode == "dynamic"){
		$x = "/".sitePath.topicDirName."/";
		if (paramset == 0) $x .= ifthen($page == 1,"","?".$page.fileSuffix);else $x .= ifthen($page == 1,"","?".parampage."=".$page);
	} else if (runMode == "static"){
		$x = "/".sitePath.topicDirName."/index".ifthen($page != 1,$page,"").fileSuffix;
    } else if (runMode == "forgedStatic"){
		$x = "/".sitePath.topicDirName4."/index".ifthen($page != 1,$page,"").fileSuffix;
	}
	return $x;
}

function getCustomLink($page){
	global $customLink;
	return replaceStr($customLink,"<page>",ifthen(intval($page)<>"1",$page,""));
}

function getIndexLink(){
	if (runMode == "dynamic" || runMode == "static"){
		return "/".sitePath;
    }else if (runMode == "forgedStatic"){
		return "/".sitePath."index".fileSuffix;
    }
}

function getPlayerParas() {
	if (paramset == 0){
	    $paras = explode("-", replaceStr(QUERY_STRING, fileSuffix, ""));
	    $len = count($paras);
	    if ($len > 1) {
			$getPlayerParas = array($paras[1],$paras[2]);
	    } else {
			$getPlayerParas = array(-1,-1);
	    }
	}else{
		$getPlayerParas = array(getForm(parampage,"both"),getForm(paramindex,"both"));
	}
	return $getPlayerParas;
}

function getPlayUrlList($ifrom,$url,$typeId,$vId,$enname,$sDate,$typestr,$starget){
	$paras=getPlayerParas();
	if (empty($url)){
		return '';
	}else{
		if ($starget != "") {
		    $target = " target=\"".$starget."\"";
	    } else {
		    $target = " target=\"_blank\"";
	    }
		$urlArray = explode("#",$url);
	    $urlCount = count($urlArray);
	    $urlStr = "<ul>";
		for ($i = 0;$i < $urlCount;$i++) {
			if (!empty($urlArray[$i])) {
				$singleUrlArray = explode("$", $urlArray[$i]);
				if (count($singleUrlArray) < 2) $singleUrlArray = array("", "", "");
				if ($paras[0] == $ifrom && $i == $paras[1]) $style = " style=\"color:red\""; else $style = "";
				switch ($typestr) {
					case "play" :
						if (isAlertWin == 1) {
							$urlStr.= "<li><a title='".$singleUrlArray[0]."' href=\"javascript:openWin('".getPlayLink2($typeId,$vId,$enname,$sDate,$ifrom,$i)."',".(alertWinW+10).",".(alertWinH+55).",250,100,1)\"".$style.">".$singleUrlArray[0]."</a></li>";
						} else {
							 $urlStr.= "<li><a target='_blank' title='".$singleUrlArray[0]."' href='".getPlayLink2($typeId,$vId,$enname,$sDate,$ifrom,$i)."'".$style.$target.">".$singleUrlArray[0]."</a></li>";
						}
					break;
					case "down" :
					    $urlStr.= "<li><a href='".$singleUrlArray[1]."'".$style.$target.">".$singleUrlArray[0]."</a></li>";
				    break;
		        }
		    }
		}
	}
	$urlStr.= "</ul>";
	return $urlStr;
}

function getTypePath($id,$by) {
	if ($by == "news") {
		$tlist = getNewsTypeLists();
	} else {
		$tlist = getTypeLists();
	}
	foreach ($tlist as $row) {
		if ($row['m_id'] == $id) {
			if ($row['m_upid'] == 0) {
				return $row['m_enname']."/";
			} else {
				return getTypePath($row['m_upid']).$row['m_enname']."/";
			}
		}
	}
}

function getTypePathOnCache($id, $by) {
	$cacheName = "str_get_curtype_dir_type".$id;
	if (cacheStart == 1) {
		if (!$pathStr = memory('get', $cacheName)) {
			$pathStr = getTypePath($id, $by);
			memory('set', $cacheName, $pathStr);
        }
	} else {
		$pathStr = getTypePath($id, $by);
	}
	return $pathStr;
}

function getTypeField($id,$Col,$by) {
	if ($by=="news"){ $tlist=getNewsTypeLists();}else{ $tlist=getTypeLists();};$k=explode(",",$Col);$id=intval($id);
	foreach ($tlist as $row) {
		if ($row['m_id'] == $id) {
			$kcount = count($k);
			for ($j = 0;$j < $kcount;$j++) {
				$k[$j]=$row[$k[$j]];
	        }
			return $k;
		}
	}
	return $k;
}

function getTypeUpid($id) {
	$x = getTypeField($id,"m_upid","");
	if (is_numeric($x[0])){
		return intval($x[0]);
	}else{
		return $id;
	}
}

function getNewsTypeUpid($id) {
	$x = getTypeField($id,"m_upid","news");
	if (is_numeric($x[0])){
		return intval($x[0]);
	}else{
		return $id;
	}
}

function getTypeText($id) {
	$tlist = getTypeLists();
	foreach ($tlist as $row) {
		if ($row['m_id'] == $id) {
			if ($row['m_upid'] == 0) {
				return "<a href='".getIndexLink()."' >首页</a>&nbsp;&nbsp;&raquo;&nbsp;&nbsp;<a href='".getTypeLink($row['m_id'])."' >".$row['m_name']."</a>";
			} else {
				return getTypeText($row['m_upid'])."&nbsp;&nbsp;&raquo;&nbsp;&nbsp;<a href='".getTypeLink($row['m_id'])."'>".$row['m_name']."</a>";
			}
		}
	}
}

function getNewsTypeText($id) {
	$tlist = getNewsTypeLists();
	foreach ($tlist as $row) {
		if ($row['m_id'] == $id) {
			if ($row['m_upid'] == 0) {
				return "<a href='".getIndexLink()."'>首页</a>&nbsp;&nbsp;&raquo;&nbsp;&nbsp;<a href='".getNewsIndexLink()."'>新闻首页</a>&nbsp;&nbsp;&raquo;&nbsp;&nbsp;<a href='".getNewsTypeLink($row['m_id'])."' >".$row['m_name']."</a>";
			} else {
				return getNewsTypeText($row['m_upid'])."&nbsp;&nbsp;&raquo;&nbsp;&nbsp;<a href='".getNewsTypeLink($row['m_id'])."'>".$row['m_name']."</a>";
			}
		}
	}
}

function getTypeTextOnCache($id) {
	$cacheName = "str_get_curtype_location_type".$id;
	if (cacheStart == 1) {
		if (!$typeText = memory('get', $cacheName)) {
			$typeText = getTypeText($id);
			memory('set', $cacheName, $typeText);
        }
	} else {
		$typeText = getTypeText($id);
	}
	return $typeText;
}

function getNewsTypeTextOnCache($id) {
	$cacheName = "str_get_newstype_location_type".$id;
	if (cacheStart == 1) {
		if (!$typeText = memory('get', $cacheName)) {
			memory('set', $cacheName, getNewsTypeText($id));
        }
	} else {
		$typeText = getNewsTypeText($id);
	}
	return $typeText;
}

function getTopicId(){
	$ret = "";
	$query = DB::query("SELECT m_id FROM ".DB::table('topic')." ORDER BY m_sort ASC");
    while($row = DB::fetch($query)) {
		if ($ret == "") {
			$ret = $row['m_id'];
		} else {
			$ret.= ",".$row['m_id'];
		}
	}
	return $ret;
}

function getTypeId($id) {
	$ret = "";
	$tlist = getTypeLists();
	if (intval($id) > 0) $ret = $id;
	foreach ($tlist as $row) {
		if ($row['m_upid'] == $id) {
			if ($ret == "") {
				$ret = getTypeId($row['m_id']);
			} else {
				$ret.= ",".getTypeId($row['m_id']);
			}
		}
	}
	return $ret;
}

function getNewsTypeId($id) {
	$ret = "";
	$tlist = getNewsTypeLists();
	if (intval($id) > 0) $ret = $id;
	foreach ($tlist as $row) {
		if ($row['m_upid'] == $id) {
			if ($ret == "") {
				$ret = getNewsTypeId($row['m_id']);
			} else {
				$ret.= ",".getNewsTypeId($row['m_id']);
			}
		}
	}
	return $ret;
}

function getTypeIdOnCache($id) {
	$cacheName = "str_get_subtypes_type".$id;
	if (cacheStart == 1) {
		if (!$typeid = memory('get', $cacheName)) {
			$typeid = getTypeId($id);
            memory('set', $cacheName, $typeid);
        }
	} else {
		$typeid = getTypeId($id);
	}
	return $typeid;
}

function getNewsTypeIdOnCache($id) {
	$cacheName = "str_get_newssubtypes_type".$id;
	if (cacheStart == 1) {
		if (!$typeid = memory('get', $cacheName)) {
			$typeid = getNewsTypeId($id);
			memory('set', $cacheName, $typeid);
        }
	} else {
		$typeid = getNewsTypeId($id);
	}
	return $typeid;
}

function getAllMenuList($id) {
	$tlist = getTypeLists();$s = "";
	foreach ($tlist as $row) {
		if ($row['m_upid'] == $id) {
			$s=$s."<li><a href='".getTypeLink($row['m_id'])."'>".$row['m_name']."</a>".getAllMenuList($row['m_id'])."</li>";
		}
	}
	if ($s != ""){ $getAllMenuList = "<ul>".$s."</ul>";}
	return $getAllMenuList;
}

function getAllMenuListOnCache($id,$by){
	$cacheName="str_".$by."menu_list".$id;
	if (cacheStart==1){
		if (!$menuList = memory('get', $cacheName)) {
			if ($by=="news"){
				$menuList=getAllNewsMenuList($id);
		    }else{
				$menuList=getAllMenuList($id);
		    }
			memory('set', $cacheName, $menuList);
        }
	}else{
		if ($by=="news"){
			$menuList=getAllNewsMenuList($id);
		}else{
			$menuList=getAllMenuList($id);
		}
	}
	return $menuList;
}

function getTypeArray($itype='0') {
	$sql="SELECT m_id,m_name,m_enname,m_sort,m_upid,m_hide,m_template,m_subtemplate,m_unionid,-1 AS m_count,m_keyword,m_description FROM ".DB::table('type')." WHERE m_type=$itype ORDER BY m_sort ASC";
    $query = DB::query($sql);
    while($row = DB::fetch($query)) {
		 $rows[] = $row;
	}
	return $rows;
}

function getTypeListsl() {
	$currentLevel = getLevelCourt();
	$sql="SELECT m_id,m_name,m_enname,m_sort,m_upid,m_hide,m_template,m_subtemplate,m_unionid,-1 AS m_count,m_keyword,m_description FROM ".DB::table('type')." WHERE m_id in (".$currentLevel.")";
    $query = DB::query($sql);
    while($row = DB::fetch($query)) {
		 $rows[] = $row;
	}
	return $rows;
}

function getTypeLists(){
	$cacheName="array_type_lists_all";
	if (cacheStart == 1) {
		if (!$gTypeary = memory('get', $cacheName)) {
			$gTypeary = getTypeArray(0);
			memory('set', $cacheName, $gTypeary);
        }
	} else {
        $gTypeary = getTypeArray(0);
	}
	return $gTypeary;
}

function getNewsTypeLists(){
	$cacheName="array_newstype_lists_all";
	if (cacheStart == 1) {
		if (!$gTypeary = memory('get', $cacheName)) {
			$gTypeary = getTypeArray(1);
            memory('set', $cacheName, getTypeArray(1));
        }
	} else {
        $gTypeary = getTypeArray(1);
	}
	return $gTypeary;
}

function getNumPerType($id) {
	$Bool=false;
	$num = 0;$tlist = getTypeLists();
	$ids = ",,".str_replace(" ", "", getTypeIdOnCache($id)).",,";
	foreach ($tlist as $k => $row) {
		if (strpos($ids, ",".trim($row['m_id']).",") > 0) {
			$tcount = $row['m_count'];
			if ($tcount == -1) {
				$tcount = DB::result_first("SELECT count(*) FROM ".DB::table('data')." WHERE m_type=".$row['m_id']);
			}
			$num=$num+intval($tcount);$Bool=true;
			$tlist[$k]['m_count']=$num;
		}
	}
	if($Bool==true)
	{
		if (cacheStart == 1) memory('set', "array_type_lists_all", $tlist);
	}
	return $num;

}

function getNumPerNewsType($id) {
	$Bool=false;
	$num = 0;$tlist = getNewsTypeLists();
	$ids = ",,".str_replace(" ", "", getNewsTypeIdOnCache($id)).",,";
	foreach ($tlist as $k => $row) {
		if (strpos($ids, ",".trim($row['m_id']).",") > 0) {
			$tcount = $row['m_count'];
			if ($tcount == -1) {
				$tcount = DB::result_first("SELECT count(*) FROM ".DB::table('news')." WHERE m_type=".$row['m_id']);
			}
			$num=$num+intval($tcount);$Bool=true;
			$tlist[$k]['m_count']=$num;
		}
	}
	if($Bool==true)
	{
		if (cacheStart==1) memory('set', "array_newstype_lists_all", $tlist);
	}
	return $num;

}

function getHideTypeIDS() {
	$ret = "";
	$tlist = getTypeLists();
	foreach ($tlist as $row) {
		if ($row['m_hide'] == 1) {
			if ($ret == ""){
				$ret = $row['m_id'];
			} else {
				$ret.= ",".$row['m_id'];
			}
		}
	}
	return $ret;
}

function getHideNewsTypeIDS() {
	$ret = "";
	$tlist = getNewsTypeLists();
	foreach ($tlist as $row) {
		if ($row['m_hide'] == 1) {
			if ($ret == ""){
				$ret = $row['m_id'];
			} else {
				$ret.= ",".$row['m_id'];
			}
		}
	}
	return $ret;
}

function makeTypeOption($topId, $separateStr, $span = '') {
	$tlist = getTypeLists();
	if ($topId != 0) $span.= $separateStr; else $span = "";
	foreach ($tlist as $row) {
		if ($row['m_upid'] == $topId) {
			echo "<option value='".$row['m_id']."'>".$span."&nbsp;|—".$row['m_name']."</option>";
			makeTypeOption($row['m_id'], $separateStr, $span);
		}
	}
}

function makeNewsTypeOption($topId, $separateStr, $span = '') {
	$tlist = getNewsTypeLists();
	if ($topId != 0) $span.= $separateStr; else $span = "";
	foreach ($tlist as $row) {
		if ($row['m_upid'] == $topId) {
			echo "<option value='".$row['m_id']."'>".$span."&nbsp;|—".$row['m_name']."</option>";
			makeTypeOption($row['m_id'], $separateStr, $span);
		}
	}
}

function makeTypeSelect($selectName) {
	echo "<select name='".$selectName."'>";
	echo "<option value=''>请选择视频分类</option>";
	makeTypeOption(0,"&nbsp;|&nbsp;&nbsp;");
	echo "</select>";
}

function makeNewsTypeSelect($selectName) {
	echo "<select name='".$selectName."'>";
	echo "<option value=''>请选择文章分类</option>";
	makeNewsTypeOption(0,"&nbsp;|&nbsp;&nbsp;");
	echo "</select>";
}

function getTopicArray() {
	$query = DB::query("SELECT m_id,m_name FROM ".DB::table('topic')." ORDER BY m_sort ASC");
    while($row = DB::fetch($query)) {
		 $rows[] = $row;
	}
	return $rows;
}

function getTopicLists(){
	$cacheName="array_topic_lists_all";
	if (cacheStart == 1) {
		if (!$gTypeary = memory('get', $cacheName)) {
			$gTypeary = getTopicArray();
			memory('set', $cacheName, $gTypeary);
        }
	} else {
        $gTypeary = getTopicArray();
	}
	return $gTypeary;
}

function makeTopicSelect($selectName,$strSelect,$topicId){
	$selectedStr="";
	$topic = getTopicLists();
	$str="<select id='".$selectName."'  name='".$selectName."' >";
	if (!empty($strSelect))  $str .= "<option value=''>".$strSelect."</option>";
    foreach ($topic as $row) {
		if (!empty($topicId)){
			if (intval($row['m_id'])==intval($topicId)) $selectedStr="selected";
		}
		$str .= "<option value='".$row['m_id']."' ".$selectedStr.">".$row['m_name']."</option>";
	}
	$str .= "</select>";
	return $str;
}

function makeTopicOptions($strSelect){
	$str="";
	$topic = getTopicLists();
	if (!empty($str)) $str .= "<option value='-1'>".$strSelect."</option>";
	foreach ($topic as $row) {
		$str .= "<option value='".$row['m_id']."'>".$row['m_name']."</option>";
    }
	return $str;
}

function getTypeNameTemplateArray($m_id) {
	$ret = "";$typeArray = getTypeLists();
	foreach ($typeArray as $row) {
		if ($row['m_id'] == $m_id) {
			$ret=$row['m_name'].",".$row['m_template'].",".$row['m_upid'].",".$row['m_enname'].",".$row['m_subtemplate'];
		}
	}
	return $ret;
}

function getNewsTypeNameTemplateArray($m_id) {
	$ret = "";$typeArray = getNewsTypeLists();
	foreach ($typeArray as $row) {
		if ($row['m_id'] == $m_id) {
			$ret=$row['m_name'].",".$row['m_template'].",".$row['m_upid'].",".$row['m_enname'].",".$row['m_subtemplate'];
		}
	}
	return $ret;
}

function getTypeNameTemplateArrayOnCache($id) {
	$cacheName="array_type_id_name_template_upid".$id;
    if (cacheStart==1) {
		if (!$ret = memory('get', $cacheName)) {
            $ret = getTypeNameTemplateArray($id);
			memory('set', $cacheName, $ret);
        }
	} else {
		$ret = getTypeNameTemplateArray($id);
	}
	return $ret;
}

function getNewsTypeNameTemplateArrayOnCache($id) {
	$cacheName="array_NewsType_id_name_template_upid".$id;
    if (cacheStart==1) {
		if (!$ret = memory('get', $cacheName)) {
            $ret = getNewsTypeNameTemplateArray($id);
			memory('set', $cacheName, $ret);
        }
	} else {
		$ret = getNewsTypeNameTemplateArray($id);
	}
	return $ret;
}

function echoSaveStr($ptype) {
	$cssstr = "<style>body{text-align:center}#msg{background-color:white;border:1px solid #1B76B7;margin:0 auto;width:400px;text-align:left}.msgtitle{padding:3px 3px;color:white;font-weight:700;line-height:21px;height:25px;font-size:12px;border-bottom:1px solid #1B76B7; text-indent:3px; background-color:#1B76B7}#msgbody{font-size:12px;padding:40px 8px 50px;line-height:25px}#msgbottom{text-align:center;height:20px;line-height:20px;font-size:12px;background-color:#1b76b7;color:#FFFFFF}</style>";
	switch (trim($ptype)) {
		case "safe":
			die($cssstr."<div id='msg'><div class='msgtitle'>【警告】非法提交：</div><div id='msgbody'>你提交的数据有非法字符，你的IP【<b>".getIp()."</b>】已被记录,操作时间:".date("Y-m-d H:i:s", time())
."</div><div id='msgbottom'>Powered By ".siteName."</div></div>");
        break;
		case "null":
			die($cssstr."<div id='msg'><div class='msgtitle'>【警告】参数错误：</div><div id='msgbody'><b>错误描述</b>：参数为空或不正确</div><div id='msgbottom'>Powered By ".siteName."</div></div>");
		break;
	}
}

function replaceCurrentTypeId($str){
	return replaceStr($str,"{djcms:currenttypeid}",djcms::$currentTypeId);
}

function replaceTopicId($str){
	return replaceStr($str,"{djcms:currenttopicid}",djcms::$currentTopicId);
}

function getFromStr($playurl) {
	if (empty($playurl)) return "";
	$span1="$$$";
	$span2="$$";
	$urlstr = '';
	$playurlArray=explode($span1,$playurl);
	$playurlLen=count($playurlArray);
	for ($i = 0;$i < $playurlLen;$i++) {
		$playFromArray=explode($span2,$playurlArray[$i]);
	    if ($i==$playurlLen-1) {
		    $urlstr=$urlstr.$playFromArray[0];
	    } else {
		    $urlstr=$urlstr.$playFromArray[0].",";
	    }
	}
	return $urlstr;
}

function getPlayurlArray($playurl) {
	$span1 = "$$$";
	if (empty($playurl)) $playurl = '';
	return explode($span1, $playurl);
}

function filterDirty($content) {
	$dirtyStr = '%u80e1%u9526%u6d9b%2C%u6e29%u5bb6%u5b9d%2C%u5c3b%2C%u64cd%u4f60%2C%u5e72%u6b7b%u4f60%2C%u8d31%u4eba%2C%u72d7%u5a18%2C%u5a4a%u5b50%2C%u8868%u5b50%2C%u9760%u4f60%2C%u53c9%u4f60%2C%u53c9%u6b7b%2C%u63d2%u4f60%2C%u63d2%u6b7b%2C%u5e72%u4f60%2C%u5e72%u6b7b%2C%u65e5%u4f60%2C%u65e5%u6b7b%2C%u9e21%u5df4%2C%u777e%u4e38%2C%u5305%u76ae%2C%u9f9f%u5934%2C%u59a3%2C%u5976%u5b50%2C%u5976%u5934%2C%u9634%u6bdb%2C%u9634%u9053%2C%u9634%u830e%2C%u53eb%u5e8a%2C%u5f3a%u5978%2C%u7231%u6db2%2C%u6027%u9ad8%u6f6e%2C%u505a%u7231%2C%u6027%u4ea4%2C%u53e3%u4ea4%2C%u809b%u4ea4';
	$dirtyArray = explode(",",unescape($dirtyStr));$count = count($dirtyArray);
	for ($ki = 1;$ki < $count;$ki++) {
		$content=str_replace($dirtyArray[$ki],"***",$content);
	}
	return $content;
}

function showFace($message) {
	return preg_replace("/\[ps:([0-9]{1,2})\]/is","<img src=\"/".sitePath."pic/faces/\\1.gif\" border=\"0\"/>", $message);
}

function isExistStr($string, $find) {
	return !(strpos($string, $find) === FALSE);
}

function getrulevaluearr($content,$str)
{
	if(!empty($content) && !empty($str)){
		$labelRule = buildregx("<".$str.">(.*?)</".$str.">","is");
		preg_match_all($labelRule,$content,$ar);
		return $ar[0];
	}
}

function StrSlice($str,$startStr,$endStr){
    $strtemp1 = explode($startStr, $str);
    $strtemp2 = explode($endStr, $strtemp1[1]);
    return $strtemp2[0];
}

function jsIndexOf($Str, $substr) {
    $Pos = strpos(chr(0).$Str,$substr);
    return ifthen($Pos==0,-1,$Pos-1);
}

//截取文本中间B 最大范围
function StrSliceB($Str,$sStr,$eStr){
	if ($sStr.$eStr=="") return $Str;
	$tStr=strtolower($Str);$iPos=jsIndexOf($tStr,strtolower($sStr));$sLen=strlen($sStr);$StrSliceB="";
	if ($iPos=='-1') return '';
	$iPos=ifthen($sLen>0,$iPos+$sLen,1);
	if ($eStr==""){
		$StrSliceB=jsSlice($Str,$iPos-1,0);
    }else{
		$tStr=jsSlice($tStr,$iPos,0);
		$StrSliceB=substr($Str,$iPos-1,strrpos($tStr,strtolower($eStr)));
    }
	return $StrSliceB;
}

function jsSlice($Str,$Start,$iEnd){
	if ($Start<0){
		$Start=strlen($Str)+$Start;
	}
	if ($iEnd<1){
		$iEnd=strlen($Str)+$iEnd;
	}
	return substr($Str,$Start,$iEnd-$Start);
}

function StrSplits($content, $start, $end) {
	$start = stripcslashes($start);
	$end = stripcslashes($end);
	$m = @explode($start,$content); 
	$a = array(); 
	$sum = count($m); 
	for ( $i = 1;$i < $sum;$i++ ) { 
		$my = @explode($end,$m[$i]); 
		$a[] = $my[0];
		unset($my); 
	} 
	return $a; 
}

function replacedirtyWords($str) {
	$mystr = $str;
	$mystra = dirtyWords;
	if (empty($mystra)) { return $str;}
	$warray = explode(",", dirtyWords);
	$count = count($warray);
	for ($i = 0;$i < $count;$i++){
		$mystr=replaceStr($mystr, $warray[$i], "*");
	}
	return $mystr;
}

function getletterlist() {
	$mystr = '';
	for ($i = 65;$i <= 90;$i++) {
		$mystr.="<a href='/".sitePath."search.php?searchtype=4&searchword=".chr($i)."'>".chr($i)."</a>";
	}
	return $mystr;
}

function getSubStrByFromAndEnd($str, $startStr, $endStr, $operType) {
	switch ($operType) {
		case "start":
		    $location1=strpos($str,$startStr)+strlen($startStr);$location2=strlen($str)+1;
		break;
		case "end":
		    $location1=1;$location2=strpos($str,$endStr,$location1);
		break;
		default:
		    $location1=strpos($str,$startStr)+strlen($startStr);$location2=strpos($str,$endStr,$location1);
	}
	return substr($str,$location1,$location2-$location1);
}

function getArrayElementID($parray,$itemid,$compareValue){
	$l = count($parray[0]);
	for ($i = 0;$i < $l;$i++) {
		if (trim($parray[$itemid][$i])==trim($compareValue)){
			$getArrayElementID=$i;
			return $getArrayElementID;
	    }
    }
}

function getPlayerIntroArrayOnCache($str){
	if ($str=="play") $i=0;else $i=1;
    $cacheName="array_".$str."list";
	if (cacheStart==1) {
		if (!$gPlayerIntroArray[$i] = memory('get', $cacheName)) {
            $gPlayerIntroArray[$i]=getPlayerIntroArray($str);
			memory('set', $cacheName, $gPlayerIntroArray[$i]);
        }
	} else {
		$gPlayerIntroArray[$i] = getPlayerIntroArray($str);
	}
	return $gPlayerIntroArray[$i];
}

function getPlayerIntroArray($str){
	$temp=array();
	if ($str == 'play') {
		$xml = loadFile(DJ_ROOT."inc/playerKinds.xml");
		$xml = StrSlice($xml,'<playerkinds>','</playerkinds>');
		$nodes = getruleval($xml,'player');
		foreach($nodes as $f => $v){
			$temp[0][$f] = StrSlice($v,'flag="','"');
		    $temp[1][$f] = StrSlice($v,'<intro><![CDATA[',']]></intro>')."__djcms__".StrSlice($v,'open="','"');
		    $temp[2][$f] = StrSlice($v,'sort="','"');
	    }
	} elseif($str == 'down') {
		$xml = loadFile(DJ_ROOT."inc/downKinds.xml");
		$nodes = getruleval($xml,'source');
		foreach($nodes as $f => $v){
			$temp[0][$f] = StrSlice($v,'flag="','"');
		    $temp[1][$f] = StrSlice($v,'<intro><![CDATA[',']]></intro>')."__djcms__".StrSlice($v,'open="','"');
		    $temp[2][$f] = 0;
	    }
	}
	for ($i = 0;$i < $f;$i++) {
		for ($j = ($i+1);$j < $f;$j++) {
			if ($temp[2][$i] < $temp[2][$j]){
				$tmp=$temp[0][$j];$temp[0][$j]=$temp[0][$i];$temp[0][$i]=$tmp;
				$tmp=$temp[1][$j];$temp[1][$j]=$temp[1][$i];$temp[1][$i]=$tmp;
				$tmp=$temp[2][$j];$temp[2][$j]=$temp[2][$i];$temp[2][$i]=$tmp;
		    }
	    }
	}
	return $temp;
}

function getPlayerIntroOnCache($str,$flag){
	$playerArray=getPlayerIntroArrayOnCache($str);
	return $playerArray[1][getArrayElementID($playerArray,0,$flag)];
}

function ResetFromSort($sData){
	if ($sData=="") return '';
	$dd = getPlayurlArray($sData);$dl = count($dd);
	if ($dl>0){
		$ay = getPlayerIntroArrayOnCache("play");
		$ul = count($ay[0]);$ret="";$li=array();
		for ($i = 0;$i < $dl;$i++) {
			$ff = explode("$$",$dd[$i]);$j = getArrayElementID($ay,0,$ff[0]);
			if ("".$li[$j]<>""){
				$li[$j] = $li[$j]."$$$".$dd[$i];
			}else{
				$li[$j] = $dd[$i];
			}
		}
		for ($i = 0;$i < $ul;$i++) {
			if ($li[$i]<>""){
			    if ($ret<>"") $ret .= "$$$".$li[$i];else $ret=$li[$i];
			}
		}
		return $ret;
	}else{
		return $sData;
	}
}

function getTextsegments(){
	$xml = file_get_contents(DJ_ROOT."inc/textsegment.xml");
	$nodes = getrulevaluearr($xml,'item');
    foreach($nodes as $f => $v){
        $ret[$f] = StrSlice($v,'<item><![CDATA[',']]></item>');
    }
	return $ret;
}

function getTextsegmentsOnCache(){
	$cacheName="array_textsegmentlist";
	if (cacheStart==1) {
		if (!$ret = memory('get', $cacheName)) {
            $ret=getTextsegments();
			memory('set', $cacheName, $ret);
        }
    }else{
		$ret=getTextsegments();
	}
	return $ret;
}

function doPseudo($des,$iId){
	$iType=($iId % 3);$ts=getTextsegmentsOnCache();$l=count($ts)+1;
	if ($l==0 || $des==""){
		$doPseudo=$des;
	}elseif ($iType==1){
		$doPseudo=$ts[($iId % $l)].$des;
	}elseif ($iType==2){
		$doPseudo=$des.$ts[($iId % $l)];
	}else{
		$pos=strpos($des,"<br>");
		if ($pos==0) $pos=strpos($des,"<br/>");
		if ($pos==0) $pos=strpos($des,"<br />");
		if ($pos==0) $pos=strpos($des,"\n");
		if ($pos==0) $pos=(strpos($des,"。")+1);
		if ($pos>0){
			$doPseudo = substr($des,1,$pos-1).$ts[($iId % $l)].substr($des,$pos);
        }else{
			$doPseudo=$ts[($iId % $l)].$des;
        }
    }
	return $des;
}

function getRemoteContent($url, $conall = null) {
	$purl = parse_url($url);
	$con = '';
	$host = $purl['host'];
	$path = $purl['path'];
	$port = empty($purl['port']) ? 80 : $purl['port'];

	if (isset($purl['query']))
		$path.='?'.$purl['query'];
	    $fp = fsockopen($host, $port, $errno, $errstr, 10);
	if (!$fp) {
		return false;
	} else {
		$out = "GET $path HTTP/1.1\r\n";
		$out.= "Accept: */*\r\n";
		$out.= "Accept-Language: zh-cn\r\n";
		$out.= "Referer: http://$host\r\n";
		$out.= "User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322)\r\n";
		$out.= "Host: $host\r\n";
		$out.= "Connection: Close\r\n";
		$out.="\r\n";
	    fwrite($fp, $out);
	    while (!feof($fp)) {
	        $con.= fgets($fp, 1024);
	    }
	    fclose($fp);
	}

    if ($conall == null) {
		$tmp = explode("\r\n\r\n",$con,2);
		$con = empty($tmp[1]) ? '' : $tmp[1];
    }
	return $con;
}

function writeFontWaterPrint($imgSrc)
{
	if(marktype == 'text'){
        imageWaterMark(DJ_ROOT.$imgSrc,waterlocation,"",watermarkfont,watermarksize,watermarkcolor,DJ_ROOT.fonttype);
    }else{
        imageWaterMark(DJ_ROOT.$imgSrc,waterlocation,DJ_ROOT.markimg);
    }
}

function imageWaterMark($groundImage,$waterPos=0,$waterImage="",$waterText="",$fontSize=12,$textColor="#CCCCCC", $fontfile='./inc/data/ant2.ttf',$xOffset=0,$yOffset=0) 
{ 
     $isWaterImage = FALSE; 
     //读取水印文件 
     if(!empty($waterImage) && file_exists($waterImage)) { 
         $isWaterImage = TRUE; 
         $water_info = getimagesize($waterImage); 
         $water_w     = $water_info[0];//取得水印图片的宽 
         $water_h     = $water_info[1];//取得水印图片的高 

         switch($water_info[2])   {    //取得水印图片的格式  
             case 1:$water_im = imagecreatefromgif($waterImage);break; 
             case 2:$water_im = imagecreatefromjpeg($waterImage);break; 
             case 3:$water_im = imagecreatefrompng($waterImage);break; 
             default:return 1; 
         } 
     } 

     //读取背景图片 
     if(!empty($groundImage) && file_exists($groundImage)) { 
         $ground_info = getimagesize($groundImage); 
         $ground_w     = $ground_info[0];//取得背景图片的宽 
         $ground_h     = $ground_info[1];//取得背景图片的高 

         switch($ground_info[2]) {    //取得背景图片的格式  
             case 1:$ground_im = imagecreatefromgif($groundImage);break; 
             case 2:$ground_im = imagecreatefromjpeg($groundImage);break; 
             case 3:$ground_im = imagecreatefrompng($groundImage);break; 
             default:return 1; 
         } 
     } else { 
         return 2; 
     } 

     //水印位置 
     if($isWaterImage) { //图片水印  
         $w = $water_w; 
         $h = $water_h; 
         $label = "图片的";
         } else {  
     //文字水印 
        if(!file_exists($fontfile))return 4;
         $temp = imagettfbbox($fontSize,0,$fontfile,$waterText);//取得使用 TrueType 字体的文本的范围 
         $w = $temp[2] - $temp[6]; 
         $h = $temp[3] - $temp[7]; 
         unset($temp); 
     } 
     if( ($ground_w < $w) || ($ground_h < $h) ) { 
         return 3; 
     } 
     switch($waterPos) { 
         case 0://随机 
             $posX = rand(0,($ground_w - $w)); 
             $posY = rand(0,($ground_h - $h)); 
             break; 
         case 1://1为顶端居左 
             $posX = 0; 
             $posY = 0; 
             break; 
         case 2://2为顶端居中 
             $posX = ($ground_w - $w) / 2; 
             $posY = 0; 
             break; 
         case 3://3为顶端居右 
             $posX = $ground_w - $w; 
             $posY = 0; 
             break; 
         case 4://4为中部居左 
             $posX = 0; 
             $posY = ($ground_h - $h) / 2; 
             break; 
         case 5://5为中部居中 
             $posX = ($ground_w - $w) / 2; 
             $posY = ($ground_h - $h) / 2; 
             break; 
         case 6://6为中部居右 
             $posX = $ground_w - $w; 
             $posY = ($ground_h - $h) / 2; 
             break; 
         case 7://7为底端居左 
             $posX = 0; 
             $posY = $ground_h - $h; 
             break; 
         case 8://8为底端居中 
             $posX = ($ground_w - $w) / 2; 
             $posY = $ground_h - $h; 
             break; 
         case 9://9为底端居右 
             $posX = $ground_w - $w; 
             $posY = $ground_h - $h; 
             break; 
         default://随机 
             $posX = rand(0,($ground_w - $w)); 
             $posY = rand(0,($ground_h - $h)); 
             break;     
     } 

     //设定图像的混色模式 
     imagealphablending($ground_im, true); 

     if($isWaterImage) { //图片水印 
         imagecopy($ground_im, $water_im, $posX + $xOffset, $posY + $yOffset, 0, 0, $water_w,$water_h);//拷贝水印到目标文件         
     } else {//文字水印
         if( !empty($textColor) && (strlen($textColor)==7) ) { 
             $R = hexdec(substr($textColor,1,2)); 
             $G = hexdec(substr($textColor,3,2)); 
             $B = hexdec(substr($textColor,5)); 
         } else { 
           return 5;
         } 
         imagettftext ( $ground_im, $fontSize, 0, $posX + $xOffset, $posY + $h + $yOffset, imagecolorallocate($ground_im, $R, $G, $B), $fontfile, $waterText);
     } 

     //生成水印后的图片 
     @unlink($groundImage); 
     switch($ground_info[2]) {//取得背景图片的格式 
         case 1:imagegif($ground_im,$groundImage);break; 
         case 2:imagejpeg($ground_im,$groundImage);break; 
         case 3:imagepng($ground_im,$groundImage);break; 
         default: return 6; 
     } 

     //释放内存 
     if(isset($water_info)) unset($water_info); 
     if(isset($water_im)) imagedestroy($water_im); 
     unset($ground_info); 
     imagedestroy($ground_im); 
     //
     return 0;
}

function flashslide($Slidewidth, $Slideheight) {
    $flashslide = "<script type=text/javascript>\n";
	$flashslide .= "var pic_width=".$Slidewidth."; //图片宽度\n";
	$flashslide .= "var pic_height=".$Slideheight."; //图片高度\n";
	$flashslide .= "var button_pos=4; //按扭位置 1左 2右 3上 4下\n";
	$flashslide .= "var stop_time=3000; //图片停留时间(1000为1秒钟)\n";
	$flashslide .= "var show_text=0; //是否显示文字标签 1显示 0不显示\n";
	$flashslide .= "var txtcolor=\"000000\"; //文字色\n";
	$flashslide .= "var bgcolor=\"DDDDDD\"; //背景色\n";
	$flashslide .= "var imag=new Array();\n";
	$flashslide .= "var link=new Array();\n";
	$flashslide .= "var text=new Array();\n";
	$i=0;
    $query = DB::query("SELECT m_id,m_name,m_pic,m_url,m_des,m_sort FROM ".DB::table('slide')." Order by m_sort asc,m_id desc");
    while ($row = DB::fetch($query)) {
	    $i++;
		if (stristr($row['m_pic'], "http://")) {
			$images = $row['m_pic'];
		} else {
			$images = '/'.sitePath."pic/slide/".$row['m_pic'];
		}
		$flashslide .= "imag[".$i."]=\"".$images."\";\n";
		$flashslide .= "text[".$i."]=\"".$row['m_name']."\";\n";
		$flashslide .= "link[".$i."]=\"".$row['m_url']."\";\n";
	}
	$flashslide .= "var swf_height=show_text==1?pic_height+20:pic_height;\n";
	$flashslide .= "var pics=\"\", links=\"\", texts=\"\";\n";
	$flashslide .= "for(var i=1; i<imag.length; i++){\n";
	$flashslide .= "pics=pics+(\"|\"+imag[i]);\n";
	$flashslide .= "links=links+(\"|\"+link[i]);\n";
	$flashslide .= "texts=texts+(\"|\"+text[i]);\n";
	$flashslide .= "}\n";
	$flashslide .= "pics=pics.substring(1);\n";
	$flashslide .= "links=links.substring(1);\n";
	$flashslide .= "texts=texts.substring(1);\n";
	$flashslide .= "document.write('<object classid=\"clsid:d27cdb6e-ae6d-11cf-96b8-444553540000\" codebase=\"http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cabversion=6,0,0,0\" width=\"'+ pic_width +'\" height=\"'+ swf_height +'\">');\n";
	$flashslide .= "document.write('<param name=\"movie\" value=\"/".sitePath."pic/slide/slide.swf\">');\n";
	$flashslide .= "document.write('<param name=\"quality\" value=\"high\"><param name=\"wmode\" value=\"opaque\">');\n";
	$flashslide .= "document.write('<param name=\"FlashVars\" value=\"pics='+pics+'&links='+links+'&texts='+texts+'&pic_width='+pic_width+'&pic_height='+pic_height+'&show_text='+show_text+'&txtcolor='+txtcolor+'&bgcolor='+bgcolor+'&button_pos='+button_pos+'&stop_time='+stop_time+'\">');\n";
	$flashslide .= "document.write('<embed src=\"/".sitePath."pic/slide/slide.swf\" wmode=\"opaque\" FlashVars=\"pics='+pics+'&links='+links+'&texts='+texts+'&pic_width='+pic_width+'&pic_height='+pic_height+'&show_text='+show_text+'&txtcolor='+txtcolor+'&bgcolor='+bgcolor+'&button_pos='+button_pos+'&stop_time='+stop_time+'\" quality=\"high\" width=\"'+ pic_width +'\" height=\"'+ swf_height +'\" allowScriptAccess=\"sameDomain\" type=\"application/x-shockwave-flash\" pluginspage=\"http://www.macromedia.com/go/getflashplayer\" />');\n";
	$flashslide .= "document.write('</object>');\n";
	$flashslide .= "</script>";
	return $flashslide;
}

function ifthen($Bol, $val, $val2) {
	if ($Bol == true){
		return $val;
	}else{
		return $val2;
	}

}

function parseNewsNote($by){
	return ifthen($by==64,"[荐]","").ifthen($by==128,"[图]","").ifthen($by==32,"[视]","");
}

function Str2Num($sNum){
	if (!is_numeric($sNum)) return 0;
	return intval($sNum);
}

function PlayData2Json($playData){
	$x = explode("$$$",$playData);$l=count($x);$r=array();$j=0;
	for ($i = 0;$i < $l;$i++) {
		$y=explode("$$",$x[$i]);$z=getPlayerIntroArray("play",$y[0]);
		if (strpos(" ".$z,"djcms__0")==0) {
			$y[0] = "'".$y[0]."'";$y[1]=unescape(ReplaceStr(escape(join("','",explode("#",$y[1]))),"%u","\u"));
			$y[1] = ifthen($y[1]<>"","['".$y[1]."']","[]");
			$r[$j] = "[".$y[0].",".$y[1]."]";$j=$j+1;
	    }
	}
	$j=join(",",$r);
	return ifthen($j<>"","[".$j."]","[]");
}

function PlayData2Json2($playData){
    $x = explode("$$$",$playData);$l=count($x);$r=array();$y=array();$ary=array();$ret=array("[%s]",0,array());$k=0;
	for ($i = 0;$i < $l;$i++) {
		$y=explode("$$",$x[$i]);$z=getPlayerIntroArray("play",$y[0]);
		if (strpos(" ".$z,"djcms__0")==0) {
			$f[$k]=$y[0];
			$y[0]="'".$y[0]."'";$pn=explode("#",$y[1]);$t=array();$q=array();$it=0;
			$pnl=count($pn);
			for ($j = 0;$j < $pnl;$j++) {
				$p=strpos($pn[$j],"$");
				if ($p>0){
					$t[$it]=$pn[$j];$q[$it]=substr($pn[$j],1,$p-1);
					$it=$it+1;
			    }
			}
			$y[1]=unescape(replaceStr(escape(join("','",$t)),"%u","\u"));$y[1]=ifthen($y[1]<>"","['".$y[1]."']","[]");
			$r[$k]="[".$y[0].",".$y[1]."]";$ary[$k]=$pn;$k=$k+1;
		}
	}
	$ret[1]=$k-1;$ret[2]=$ary;;$ret[3]=$f;
	$ret[0]=replaceStr($ret[0],"%s",join(",",$r));
	return $ret;
}

function libfile($libname, $folder = '') {
	$libpath = DJ_ROOT.'/inc/'.$folder;
	if(strstr($libname, '/')) {
		list($pre, $name) = explode('/', $libname);
		return realpath("{$libpath}/{$pre}/{$pre}_{$name}.php");
	} else {
		return realpath("{$libpath}/{$libname}.php");
	}
}


function memory($cmd, $key='', $value='', $ttl = 0) {
	require_once libfile('cache/'.cachetype);
	if(in_array($cmd, array('set', 'get', 'rm', 'clear'))) {
		switch ($cmd) {
			case 'set': return cache::set($key, $value, $ttl); break;
			case 'get': return cache::get($key); break;
			case 'rm': return cache::delete($key); break;
			case 'clear': return cache::flush(); break;
		}
	}
	return null;
}

function OutNotFound($flag){
	die(loadFileOnCache("djcms404".$flag,DJ_ROOT."/".sitePath."djcms404.html"));
}
?>
