<?php
if( !defined('ISDVBBS') ){
	header('HTTP/1.0 400 Bad Request');
	exit;
}

if (defined('GENERAL_FUNCTIONS')) {
	return;
}

define('GENERAL_FUNCTIONS', true);

!defined('TIME_NOW') AND define('TIME_NOW', time());
!defined('DATE_Z') AND define('DATE_Z', date('Z'));

function i_addslashes(&$string, $force = 0) {
	if(!$GLOBALS['magic_quotes_gpc'] || $force) {
		if(is_array($string)) {
			foreach($string as $key => $val) {
				$string[$key] = i_addslashes($string[$key], $force);
			}
		} else {
			$string = addslashes($string);
		}
	}
	return $string;
}
function checkIDList($id_list){
	if( $id_list.'' === '' ) return false;
	return ( preg_match('/^(?:[0-9]+,)+$/i',"{$id_list},") === 0 ? false : true );
}//end function checkIDList

/**
 * Description 根据系统时差返回日期/时间格式的值
 * @author @dvbbs
 * @return int 返回基于系统时差的日期/时间格式的值
 */
function dvgmdate($dateformat = 'Y-m-d H:i:s', $timestamp = TIME_NOW)
{
	if (empty($dateformat)) {
		$dateformat = 'Y-m-d H:i:s';
	}
	$user_timezone_offset = getUserTimeZoneOffset();
	return gmdate($dateformat, $timestamp+$user_timezone_offset);
}//end function dvgmdate

/**
 * Description 获取当前用户（包括游客）的时差的秒数
 * @author
 * @return int 返回当前用户（包括游客）的时差的秒数
 */
function getUserTimeZoneOffset()
{
	static $user_timezone_offset;
	if (!isset($timezoneoffset)) {
		if (defined('USER_TIMEZONE_OFFSET')) {
			$user_timezone_offset = USER_TIMEZONE_OFFSET;
		} else {
			global $userinfo;
			if (!empty($userinfo) AND is_numeric($userinfo['user_timezone_offset'])) {
				$user_timezone_offset = intval($userinfo['user_timezone_offset']);
			} elseif (is_numeric($offsetseconds = get_cookie('user_timezone_offset'))) {
				$user_timezone_offset = $offsetseconds;
			} elseif (isset($fsetting['timeoffset']) AND is_numeric($fsetting['timeoffset'])) {
				$user_timezone_offset = $fsetting['timeoffset'] * 3600;
			} else {
				$user_timezone_offset = date('Z');
			}
			define('USER_TIMEZONE_OFFSET', $user_timezone_offset);
		}
	}
	return $user_timezone_offset;
}//end function getUserTimeZoneOffset

/**
 * Description 返回已添加指定天数的日期（注：返回结果与时区无关）
 * @author
 * @param mixed 可以是任意可被识别为日期和时间的日期表达式或字符串表达式
 * @param mixed 可以是任意可被识别为日期和时间的日期表达式或字符串表达式
 * @return string 返回已添加指定天数的字符串表现形式的日期。失败返回-1
 */
function addDays($date, $days, $returntimestamp = false)
{
	if (0 == $days) {
		return $date;
	}
	if (!is_numeric($days)) {
		return -1;
	}
	if ($days > 0) {
		$days = '+'.$days;
	}
	if (is_numeric($date)) {
		if (true === $returntimestamp) {
			return strtotime($days.' day', $date);
		} else {
			return gmdate('Y-m-d H:i:s', strtotime($days.' day', $date));
		}
	} else {
		$timestamp = @strtotime($date);
		if (-1 == $timestamp OR false === $timestamp) {
			return -1;
		}
		if (true === $returntimestamp) {
			return strtotime($days.' day', $timestamp) + date('Z');
		} else {
			return gmdate('Y-m-d H:i:s', strtotime($days.' day', $timestamp) + date('Z'));
		}
	}

}//end function addDays

/**
 * Description 对指定的 date 返回特定的日期格式 format（注：返回结果与时区无关）
 * @author
 * @param mixed 可以是任意可被识别为日期和时间的日期表达式或字符串表达式
 * @param mixed 可以是任意可被识别为日期和时间的日期表达式或字符串表达式
 * @return string 返回日期的字符串表现形式。失败返回-1
 */
function dateFormat($date, $format)
{
	if (empty($date)) {
		return '';
	}
	if (is_numeric($date)) {
		return gmdate($format, $date);
	} else {
		if (!isDate($date)) {
			return -1;
		}
		$timestamp = @strtotime($date);
		if (-1 == $timestamp OR false === $timestamp) {
			return -1;
		}
		return gmdate($format, $timestamp + date('Z'));
	}
}//end function dateFormat

/**
 * Description 返回 Boolean 值指明某表达式是否是一个绝对日期/时间
 * @author
 * @param mixed 可以是任意可被识别为日期和时间的日期表达式或字符串表达式
 * @return Boolean 返回 Boolean 值指明某表达式是否是一个绝对日期/时间
 */
function isDate($mixed)
{
	if (empty($mixed)) {
		return false;
	}
	$timestamp = @strtotime($mixed);
	if (-1 == $timestamp OR false === $timestamp) {
		return false;
	}
	return true;
}//end function isDate

