<?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) {
	echo "".$str.",稍后将自动返回<script language='javascript'>setTimeout('goLastPage()','".$timenum."000');function goLastPage(){history.go(-1);}</script>&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 get($url) {
	return @file_get_contents($url);
}

function AjaxHead() {
	@header("Pragma:no-cache\r\n");
	@header("Cache-Control:no-cache\r\n");
	@header("Expires:0\r\n");
}

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 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 = "<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>" ;
	echo $cssstr.$errstr;
}

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($var, $value = '', $life = 0, $prefix = 1, $httponly = false) {
	$_COOKIE[$var] = $var;
	if($value == '' || $life < 0) {
		$value = '';
		$life = -1;
	}

	$life = $life > 0 ? TIMESTAMP + $life : ($life < 0 ? TIMESTAMP - 31536000 : 0);
	$path = $httponly && PHP_VERSION < '5.2.0' ? '/'.'; HttpOnly' : '/';

	$secure = $_SERVER['SERVER_PORT'] == 443 ? 1 : 0;
	if(PHP_VERSION < '5.2.0') {
		setcookie($var, $value, $life, $path, $_SERVER['SERVER_NAME'], $secure);
	} else {
		setcookie($var, $value, $life, $path, $_SERVER['SERVER_NAME'], $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 getRunTime($t1)
{
	global $db;
	$t2 = ExecTime() - $t1;
	return "页面执行时间: ".number_format($t2, 4)."秒&nbsp;".$db->querynum."次数据查询";;
}

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 getAgent()
{
	return $_SERVER['HTTP_USER_AGENT'];
}

function getRefer()
{
	return $_SERVER['HTTP_REFERER'];
}

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 MyDate($format = 'Y-m-d H:i:s', $timest = 0)
{
	$addtime = 8 * 3600;
	if (empty($format)) {
		$format = 'Y-m-d H:i:s';
	}
	return gmdate ($format, $timest+$addtime);
}

//写入文件
function createTextFile($content, $path)
{
	$path=replaceStr($path, "..", "");
	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)
{
	$reString = "";
	preg_match_all("/[\x80-\xff].|[\x01-\x7f]+/",$str,$newstr);
	$ar = $newstr[0];
	foreach ($ar as $k => $v) {
		if (ord($ar[$k]) >= 127) {
			if (function_exists("mb_convert_encoding")) {
				$tmpString = bin2hex(mb_convert_encoding($v, "ucs-2", "GBK"));
			} else if (function_exists("iconv")) {
				$tmpString=bin2hex(iconv("GBK", "ucs-2", $v));
			}
			if (strpos(PHP_OS, 'WIN') === false){
			    $tmpString = substr($tmpString,2,2).substr($tmpString, 0, 2);
			}
			$reString.= "%u".$tmpString;
		} else {
			$reString.= rawurlencode($v);
		}
	}
	return $reString;
}

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] = iconv("UCS-2","GB2312",pack("H4",substr($v,-4)));
  }
  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 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[0] = $paras[1];
		    $getPlayerParas[1] = $paras[2];
	    } else {
		    $getPlayerParas[0] = -1;
		    $getPlayerParas[1] = -1;
	    }
	}else{
		global $parampage,$paramindex;
		$getPlayerParas[0] = $parampage;
		$getPlayerParas[1] = $paramindex;
	}
	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.="<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)) {
        } else {
			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) {
	$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";
    $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":
			$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":
			$cssstr .= "<div id='msg'><div class='msgtitle'>【警告】参数错误：</div><div id='msgbody'><b>错误描述</b>：参数为空或不正确</div><div id='msgbottom'>Powered By ".siteName."</div></div>";
		break;
	}
	echo $cssstr;exit();
}

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

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