/**
 * Description 根据 date_part 返回两个日期 start_date 和 end_date 之间的时间间隔（注：返回结果与时区无关）
 * @author
 * @param string 表示要添加的时间间隔
 * @param string 合法的日期文字
 * @param string 合法的日期文字
 * @return int 返回两个日期之间的时间间隔
 */
function dateDiff($date_part, $start_date, $end_date)
{
	if (empty($start_date) OR empty($end_date)) {
		return false;
	}
	if (is_numeric($start_date) AND is_numeric($end_date)) {
		$starttimestamp = $start_date;
		$endtimestamp = $end_date;
	} else {
		if (!isDate($start_date) OR !isDate($end_date)) {
			return -1;
		}
		$starttimestamp = @strtotime($start_date);
		if (-1 == $starttimestamp OR false === $starttimestamp) {
			return false;
		}
		$endtimestamp = @strtotime($end_date);
		if (-1 == $endtimestamp OR false === $endtimestamp) {
			return false;
		}
	}
	$starttimestamp = $starttimestamp + date('Z');
	$endtimestamp = $endtimestamp + date('Z');

	switch(strtoupper(trim($date_part)))
	{
		case "S":
		case "SECOND"://按秒计算，精确到秒
		return intval($endtimestamp - $starttimestamp);
		break;
		case "M":
		case "MINUTE"://按分计算，精确到分
		$starttimestamp = $starttimestamp - ($starttimestamp % 60);
		$endtimestamp = $endtimestamp - ($endtimestamp % 60);
		return intval(($endtimestamp - $starttimestamp) / 60);
		break;
		case "H":
		case "HOUR"://按小时计算，精确到小时
		$starttimestamp = $starttimestamp - ($starttimestamp % 3600);
		$endtimestamp = $endtimestamp - ($endtimestamp % 3600);
		return intval(($endtimestamp - $starttimestamp) / 3600);
		break;
		case "D":
		case "DAY"://按天计算，精确到天
		$starttimestamp = $starttimestamp - ($starttimestamp % 86400);
		$endtimestamp = $endtimestamp - ($endtimestamp % 86400);
		return intval(($endtimestamp - $starttimestamp) / 86400);
		break;
		case "N":
		case "MONTH"://按月计算，精确到月
		$year_offset = intval(gmdate("Y",$endtimestamp)-gmdate("Y",$starttimestamp));
		$month_offset = intval(gmdate("m",$endtimestamp)-gmdate("m",$starttimestamp));
		return $year_offset*12+$month_offset;
		break;
		case "Y":
		case "YEAR"://按年计算，精确到年
		return intval(gmdate("Y",$endtimestamp)-gmdate("Y",$starttimestamp));
		break;
		case "WW":
		case "WEEK"://按星期计算，精确到星期
		$starttimestamp = $starttimestamp - ($starttimestamp % 86400);
		$endtimestamp = $endtimestamp - ($endtimestamp % 86400);
		return intval(($endtimestamp - $starttimestamp) / 604800);
		break;
		case "Q":
		case "QUARTER"://按季度计算，精确到季度
		$year_offset = intval(gmdate("Y",$endtimestamp)-gmdate("Y",$starttimestamp));
		$month_offset = intval(gmdate("m",$endtimestamp)-gmdate("m",$starttimestamp));
		return intval(($year_offset*12+$month_offset+1)/3);
		break;
		default:
			return FALSE;
	}
}//end function dateDiff

/**
 * Description 根据 date_part 在 date 上执行加 number 的操作（注：返回结果与时区无关）
 * @author
 * @param string 表示要添加的时间间隔
 * @param int 表示要添加的时间间隔的个数
 * @param mixed unix时间戳或要添加 date_part 的表示日期的文字(它应该是一个合法的日期文字)
 * @param string 指定返回值的日期格式，如果指定的值为空字符串、flase、null，则表明返回值是时间戳
 * @return mixed 返回已添加指定时间间隔的字符串表示的日期或时间戳。
 */
function dateAdd($date_part, $number, $date, $return_format="Y-m-d H:i:s")
{
	if (!is_numeric($number)) {
		return NULL;
	}
	$type = gettype($date);
	if ('integer' === $type OR 'float' === $type OR 'double' === $type) {
		$timestamp = intval($date);
	} elseif ('string' === $type) {
		if (!isDate($date)) {
			return NULL;
		}
		$timestamp = @strtotime($date);
		if (-1 == $timestamp OR false === $timestamp) {
			return false;
		}
	} else {
		return NULL;
	}
	$number = intval($number);
	$strtmp = '';
	$date_part = strtoupper(trim($date_part));
	switch ($date_part) {
		case 'Y':		//	按年进行计算
		case 'YEAR':	//	按年进行计算
		$strtmp = ' year ';
		break;
		case 'N':		//	按月进行计算
		case 'MONTH':	//	按月进行计算
		$strtmp = ' month ';
		break;
		case 'D':		//	按日进行计算
		case 'DAY':		//	按日进行计算
		$strtmp = ' day ';
		break;
		case 'H':		//	按小时进行计算
		case 'HOUR':	//	按小时进行计算
		$strtmp = ' hour ';
		break;
		case 'm':		//	按分钟进行计算
		case 'MINUTE':	//	按分钟进行计算
		$strtmp = ' minute ';
		break;
		case 's':		//	按秒钟进行计算
		case 'SECOND':	//	按秒钟进行计算
		$strtmp = ' second ';
		break;
		case 'ww':		//	按星期进行计算
		case 'WEEK':	//	按星期进行计算
		$strtmp = ' week ';
		break;
		case 'Q':		//	按季度进行计算
		case 'QUARTER':	//	按季度进行计算
		$number = $number * 3;
		$strtmp = ' month ';
		break;
		default:	//	如果没有指定日期格式，则返回时间戳
		$strtmp = '';
		return NULL;
		break;
	}//end switch
	if ($number >= 0) {
		$number = '+'.$number;
	}
	if ('' === trim($return_format)) {
		return strtotime($number.$strtmp, $timestamp);
	} else {
		return gmdate($return_format, strtotime($number.$strtmp, $timestamp));
	}
}//end function dateAdd