function isCurrentDay($timeStr) {
	if (empty($timeStr)) return "";
	if (MyDate("Y-m-d", $timeStr) == MyDate("Y-m-d", time())) {
		return "<span style='color:red;font-size:10px'>".MyDate('Y-m-d H:i:s',$timeStr)."</span>";
	} else {
		return "<span style='font-size:10px'>".MyDate('Y-m-d H:i:s',$timeStr)."</span>";
	}
}

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 StrSlice($str,$startStr,$endStr){
    $strtemp1 = explode($startStr, $str);
    $strtemp2 = explode($endStr, $strtemp1[1]);
    return $strtemp2[0];
}

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 getPlayerIntroArray($str) {
	$temp=array();
	if ($str == 'play') {
		$m_file = DJ_ROOT."inc/playerKinds.inc";
	} else {
		$m_file = DJ_ROOT."inc/downKinds.inc";
    }
	$allPlayerKinds = file($m_file);
	foreach ($allPlayerKinds as $k=>$v) {
		$v = trim($v);
		if ($v!="") {
		    $vstr = explode("|",$v);
		    if (count($vstr)>0) {
		        $temp[$k]['flag']=$vstr[0];
		        $temp[$k]['open']=$vstr[3];
		        $temp[$k]['sort']=$vstr[4];
		    }
		}
	}
	$l = count($temp);
	for ($i = 0;$i <= $l;$i++) {
		for ($j = ($i+1);$j < $l;$j++) {
			if ($temp[$i]['sort'] < $temp[$j]['sort']) {
				$tmp = $temp[$j];$temp[$j] = $temp[$i];$temp[$i] = $tmp;
			}
		}
	}
	return $temp;
}

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

function getPlayerKindsArray($str) {
	$PlayerKindsArray=array();
	if ($str == 'play') {
		$m_file = DJ_ROOT."inc/playerKinds.inc";
	} else {
		$m_file = DJ_ROOT."inc/downKinds.inc";
    }
	$allPlayerKinds = file($m_file);
	foreach ($allPlayerKinds as $v) {
		$v = trim($v);
		if ($v!="") {
		   $vstr = explode("|",$v);
		   $count=count($vstr);
		    if ($count>0) {
		        $PlayerKindsArray[$vstr[0]]['des']=$vstr[1];
		        $PlayerKindsArray[$vstr[0]]['intro']=$vstr[2];
		        $PlayerKindsArray[$vstr[0]]['open']=$vstr[3];
		    }
		}
	}
	return $PlayerKindsArray;
}

function cget($url,$isref) {
	if ($isref == 1) return getRemoteContent($url);else return get($url);
}

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;
}

$UC2GBTABLE = $CODETABLE = $BIG5_DATA = $GB_DATA = '';
//UTF-8 转GB编码
function utf82gb($utfstr) {
	if (function_exists('iconv')) {
		return iconv('utf-8','gbk//ignore',$utfstr);
	}
	global $UC2GBTABLE;
	$okstr = "";
	if (trim($utfstr)=="") {
		return $utfstr;
	}
	if (empty($UC2GBTABLE)) {
		$filename = DJ_ROOT."inc/data/gb2312-utf8.dat";
		$fp = fopen($filename,"r");
		while ($l = fgets($fp,15)) {
			$UC2GBTABLE[hexdec(substr($l, 7, 6))] = hexdec(substr($l, 0, 6));
		}
		fclose($fp);
	}
	$okstr = "";
	$ulen = strlen($utfstr);
	for ($i = 0;$i < $ulen;$i++) {
		$c = $utfstr[$i];
		$cb = decbin(ord($utfstr[$i]));
		if (strlen($cb) == 8) {
			$csize = strpos(decbin(ord($cb)),"0");
			for ($j = 0;$j < $csize;$j++) {
				$i++; $c .= $utfstr[$i];
			}
			$c = utf82u($c);
			if (isset($UC2GBTABLE[$c])) {
				$c = dechex($UC2GBTABLE[$c]+0x8080);
				$okstr .= chr(hexdec($c[0].$c[1])).chr(hexdec($c[2].$c[3]));
			} else {
				$okstr .= "&#".$c.";";
			}
		} else {
			$okstr .= $c;
		}
	}
	$okstr = trim($okstr);
	return $okstr;
}