/**
 * Description 返回 $date 距离1970-01-01 00:00:00的秒数
 * @author
 * @param string 包含英文日期格式的字符串
 * @return int 成功返回 $date 距离1970-01-01 00:00:00的秒数，失败返回 false
 */
function dv_gmtimestamp($date)
{
	$timestamp = strtotime($date);
	if (-1 == $timestamp OR false === $timestamp) {
		return false;
	}
	return $timestamp + DATE_Z;
}//end function dv_gmtimestamp

function Dv_StrLength(&$str)
{
	$strtmp = trim($str);
	if ($strtmp === '') {
		return 0;
	}
	static $objenc;
	if (!isset($objenc)) {
		require_once INC_PATH.'DV_Encoding.class.php';
		$objenc = DV_Encoding::GetEncoding($GLOBALS['charset']);
	}
	return $objenc->StrLength($strtmp);
}//end function Dv_StrLength

function TestEmail($str_email){
	$str_email = trim($str_email);
	if( strlen($str_email) <= 0 ) return false;
	$str_reg1 = '(\\.@)|(@\\.)|(\\.{2,})';
	if( eregi($str_reg1,$str_email) ) return false;
	$str_reg2 = '^[0-9a-zA-Z_]{1}.*@(.+\\..+)+(\\..+)*$';
	if( eregi($str_reg2,$str_email) ) return true;
	else return false;
}//end function TestEmail

function EncodeUtf8(&$code,$srcEnc=''){
	return urlencode($code);
	global $fsetting;
	if( $srcEnc === '' ){
		$srcEnc = $fsetting['lang'];
	}
	if( $srcEnc == '' ){
		$srcEnc = 'gb2312';
	}
	return iconv($srcEnc,'utf-8',$code);
}//end funciton EncodeUtf8

function getRawUrl($useArgs=false){
	global $_SERVER;
	$scriptName = str_filter_xss($_SERVER['PHP_SELF'] ? $_SERVER['PHP_SELF'] : THIS_SCRIPT.".php");
	$scriptName=str_replace("//","/",$scriptName);
	if( $useArgs === true ){
		$queryString = '?'.str_filter_xss($_SERVER['QUERY_STRING']);
	} else{
		$queryString = '';
	}
	return "http://{$_SERVER['HTTP_HOST']}{$scriptName}{$queryString}";
}//end function getRawUrl

function getScriptUrl(){
	$rawUrl = getRawUrl();
	return substr($rawUrl,0,strrpos($rawUrl,'/')).'/';
}//end function getScriptUrl

function getScriptName(){
	static $scriptname;
	if (!isset($scriptname)) {
		global $fsetting, $HTTP_SERVER_VARS, $_SERVER;
		!isset($_SERVER) AND ($_SERVER =& $HTTP_SERVER_VARS);
		if (1 == $fsetting['bogushtml_settings']) {
			$scriptname = str_replace(array('\\', '//', getDocumentRoot(true)), array('/', '/', ''), $_SERVER['SCRIPT_FILENAME']);
		} else {
			if ($_SERVER['SCRIPT_NAME']) {
				$scriptname = $_SERVER['SCRIPT_NAME'];
			} elseif ($_SERVER['ORIG_SCRIPT_NAME']) {
				$scriptname = $_SERVER['ORIG_SCRIPT_NAME'];
			}  elseif ($_SERVER['PHP_SELF']) {
				$scriptname = $_SERVER['PHP_SELF'];
			} elseif ($_SERVER['PATH_INFO']) {
				$scriptname = $_SERVER['PATH_INFO'];
			} elseif ($_SERVER['ORIG_PATH_INFO']) {
				$scriptname = $_SERVER['ORIG_PATH_INFO'];
			} elseif ($_SERVER['REQUEST_URI']) {
				$scriptname = $_SERVER['REQUEST_URI'];
				if (false !== ($ipos = strpos($scriptname, '?'))) {
					$scriptname = substr($scriptname, 0, $ipos);
				}
			} elseif ($_SERVER['URL']) {
				$scriptname = $_SERVER['URL'];
				if (false !== ($ipos = strpos($scriptname, '?'))) {
					$scriptname = substr($scriptname, 0, $ipos);
				}
			}
		}
	}
	return $scriptname;
}//end function getScriptName
function getPathTranslated($reverseslash = true)
{
	static $pathtranslated;
	if (!isset($pathtranslated)) {
		global $fsetting, $HTTP_SERVER_VARS, $_SERVER;
		!isset($_SERVER) AND ($_SERVER =& $HTTP_SERVER_VARS);
		if ($_SERVER['SCRIPT_FILENAME']) {
			$pathtranslated = $_SERVER['SCRIPT_FILENAME'];
		} elseif ($_SERVER['ORIG_PATH_TRANSLATED']) {
			$pathtranslated = $_SERVER['ORIG_PATH_TRANSLATED'];
		} elseif ($_SERVER['PATH_TRANSLATED']) {
			$pathtranslated = $_SERVER['PATH_TRANSLATED'];
		}
		(true === $reverseslash) AND $pathtranslated AND ($pathtranslated = str_replace(array('\\', '//'), '/', $pathtranslated));
	}
	return $pathtranslated;
}//end function getPathTranslated
function getDocumentRoot($reverseslash = true)
{
	static $documentroot;
	if (!isset($documentroot)) {
		global $HTTP_SERVER_VARS, $_SERVER;
		!isset($_SERVER) AND ($_SERVER =& $HTTP_SERVER_VARS);
		if (getenv('DOCUMENT_ROOT')) {
			$documentroot = getenv('DOCUMENT_ROOT');
		} elseif ($_SERVER['DOCUMENT_ROOT']) {
			$documentroot = $_SERVER['DOCUMENT_ROOT'];
		} elseif ($_SERVER['PATH_TRANSLATED']) {	//	PHP4
			if (@is_dir($_SERVER['PATH_TRANSLATED'])) {
				$documentroot = $_SERVER['PATH_TRANSLATED'];
			} else {
				$pathtranslated = str_replace(array('\\', '//'), '/', $_SERVER['PATH_TRANSLATED']);
				$scripturi = getScriptName();
				$documentroot = str_replace($scripturi, '', $pathtranslated);
			}
		} elseif ($_SERVER['ORIG_PATH_TRANSLATED']) {	//	PHP5
			$pathtranslated = str_replace(array('\\', '//'), '/', $_SERVER['ORIG_PATH_TRANSLATED']);
			$scripturi = getScriptName();
			$documentroot = str_replace($scripturi, '', $pathtranslated);
		}
		(true === $reverseslash) AND $documentroot AND ($documentroot = str_replace(array('\\', '//'), '/', $documentroot));
	}
	return $documentroot;
}//end function getDocumentRoot

function &DV_GetStopWordList($encodingName='gbk'){
	static $cacheLang = array();
	$encodingName = strtolower(trim($encodingName));
	if( !isset($cacheLang[$encodingName]) ){
		$arrLang =& load_lang($arrLang,'ft_stopwords');
		foreach( $arrLang['ft_stopword_list']['PregRepl'] as $val ){
			$cacheLang[$encodingName]['PregRepl'][] = '/\b(?:'.preg_quote($val,'/').')\b/i';
		}
		foreach( $arrLang['ft_stopword_list']['StrRepl'] as $val ){
			$cacheLang[$encodingName]['StrRepl'][] = $val;
		}
	}
	return $cacheLang[$encodingName];
}//end function DV_GetStopWordList

function &DV_ChineseWordSegment($str,$encodingName='gbk'){
	static $objEnc = null;
	if( $objEnc === null ){
		if( !class_exists('DV_Encoding') ){
			require_once INC_PATH.'DV_Encoding.class.php';
		}
		$objEnc = DV_Encoding::GetEncoding($encodingName);
	}
	$strLen = $objEnc->StrLength($str);
	$returnVal = array();
	if( $strLen <= 1 ){
		return $str;
	}
	$arrStopWords =& DV_GetStopWordList();
	//过滤所有HTML标签
	$str = preg_replace('#<[a-zA-Z]+?.*?>|</[a-zA-Z]+?.*?>#is', '', $str);
	//过滤所有stopword
	$str = str_replace($arrStopWords['StrRepl'],' ',$str);
	$str = preg_replace($arrStopWords['PregRepl'],' ',$str);
	$arr = explode(' ',$str);
	foreach( $arr as $tmpStr ){
		if ( preg_match("/^[\\x00-\\x7f]+$/i",$tmpStr) === 1 ) {
			$returnVal[] = ' '.$tmpStr;
		} else{
			preg_match_all("/([a-zA-Z]+)/i", $tmpStr, $matches);
			if( !empty($matches) ){
				foreach( $matches[0] as $matche ){
					$returnVal[] = $matche;
				}
			}
			//过滤ASCII字符
			$tmpStr = preg_replace("/([\\x00-\\x7f]+)/i", '', $tmpStr);
			$strLen = $objEnc->StrLength($tmpStr)-1;
			for( $i = 0 ; $i < $strLen ; $i++ ){
				$returnVal[] = $objEnc->SubString($tmpStr,$i,2);
			}
		}
	}
	return $returnVal;
}//end function DV_ChineseWordSegment