//GB转UTF-8编码
function gb2utf8($gbstr) {
	if (function_exists('iconv')) {
		return iconv('gbk','utf-8//ignore',$gbstr);
	}
	global $CODETABLE;
	if (trim($gbstr)=="") {
		return $gbstr;
	}
	if (empty($CODETABLE)) {
		$filename = DJ_ROOT."inc/data/gb2312-utf8.dat";
		$fp = fopen($filename,"r");
		while ($l = fgets($fp,15)) {
			$CODETABLE[hexdec(substr($l, 0, 6))] = substr($l, 7, 6);
		}
		fclose($fp);
	}
	$ret = "";
	$utf8 = "";
	while ($gbstr != '') {
		if (ord(substr($gbstr, 0, 1)) > 0x80) {
			$thisW = substr($gbstr, 0, 2);
			$gbstr = substr($gbstr, 2, strlen($gbstr));
			$utf8 = "";
			@$utf8 = u2utf8(hexdec($CODETABLE[hexdec(bin2hex($thisW)) - 0x8080]));
			if ($utf8!="") {
				for ($i = 0;$i < strlen($utf8);$i += 3)
				$ret .= chr(substr($utf8, $i, 3));
			}
		} else {
			$ret .= substr($gbstr, 0, 1);
			$gbstr = substr($gbstr, 1, strlen($gbstr));
		}
	}
	return $ret;
}

//unicode url编码转gbk编码函数
function UnicodeUrl2Gbk($str) {
	//载入对照词典
	if (!isset($GLOBALS['GbkUniDic'])) {
		$fp = fopen(DJ_ROOT.'inc/data/gbk-unicode.dat','rb');
		while (!feof($fp)) {
			$GLOBALS['GbkUniDic'][bin2hex(fread($fp,2))] = fread($fp,2);
		}
		fclose($fp);
	}

	//处理字符串
	$str = str_replace('$#$','+',$str);
	$glen = strlen($str);
	$okstr = "";
	for ($i=0; $i < $glen; $i++) {
		if ($glen-$i > 4) {
			if ($str[$i]=='%' && $str[$i+1]=='u') {
				$uni = strtolower(substr($str,$i+2,4));
				$i = $i+5;
				if (isset($GLOBALS['GbkUniDic'][$uni])) {
					$okstr .= $GLOBALS['GbkUniDic'][$uni];
				} else {
					$okstr .= "&#".hexdec('0x'.$uni).";";
				}
			} else {
				$okstr .= $str[$i];
			}
		} else {
			$okstr .= $str[$i];
		}
	}
	return $okstr;
}