function SimpleReplace($str){
	global $lang;
	static $keys = null;
	if( is_null($keys) ){
		$keys = array_keys($lang['ArrayRepl']);
	}
	static $vals = null;
	if( is_null($vals) ){
		$vals = array_values($lang['ArrayRepl']);
	}
	print str_replace($keys,$vals,$str);
}

function set_cookie($name, $value = "", $cookiedate = 0){
	global $_COOKIE,$_SERVER,$cookiedomain,$cookiepath,$cookieprename,$timestamp;
	empty($timestamp) AND ($timestamp = time());
	$cookiedomain = (empty($cookiedomain) OR $cookiedomain == "") ? ''  : $cookiedomain;
	$cookiepath   = (empty($cookiepath) OR $cookiepath   == "") ? '/' : $cookiepath;
	$name = $cookieprename.$name;
	$_COOKIE[$name] = $value;
	$tmpport = $_SERVER['SERVER_PORT'] == 443 ? 1 : 0;
	if (func_num_args() < 3) {
		if (($tmp = intval(get_cookie('selected_cookiedate'))) > 0) {
			$cookiedate = $tmp;
		} else {
			$cookiedate = 30*24*3600;
			setcookie('selected_cookiedate', $cookiedate, $timestamp + $cookiedate, $cookiepath, $cookiedomain, $tmpport);
		}
	}
	setcookie($name, $value, $cookiedate ? $timestamp + $cookiedate : 0, $cookiepath, $cookiedomain, $tmpport);
}
function get_cookie($name){
	global $_COOKIE,$cookieprename,$magic_quotes_gpc;
	if (isset($_COOKIE[$cookieprename.$name])) {
		$value = urldecode($_COOKIE[$cookieprename.$name]);
		if ($magic_quotes_gpc) {
			$value = addslashes(stripslashes($value));
		} else {
			$value = addslashes($value);
		}
		return $value;
	}
	return FALSE;
}
function Createpass($length, $numeric = 0) {
	if ($numeric){
		mt_srand((double)microtime() * 1000000);
		$string = sprintf('%0'.$length.'d', mt_rand(0, pow(10, $length) - 1));
	}else{
		srand(date('s'));
		$possible_charactors = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
		$string = '';
		while( strlen($string) < $length ) {
			$string .= substr($possible_charactors,(rand()%(strlen($possible_charactors))),1);
		}
	}
	return($string);
}//Createpass
function dv_md5($str){
	return md5($str);
}

/**
 * Description 输出或返回一个变量的字符串表示(该字符串是合法的 PHP 代码)
 * @author
 * @param mixed 任意类型的 PHP 变量
 * @param boolean 其值为真时，返回关于传递给该函数的变量的结构信息，值为假时，直接输出字符串形式的变量的结构信息，并返回NULL
 * @param boolean 其值为真时，将使用自定义算法代替系统函数var_export
 * @return string 返回关于传递给该函数的变量的结构信息
 */
function &Dv_varExport(&$mixedvar, $isreturn = false, $usedvcode = false)
{
	if (!is_bool($isreturn)) {
		$isreturn = false;
	}
	if (!is_bool($usedvcode)) {
		$return = false;
	}
	if ((false === $usedvcode) AND function_exists('var_export')) {
		return var_export($mixedvar, $isreturn);
	} else {
		$returnval = '';
		$vartype = strtolower(gettype($mixedvar));
		switch ($vartype) {
			case 'boolean'://布尔类型
			if (true === $mixedvar) {
				$returnval = 'true';
			} else {
				$returnval = 'false';
			}
			break;
			case 'integer'://整数类型
			case 'float'://浮点类型
			case 'double'://浮点类型
			$returnval =& $mixedvar;
			break;
			case 'string'://字符串类型
			$returnval = "'".str_replace(array('\\', "'"), array('\\\\', "\\'"), $mixedvar)."'";
			break;
			case 'array'://数组类型
			if (empty($mixedvar)) {
				$returnval = 'array()';
			} else {
				$returnval = 'array(';
				foreach ($mixedvar AS $key => $val) {
					$returnval .= "'{$key}' => ".Dv_varExport($val, true, $usedvcode).", ";
				}
				$returnval .= ')';
			}
			break;
			case 'NULL'://特殊类型NULL
			$returnval = 'NULL';
			break;
			case 'object'://对象类型
			$parentclass = get_parent_class($mixedvar).'';
			$returnval = "\r\nclass ".get_class($mixedvar).('' !== $parentclass ? " extends {$parentclass}" : '')." {\r\n";
			$vars =& get_object_vars($mixedvar);
			if (!empty($vars) AND is_array($vars)) {
				foreach ($vars AS $key => $val) {
					$returnval .= "var \${$key} = ".Dv_varExport($val, true, $usedvcode).";\r\n";
				}
			}
			$returnval .= "\r\n}";
			break;
			case 'resource'://资源类型
			$returnval = 'NULL';
			break;
			case 'user function'://只用于 PHP 3，PHP4或更高版本已停用
			case 'unknown type'://未知的变量类型
			default:
				$returnval = 'NULL';
		}
		if (false === $isreturn) {
			print $returnval;
			return NULL;
		} else {
			return $returnval;
		}
	}
}//end function Dv_varExport
/**
 * Description 将字符串格式化为可用于JavaScript的数据
 * @author
 * @param mixed 可转换为字符串类型的变量
 * @return string 返回可用于JavaScript代码的数据
 */
function format_jscode(&$str)
{
	$data = strval($str);
	if ('' === $data) {
		return '';
	}
	return str_replace(array('\\', "\r", "\n", '"', "'"), array('\\\\', '\\0Dx', '\\x0A', '\\x22', '\\x27'), $data);
}//end function format_jscode

/**
 * Description 输出或返回一个变量的 JavaScript 字符串的表示
 * @author
 * @param mixed 任意类型的 PHP 变量
 * @param boolean 其值为真时，将返回转换后的值，否则，直接输出转换后的值并返回 NULL
 * @return string 返回可用于JavaScript代码的数据
 */
function var_export2js(&$mixedvar, $isreturn = false)
{
	if (!is_bool($isreturn)) {
		$isreturn = false;
	}
	$returnval = '';
	$vartype = strtolower(gettype($mixedvar));
	switch ($vartype) {
		case 'boolean'://布尔类型
		if (true === $mixedvar) {
			$returnval = 'true';
		} else {
			$returnval = 'false';
		}
		break;
		case 'integer'://整数类型
		case 'float'://浮点类型
		case 'double'://浮点类型
		$returnval =& $mixedvar;
		break;
		case 'string'://字符串类型
		$returnval = "'".format_jscode($mixedvar)."'";
		break;
		case 'array'://数组类型
		if (empty($mixedvar)) {
			$returnval = 'new Array()';
		} else {
			$returnval = '{';
			$comma = '';
			foreach ($mixedvar AS $key => $val) {
				$returnval .= "{$comma}'{$key}':".var_export2js($val, true)."";
				$comma = ',';
			}
			$returnval .= '}';
		}
		break;
		case 'NULL'://特殊类型NULL
		$returnval = 'null';
		break;
		case 'object'://对象类型
		$parentclass = get_parent_class($mixedvar).'';
		$returnval = 'new Object({';
		$vars =& get_object_vars($mixedvar);
		if (!empty($vars) AND is_array($vars)) {
			$comma = '';
			foreach ($vars AS $key => $val) {
				$returnval .= "{$comma}'{$key}':".var_export2js($val, true);
				$comma = ',';
			}
		}
		$returnval .= '})';
		break;
		case 'resource'://资源类型
		$returnval = 'null';
		break;
		case 'user function'://只用于 PHP 3，PHP4或更高版本已停用
		case 'unknown type'://未知的变量类型
		default:
			$returnval = 'null';
	}
	if (false === $isreturn) {
		print $returnval;
		return NULL;
	} else {
		return $returnval;
	}
}//end function var_export2js


/**
 * Description 过滤 XSS 危害字符
 * @author
 * @param mixed 要过滤的字符串
 * @return string 返回已过滤掉 XSS 危害字符的字符串
 */
function str_filter_xss($str, $filterhtml = true)
{
	static $arr_parttern = array(0=>'/&(?!amp)/i', 1=>'/&#/i', 2=>'/\x5cx/i', 3=>'/\x5cu/i', 4=>'/(?:j\s*a\s*v\s*a\s*|j\s*)s\s*c\s*r\s*i\s*p\s*t\s*:\s*/i', 5=>'/<\s*s\s*c\s*r\s*i\s*p\s*t\s*/i', 6=>'/\x5c\s*(?=\d+?)/i', 7=>'/%\s*(?=[0-9a-zA-Z]{1,2})/i', 8=>'/(\s+)(on(?:\w+?)=)/i', 9=>"/'/i", 10=>'/"/i', 11=>'/\<(?!br)/i');

	static $arr_repl = array(0=>'&amp;', 1=>'&amp;#', 2=>'&#92;x', 3=>'&#92;u', 4=>'disabled_by_dv__javascript:', 5=>'&lt;script', 6=>'&#92;', 7=>'&#37;', 8=>'$1disabled_by_dv__$2', 9=>'&#39;', 10=>'&#34;', 11=>'&lt;');

	return preg_replace($arr_parttern, $arr_repl, urldecode($str));
}//end function str_filter_xss


/**
 * Description 销毁所有的 COOKIES
 * @author
 * @param array 一些选项
 * @return boolean 此函数总是返回 true
 */