function writeFontWaterPrint($img, $alpha = 80) {
	$image_size = getimagesize($img);
    switch ($image_size[2]) {
        case 1:
            $im = @imagecreatefromgif($img);
            break;
        case 2:
            $im = imagecreatefromjpeg($img);
            break;
        case 3:
            $im = imagecreatefrompng($img);
            break;
        default:
            $im = imagecreatefromstring($img);
    }
    $image_width = $image_size[0];$image_height = $image_size[1];
    $font_type = DJ_ROOT."inc/data/ant2.ttf";
    $line = count(explode("\n", watermarkfont));
    $temp = imagettfbbox(watermarksize, 0, $font_type, watermarkfont);
    $mark_width = $temp[2] - $temp[6]; $mark_height = $line*($temp[3] - $temp[7]);
	unset($temp);
    if (($image_width < $mark_width) || ($image_height < $mark_height)) {
	    return false;
    }
	switch (waterlocation) {
        case 0://随机
            $posX = rand(0,($image_width - $mark_width));
            $posY = rand(0,($image_height - $mark_height));
            break;
        case 1://1为顶端居左
            $posX = 0;
            $posY = $mark_height;
            break;
        case 2://2为顶端居中
            $posX = ($image_width - $mark_width) / 2;
            $posY = $mark_height;
            break;
        case 3://3为顶端居右
            $posX = $image_width - $mark_width;
            $posY = $mark_height;
            break;
        case 4://4为中部居左
            $posX = 0;
            $posY = ($image_height - $mark_height) / 2;
            break;
        case 5://5为中部居中
            $posX = ($image_width - $mark_width) / 2;
            $posY = ($image_height - $mark_height) / 2;
            break;
        case 6://6为中部居右
            $posX = $image_width - $mark_width;
            $posY = ($image_height - $mark_height) / 2;
            break;
        case 7://7为底端居左
            $posX = 0;
            $posY = $image_height - $mark_height;
            break;
        case 8://8为底端居中
            $posX = ($image_width - $mark_width) / 2;
            $posY = $image_height - $mark_height;
            break;
        case 9://9为底端居右
            $posX = $image_width - $mark_width;
            $posY = $image_height - $mark_height;
            break;
        default://随机
            $posX = rand(0,($image_width - $mark_width));
            $posY = rand(0,($image_height - $mark_height));
            break;
    }
    if (preg_match("/([a-f0-9][a-f0-9])([a-f0-9][a-f0-9])([a-f0-9][a-f0-9])/i", watermarkcolor, $color)) {
        $red = hexdec($color[1]);
        $green = hexdec($color[2]);
        $blue = hexdec($color[3]);
        $text_color = imagecolorallocate($im, $red,$green,$blue);
    } else {
        $text_color = imagecolorallocate($im, 255, 255, 255);
    }
    imagettftext($im, watermarksize, 0, $posX, $posY, $text_color, $font_type, watermarkfont);
	switch ($image_size[2]) {
        case '1': imagegif($im, $img);break;
        case '2': imagejpeg($im, $img, $alpha);break;
        case '3': imagepng($im, $img);break;
        default : imagejpeg($im, $img, $alpha);break;
    }
    imagedestroy($im);
}

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 SpHtml2Text($str) {
	$str = preg_replace("/<sty(.*)\\/style>|<scr(.*)\\/script>|<!--(.*)-->/isU", "", $str);
	$alltext = "";
	$start = 1;
	for ($i = 0;$i < strlen($str);$i++) {
		if ($start == 0 && $str[$i] == ">") {
			$start = 1;
		} else if ($start == 1) {
			if ($str[$i] == "<") {
				$start = 0;
				$alltext .= " ";
			} else if (ord($str[$i]) > 31){
				$alltext .= $str[$i];
			}
		}
	}
	$alltext = str_replace("　", " ", $alltext);
	$alltext = preg_replace("/&([^;&]*)(;|&)/", "", $alltext);
	$alltext = preg_replace("/[ ]+/s", " ", $alltext);
	return $alltext;
}

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 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,"maxcc__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,"maxcc__0")==0) {
			$y[0]="'".$y[0]."'";
			$pn=explode("#",empty($y[1]) ? '' : $y[1]);
			$y[1]=unescape(replaceStr(escape(join($pn,"','")),"%u","\u"));$y[1]=ifthen($y[1]<>"","['".$y[1]."']","[]");
			$pnl=count($pn);
			for ($j = 0;$j < $pnl;$j++) {
			    $yl=explode("$",$pn[$j]);
			    $pn[$j]=$yl[0];
			}
			$r[$k]="[".$y[0].",".$y[1]."]";$ary[$k]=$pn;$k=$k+1;
		}
	}
	$ret[1]=$k-1;$ret[2]=$ary;
	$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) {
	global $_config;
	$discuz = new discuz_memory();
	$discuz->init($_config['memory']);
	if($cmd == 'check') {
		return  $discuz->mem->enable ? $discuz->mem->type : '';
	} elseif($discuz->mem->enable && in_array($cmd, array('set', 'get', 'rm', 'clear'))) {
		switch ($cmd) {
			case 'set': return $discuz->mem->set($key, $value, $ttl); break;
			case 'get': return $discuz->mem->get($key); break;
			case 'rm': return $discuz->mem->rm($key); break;
			case 'clear': return $discuz->mem->clear(); break;
		}
	}
	return null;
}

function memorya($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"));
}
?>