function cookie_destory($opts = array())	//	清除所有的 COOKIE
{
	global $_COOKIE, $HTTP_COOKIE_VARS, $cookieprename;
	if (empty($_COOKIE)) {
		$_COOKIE =& $HTTP_COOKIE_VARS;
	}
	if (!empty($_COOKIE) AND is_array($_COOKIE)) {
		if (!isset($opts['skip_backend']) OR !is_bool($opts['skip_backend'])) {//	默认下不销毁后台的 COOKIE
			$opts['skip_backend'] = true;	//	默认下不销毁后台的 COOKIE
		}
		foreach ($_COOKIE AS $key => $val) {
			// 跳过后台的 COOKIE，不销毁它们
			if (true === $opts['skip_backend'] AND ($cookieprename.'sysusername' === $key || $cookieprename.'syspassword' === $key || $cookieprename.'backend_flag' === $key)) {
				continue;
			}
			if (false !== strpos($key, 'dv_passport')) {
				continue;
			}
			if (0 === strpos($key, $cookieprename)) {
				continue;
			}
			@setcookie($key, false);
			unset($_COOKIE[$key]);
		}//end foreach
	}
	return true;
}//end function cookie_destory
//-------------------------2007-8-23 IvanSky BoardGroup del ceche file function ActionBoardGroupFileDel-------
function ActionBoardGroupFileDel( $BoardFileName=null, $GroupFileName=null )
{
	$_getPath = CACHE_PATH."group/";
	$_GetFileName = array();

	if ( ( $BoardFileName !=null ) and ($BoardFileName !=null ) )
	if (@is_dir($_getPath))
	{
		if ( !empty ( $GroupFileName ) )
		{
			if ( strpos( $GroupFileName, "," ) )
			{
				$arrGroupFileName = explode(",",$GroupFileName);
				foreach ($arrGroupFileName as $val)
				//管理员组/超级版主
				$_GetFileName[] = "board_".$val."_".$BoardFileName.".php";
			}
			else
			{
				//管理员组/超级版主
				$_GetFileName[] = "board_".$GroupFileName."_".$BoardFileName.".php";
			}
			if ( count ( $_GetFileName ) > 1 )
			{
				foreach ( $_GetFileName as $val )
				{
					$_getFilePath = $_getPath.$val;
					if ( file_exists ( $_getFilePath ) )
					{
						@unlink($_getFilePath);
					}
				}
			}
			else
			{
				$_getFilePath = $_getPath.$val;
				if ( file_exists ($_GetFileName) )@unlink($_getFilePath);
			}
		}
	}

}//end   function ActionBoardGroupFileDel

function admin_boardset_check (){

	$hide = $_GET[ahide];
	if ( empty($hide) ){
		global $hide;
		$hide = $ahide;
	}

	if (base64_decode($hide) == 'admin_boardset')
	return true;
	else
	return false;

}

function _varstoscript($varname,$value,$setvaluesign=null){
	if($varname===null)return '';
	$vartype=gettype($value);
	($setvaluesign===null) AND ($setvaluesign="=");
	if($setvaluesign==="="){
	($varname="\$$varname");
	}else if(gettype($varname)==="string"){
		$varname=str_replace("'","",$varname);
		$varname=str_replace('"',"",$varname);
		$varname=str_replace('\\','',$varname);
		$varname="'".$varname."'";
	}
	switch($vartype){
		case "boolean":
			$valuestr=$value?"true":"false";
			break;
		case "integer":
			$valuestr="$value";
			break;
		case "double":
			$valuestr="$value";
			break;
		case "string":
			$value=str_replace("'","\'",$value);
			$valuestr="'$value'";
			break;
		case "array":
			$valuestr="array(\n";
			$tmp="";

			foreach ($value as $k=>$v){
				$tmp.=",".varstoscript($k,$v,"=>")."\n";
			}
			$tmp!=="" AND $tmp=substr($tmp,1);
			$valuestr.=$tmp.")";
			break;
		case "NULL":
			$valuestr="null";
			break;
		default:
	}
		return $varname.$setvaluesign.$valuestr;
}

function get_cercode($w=100,$h=24,$level=0,$tabindex=0,$size=4,$print=false,$defaultshow=false){
	global $cercode_image,$lang;
	if($w>100)$w=100;
	if($h>24)$h=24;
	($w<40)AND($w=40);
	($h<10)AND($h=10);
	if($defaultshow){
		$cercode_height=$h;
		$cercode_width=$w;
	}else{
		$cercode_height=0;
		$cercode_width=0;
	}
	
     
	$size=$size<4?4:$size;
	($level<0)&&($level=0);
	$basepath="./".str_repeat("../",$level);
	$fv="basepath=".$basepath."&qs=?";
	$tabindexhtml=$tabindex?" tabindex=\"{$tabindex}\"":"";
    
	if(strtolower($cercode_image)=="swf"){
		$cercodehtml='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" id="cercode"'
		.' codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,19,0" width="'.strval($cercode_width).'" height="'.strval($cercode_height).'">'
		.'<param name="movie" value="'.$basepath.'dv_getcode/Dv_getCode_Fla.swf" />'
		.'<param name="quality" value="high" />'
		.'<param name="FlashVars" value="'.$fv.'" />'
		.'<embed id="cercode_emb" src="'.$basepath.'dv_getcode/Dv_getCode_Fla.swf" FlashVars="'.$fv.'" quality="high"'
		.' pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" width="'.$cercode_width.'" height="'.$cercode_height.'">'
		.'</object>';
	}else{
		$cercodehtml= '<img id="cercode_emb" src="'.$basepath.'dv_getcode.php" alt="" class="simg" style="cursor : pointer;" onclick="this.src=\''.$basepath.'dv_getcode.php?d=\'+Date();" onmouseover="this.className=\'bigimg\';" onmouseout="this.className=\'simg\';" align="absmiddle" width="'.strval($cercode_width).'" height="'.strval($cercode_height).'" border="0">';
	}
	$html=<<<EOT
	<input name="getcode" id="getcode" type="text"  size={$size} {$tabindexhtml} onfocus="try{setObjSize(document.getElementById('cercode_emb'),{$w},{$h});setObjSize(document.getElementById('cercode'),{$w},{$h});}catch(e){};" onblur="try{showonblur();}catch(e){};"/>&nbsp;&nbsp;{$cercodehtml}&nbsp;&nbsp;<span id="getcode_tip" >{$lang['msg_getcode']}</span>
EOT;
	if($print){
		echo $html;
		return true;
	}else{
		return $html;
	}
}

function checkcercode(){
	global $getcode;
	return ($getcode!=''&&$GLOBALS['userinfo']['getcode'] == $getcode);
}

function session_onstart(){
	global $SESSIONTIMEOUT;
	(!$SESSIONTIMEOUT)&&($SESSIONTIMEOUT=1200);
	$sid=get_cookie("PHPSESSID");
	if(!$sid)$sid=$_GET['PHPSESSID'];
	if(!$sid){
		session_start();
		$sid=session_id();
		set_cookie("PHPSESSID",$sid,$SESSIONTIMEOUT);
	}else{
		session_id($sid);
		session_start();
	}
}

	//生成缓存文件
	function to_static_php_file($file_name,&$file_content)
	{
		if (is_file ($file_name)){
			return true;
		}
		else{
			$handle = fopen ($file_name,"w");
			if (!is_writable ($file_name)){
				return false;
			}
			if (!fwrite ($handle,$file_content)){
				return false;
			} 
			fclose ($handle);
			return true;
		}
	}

	//把生成的缓存删除,下次访问自动生成
	function del_static_php_file($boardid,$boardids,$id)
	{
		global $userid;
		$isupdate= false;

		$boardids= explode(',',$boardids);

		if(!in_array($boardid,$boardids))
			$boardids[]= $boardid;
		
		//版面缓存
		for($i=0;$i<count($boardids);$i++){
			if($boardids[$i] != ''){
				$isupdate= true;
				del_static_board($boardids[$i]);
			}
		}

		//主页缓存
		if($isupdate){
			del_static_board('0');
		}

		//帖子第一页缓存
		del_static_topic($boardid,$id);
	}

	//更新帖子缓存
	function del_static_topic($boardid,$id){
		unlink(CACHE_PATH."static/dispbbs_0_".$boardid."_".$id.".php");
		unlink(CACHE_PATH."static/dispbbs_".$boardid."_".$id.".php");
	}

	//把生成的版面缓存删除
	function del_static_boards($boardids)
	{
		$isupdate= false;

		$boardids= explode(',',$boardids);
		
		//版面缓存
		for($i=0;$i<count($boardids);$i++){
			if($boardids[$i] != ''){
				$isupdate= true;
				del_static_board($boardids[$i]);
			}
		}

		//主页缓存
		if($isupdate){
			del_static_board('0');
		}
	}

	//把生成的版面缓存删除
	function del_static_boards_all($db)
	{
		$query = $db->query("select boardid from dv_board");

		while($arr=$db->fetch_array($query)){
			del_static_board($arr["boardid"]);
		}

		//主页缓存
		if($isupdate){
			del_static_board('0');
		}
	}

	//更新版面缓存
	function del_static_board($boardid){
		unlink(CACHE_PATH."static/index_0_".$boardid.".php");
		unlink(CACHE_PATH."static/index_".$boardid.".php");
	}
	
	function formatSize($size,$acuteDeg=3){
	if($size>1073741824){
		return strval(number_format($size/1073741824,$acuteDeg,".",""))."GB";
	}elseif($size>1048576){
		return strval(number_format($size/1048576,$acuteDeg,".",""))."MB";
	}elseif($size>1024){
		return strval(number_format($size/1024,$acuteDeg,".",""))."KB";
	}else{
		return strval($size)."Bytes";
	}
}


/**
* 加密或者解密用户信息
* @param $string - 加密或解密的串
* @param $operation - 加密还是解密，值：’ENCODE’ ‘DECODE’
* @param 密钥
* @return 返回字符串
*/function authcode($string, $operation, $key = '') {

	$key = md5($key ? $key : $GLOBALS['discuz_auth_key']);
	$key_length = strlen($key);

	$string = $operation == 'DECODE' ? base64_decode($string) : substr(md5($string.$key), 0, 8).$string;
	$string_length = strlen($string);

	$rndkey = $box = array();
	$result = '';

	for($i = 0; $i <= 255; $i++) {
		$rndkey[$i] = ord($key[$i % $key_length]);
		$box[$i] = $i;
	}

	for($j = $i = 0; $i < 256; $i++) {
		$j = ($j + $box[$i] + $rndkey[$i]) % 256;
		$tmp = $box[$i];
		$box[$i] = $box[$j];
		$box[$j] = $tmp;
	}

	for($a = $j = $i = 0; $i < $string_length; $i++) {
		$a = ($a + 1) % 256;
		$j = ($j + $box[$a]) % 256;
		$tmp = $box[$a];
		$box[$a] = $box[$j];
		$box[$j] = $tmp;
		$result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
	}

	if($operation == 'DECODE') {
		if(substr($result, 0, 8) == substr(md5(substr($result, 8).$key), 0, 8)) {
			return substr($result, 8);
		} else {
			return '';
		}
	} else {
		return str_replace('=', '', base64_encode($result));
	}

}	
?>