<?php
!defined('P_W') && exit('Forbidden');

function Cookie($ck_Var,$ck_Value,$ck_Time='F',$p=true){
	global $db_ckpath,$db_ckdomain,$timestamp,$pwServer;

	if (!$pwServer['REQUEST_URI'] || ($https = @parse_url($pwServer['REQUEST_URI']))===false) {
		$https = array();
	}
	if ($https['scheme']=='https' || (empty($https['scheme']) && ($pwServer['HTTP_SCHEME']=='https' || $pwServer['HTTPS'] && strtolower($pwServer['HTTPS'])!='off'))) {
		$ck_Secure = true;
	} else {
		$ck_Secure = false;
	}

	if (P_W!='admincp') {
		$ckpath = !$db_ckpath ? '/' : $db_ckpath;
		$ckdomain = $db_ckdomain;
	} else {
		$ckpath = '/';
		$ckdomain = '';
	}

	$ck_Httponly = false;
	if ($ck_Var=='AdminUser' || $ck_Var=='winduser') {
		$agent = strtolower($pwServer['HTTP_USER_AGENT']);
		if (!($agent && preg_match('/msie ([0-9]\.[0-9]{1,2})/i', $agent) && strstr($agent, 'mac'))) {
			$ck_Httponly = true;
		}
	}

	$p && $ck_Var = CookiePre().'_'.$ck_Var;
	if ($ck_Time=='F') {
		$ck_Time = $timestamp+31536000;
	} elseif ($ck_Value=='' && $ck_Time==0) {
		return setcookie($ck_Var,'',$timestamp-31536000,$ckpath,$ckdomain,$ck_Secure);
	}

	if (PHP_VERSION < 5.2) {
		return setcookie($ck_Var,$ck_Value,$ck_Time,$ckpath.($ck_Httponly ? '; HttpOnly' : ''),$ckdomain,$ck_Secure);
	} else {
		return setcookie($ck_Var,$ck_Value,$ck_Time,$ckpath,$ckdomain,$ck_Secure,$ck_Httponly);
	}
}
function GetCookie($Var){
	return $_COOKIE[CookiePre().'_'.$Var];
}
function CookiePre(){
	static $pre = null;
	!isset($pre) && $pre = substr(md5($GLOBALS['db_sitehash']),0,5);
	return $pre;
}
function P_unlink($filename){
	strpos($filename,'..')!==false && exit('Forbidden');
	return @unlink($filename);
}
function openfile($filename){
	$filedb = explode('<:wind:>',str_replace("\n","\n<:wind:>",readover($filename)));
	$count = count($filedb)-1;
	if ($count > -1 && (!$filedb[$count] || $filedb[$count]=="\r")) {
		unset($filedb[$count]);
	}
	empty($filedb) && $filedb[0] = '';
	return $filedb;
}
function readover($filename,$method='rb'){
	strpos($filename,'..')!==false && exit('Forbidden');
	$filedata = '';
	if ($handle = @fopen($filename,$method)) {
		flock($handle,LOCK_SH);
		$filedata = @fread($handle,filesize($filename));
		fclose($handle);
	}
	return $filedata;
}
function writeover($filename,$data,$method='rb+',$iflock=1,$check=1,$chmod=1){
	//Copyright (c) 2003-09 PHPWind
	$check && strpos($filename,'..')!==false && exit('Forbidden');
	touch($filename);
	$handle = fopen($filename,$method);
	$iflock && flock($handle,LOCK_EX);
	fwrite($handle,$data);
	$method=='rb+' && ftruncate($handle,strlen($data));
	fclose($handle);
	$chmod && @chmod($filename,0777);
}
function PwdCode($pwd){
	return md5($GLOBALS['pwServer']['HTTP_USER_AGENT'].$pwd.$GLOBALS['db_hash']);
}
function SafeCheck($CK,$PwdCode,$var='AdminUser',$expire=1800){
	global $timestamp;
	if ($timestamp-$CK[0]>$expire || $CK[2]!=md5($PwdCode.$CK[0])) {
		Cookie($var,'',0);
		return false;
	}
	$CK[0] = $timestamp;
	$CK[2] = md5($PwdCode.$CK[0]);
	Cookie($var,StrCode(implode("\t",$CK)));
	return true;
}
function StrCode($string,$action='ENCODE'){
	$action != 'ENCODE' && $string = base64_decode($string);
	$code = '';
	$key  = substr(md5($GLOBALS['pwServer']['HTTP_USER_AGENT'].$GLOBALS['db_hash']),8,18);
	$keylen = strlen($key); $strlen = strlen($string);
	for ($i=0;$i<$strlen;$i++) {
		$k		= $i % $keylen;
		$code  .= $string[$i] ^ $key[$k];
	}
	return ($action!='DECODE' ? base64_encode($code) : $code);
}
function substrs($content,$length,$add='Y'){
	if ($length && strlen($content)>$length) {
		global $db_charset;
		if ($db_charset!='utf-8') {
			$retstr = '';
			for ($i=0;$i<$length-2;$i++) {
				$retstr .= ord($content[$i]) > 127 ? $content[$i].$content[++$i] : $content[$i];
			}
			return $retstr.($add=='Y' ? ' ..' : '');
		}
		return utf8_trim(substr($content,0,$length)).($add=='Y' ? ' ..' : '');
	}
	return $content;
}
function utf8_trim($str) {
	$hex = '';
	$len = strlen($str)-1;
	for ($i=$len;$i>=0;$i-=1) {
		$ch = ord($str[$i]);
		$hex .= " $ch";
		if (($ch & 128)==0 || ($ch & 192)==192) {
			return substr($str,0,$i);
		}
	}
	return $str.$hex;
}
function get_date($timestamp,$timeformat=null){
	global $db_datefm,$db_timedf,$_datefm,$_timedf;
	if (empty($timeformat)) {
		$timeformat = $_datefm ? $_datefm : $db_datefm;
	}
	if ($_timedf && $_timedf!='111') {
		return gmdate($timeformat,$timestamp+$_timedf*3600);
	} elseif ($db_timedf && $db_timedf!='111') {
		return gmdate($timeformat,$timestamp+$db_timedf*3600);
	}
	return gmdate($timeformat,$timestamp);
}
function geturl($attachurl,$type = null,$thumb = null) {
	global $attachdir,$attachpath,$db_ftpweb,$attach_url;
	if ($thumb) {
		if (file_exists($attachdir.'/thumb/'.$attachurl)) {
			return array($attachpath.'/thumb/'.$attachurl,'Local');
		}
	}
	if (file_exists($attachdir.'/'.$attachurl)) {
		return array($attachpath.'/'.$attachurl,'Local');
	}
	if ($db_ftpweb && !$attach_url || $type == 'lf') {
		return array($db_ftpweb.'/'.$attachurl,'Ftp');
	}
	if (!$db_ftpweb && !is_array($attach_url)) {
		return array($attach_url.'/'.$attachurl,'att');
	}
	if (!$db_ftpweb && count($attach_url) == 1) {
		return array($attach_url[0].'/'.$attachurl,'att');
	}
	if ($type == 'show') {
		return ($db_ftpweb || $attach_url) ? 'imgurl' : 'nopic';
	}
	if ($db_ftpweb && $fp = @fopen($db_ftpweb.'/'.$attachurl,'rb')) {
		@fclose($fp);
		return array($db_ftpweb.'/'.$attachurl,'Ftp');
	}
	if (!empty($attach_url)) {
		foreach ($attach_url as $value) {
			if ($value != $db_ftpweb && ($fp = @fopen($value.'/'.$attachurl,'rb'))) {
				@fclose($fp);
				return array($value.'/'.$attachurl,'att');
			}
		}
	}
	return false;
}

function randstr($lenth) {
	return substr(md5(num_rand($lenth)),mt_rand(0,32-$lenth),$lenth);
}
function num_rand($lenth) {
	mt_srand((double)microtime()*1000000);
	$randval = '';
	for ($i = 0; $i<$lenth; $i++) {
		$randval .= mt_rand(0,9);
	}
	return $randval;
}
function PwStrtoTime($time){
	global $db_timedf;
	return function_exists('date_default_timezone_set') ? strtotime($time) - $db_timedf*3600 : strtotime($time);
}
function Pcv($filename,$ifcheck=1){
	$tmpname = strtolower($filename);
	$tmparray = array('http://');
	$ifcheck && $tmparray[] = '..';
	if (str_replace($tmparray,'',$tmpname)!=$tmpname) {
		exit('Forbidden');
	}
	return $filename;
}
function pwDirCv($dir){
	//Copyright (c) 2003-09 PHPWind
	$dir = str_replace(array("'",'#','=','`','$','%','&',';'),'',$dir);
	return trim(preg_replace('/(\/){2,}|(\\\){1,}/','/',$dir),'/');
}
function GetTtable($tid) {
	global $db_tlist;
	if ($db_tlist && is_array($tlistdb = unserialize($db_tlist))) {
		foreach ($tlistdb as $key => $value) {
			if ($key>0 && $tid>$value) {
				return 'pw_tmsgs'.(int)$key;
			}
		}
	}
	return 'pw_tmsgs';
}
function GetPtable($tbid,$tid=null){
	if ($GLOBALS['db_plist']) {
		if ($tbid=='N' && !empty($tid)) {
			$tbid = $GLOBALS['db']->get_value('SELECT ptable FROM pw_threads WHERE tid='.pwEscape($tid,false));
		}
		if ((int)$tbid>0 && strpos(','.$GLOBALS['db_plist'].',',','.$tbid.',')!==false) {
			return 'pw_posts'.$tbid;
		}
	}
	return 'pw_posts';
}
function Sql_cv($var){
	global $db;
	$db->update('INSERT INTO pw_sqlcv SET var='.pwEscape($var),0);
	$id = $db->insert_id();
	$rt = $db->get_one('SELECT var FROM pw_sqlcv WHERE id='.pwEscape($id));
	$db->update('DELETE FROM pw_sqlcv WHERE id='.pwEscape($id));
	return $rt['var'];
}
function CkInArray($needle,$haystack) {
	if (!$needle || empty($haystack) || !in_array($needle,$haystack)) {
		return false;
	}
	return true;
}
function pw_var_export($input,$t = null) {
	$output = '';
	if (is_array($input)) {
		$output .= "array(\r\n";
		foreach ($input as $key => $value) {
			$output .= $t."\t".pw_var_export($key,$t."\t").' => '.pw_var_export($value,$t."\t");
			$output .= ",\r\n";
		}
		$output .= $t.')';
	} elseif (is_string($input)) {
		$output .= "'".str_replace(array("\\","'"),array("\\\\","\'"),$input)."'";
	} elseif (is_int($input) || is_double($input)) {
		$output .= "'".(string)$input."'";
	} elseif (is_bool($input)) {
		$output .= $input ? 'true' : 'false';
	} else {
		$output .= 'NULL';
	}
	return $output;
}

/**
 * 針對SQL語句的變量進行反斜線過濾,並兩邊添加單引號
 *
 * @param mixed $var 過濾前變量
 * @param boolean $strip 數據是否經過stripslashes處理
 * @return mixed 過濾後變量
 */
function pwEscape($var,$strip = true) {
	if (is_array($var)) {
		foreach ($var as $key => $value) {
			$var[$key] = trim(pwEscape($value,$strip));
		}
		return $var;
	} elseif (is_numeric($var)) {
		return " '".$var."' ";
	} else {
		return " '".addslashes($strip ? stripslashes($var) : $var)."' ";
	}
}
/**
 * 過濾數組每個元素值,並進行單引號合並
 *
 * @param array $array 源數組
 * @param boolean $strip 數據是否經過stripslashes處理
 * @return string 合並後字符串
 */
function pwImplode($array,$strip=true) {
	return implode(',',pwEscape($array,$strip));
}
/**
 * 構造單記錄數據更新SQL語句
 *  格式: field='value',field='value'
 *
 * @param array $array 更新的數據,格式: array(field1=>'value1',field2=>'value2',field3=>'value3')
 * @param boolean $strip 數據是否經過stripslashes處理
 * @return string SQL語句
 */
function pwSqlSingle($array,$strip=true) {
	//Copyright (c) 2003-09 PHPWind
	$array = pwEscape($array,$strip);
	$str = '';
	foreach ($array as $key => $val) {
		$str .= ($str ? ', ' : ' ').$key.'='.$val;
	}
	return $str;
}
/**
 * 構造批量數據更新SQL語句
 *  格式: ('value1[1]','value1[2]','value1[3]'),('value2[1]','value2[2]','value2[3]')
 *
 * @param array $array 更新的數據,格式: array(array(value1[1],value1[2],value1[3]),array(value2[1],value2[2],value2[3]))
 * @param boolean $strip 數據是否經過stripslashes處理
 * @return string SQL語句
 */
function pwSqlMulti($array,$strip=true) {
	//Copyright (c) 2003-09 PHPWind
	$str = '';
	foreach ($array as $val) {
		if (!empty($val)) {
			$str .= ($str ? ', ' : ' ') . '(' . pwImplode($val,$strip) .') ';
		}
	}
	return $str;
}
/**
 * SQL查詢中,構造LIMIT語句
 *
 * @param integer $start 開始記錄位置
 * @param integer $num 讀取記錄數目
 * @return string SQL語句
 */
function pwLimit($start,$num=false) {
	return ' LIMIT '.(int)$start.($num ? ','.(int)$num : '');
}
function getstatus($status,$b,$getv = 1) {
	return $status >> --$b & $getv;
}
/**
 * 獲取指定語言包里的某一內容信息
 *
 * @param string $T 語言包文件名
 * @param string $I 指定語言信息
 * @param array $L 額外變量
 * @param array $M 是否調用模式下的語言文件
 * @return string
 */
function getLangInfo($T,$I,$L=false,$M=false) {
	static $lang;
	if (!isset($lang[$T])) {
		if ($M==false) {
			require Pcv(GetLang($T));
		} else {
			require Pcv(getModeLang($T));
		}
	}
	if (isset($lang[$T][$I])) {
		eval('$I="'.addcslashes($lang[$T][$I],'"').'";');
	}
	return $I;
}

/*獲取積分操作*/
function GetCreditLang($T,$logtype) {
	static $lang;
	if (!isset($lang[$T])) {
		require Pcv(GetLang($T));
	}
	if (isset($lang[$T][$logtype])) {
		eval('$pop="'.addcslashes($lang[$T][$logtype],'"').'";');
	}
	return $pop;
}

function getModeLang($lang,$EXT='php'){
	if (defined('M_P') && file_exists(M_P."lang/lang_$lang.$EXT")) {
		return M_P."lang/lang_$lang.$EXT";
	} else {
		return GetLang($T);
	}
}

function InitGP($keys,$method=null,$cvtype=1){//0=null,1=Char_cv,2=int
	//Copyright (c) 2003-09 PHPWind
	!is_array($keys) && $keys = array($keys);
	foreach ($keys as $key) {
		$GLOBALS[$key] = NULL;
		if ($method != 'P' && isset($_GET[$key])) {
			$GLOBALS[$key] = $_GET[$key];
		} elseif ($method != 'G' && isset($_POST[$key])) {
			$GLOBALS[$key] = $_POST[$key];
		}
		if (isset($GLOBALS[$key]) && !empty($cvtype)) {
			$GLOBALS[$key] = Char_cv($GLOBALS[$key],$cvtype==2,true);
		}
	}
}
function GetGP($key,$method=null){
	//Copyright (c) 2003-09 PHPWind
	if ($method == 'G' || $method != 'P' && isset($_GET[$key])) {
		return $_GET[$key];
	}
	return $_POST[$key];
}
/**
 * 讀取指定的全局環境變量值
 *
 * @param mixed $keys 環境變量名，可數組或單值
 * @return mixed 根據參數個數返回指定環境變量值
 */
function GetServer($keys){
	//Copyright (c) 2003-09 PHPWind
	foreach ((array)$keys as $key) {
		$server[$key] = NULL;
		if (isset($_SERVER[$key])) {
			$server[$key] = str_replace(array('<','>','"',"'",'%3C','%3E','%22','%27','%3c','%3e'),'',$_SERVER[$key]);
		}
	}
	return is_array($keys) ? $server : $server[$keys];
}
function Char_cv($mixed,$isint=false,$istrim=false) {
	//Copyright (c) 2003-09 PHPWind
	if (is_array($mixed)) {
		foreach ($mixed as $key => $value) {
			$mixed[$key] = Char_cv($value,$isint,$istrim);
		}
	} elseif ($isint) {
		$mixed = (int)$mixed;
	} elseif (!is_numeric($mixed) && ($istrim ? $mixed = trim($mixed) : $mixed) && $mixed) {
		$mixed = str_replace(array("\0","%00","\r"),'',$mixed);
		$mixed = preg_replace(
			array('/[\\x00-\\x08\\x0B\\x0C\\x0E-\\x1F]/','/&(?!(#[0-9]+|[a-z]+);)/is'),
			array('','&amp;'),
			$mixed
		);
		$mixed = str_replace(array("%3C",'<'),'&lt;',$mixed);
		$mixed = str_replace(array("%3E",'>'),'&gt;',$mixed);
		$mixed = str_replace(array('"',"'","\t",'  '),array('&quot;','&#39;','    ','&nbsp;&nbsp;'),$mixed);
	}
	return $mixed;
}
function CheckVar(&$var) {
	if (is_array($var)) {
		foreach ($var as $key => $value) {
			CheckVar($var[$key]);
		}
	} elseif (P_W != 'admincp') {
		$var = str_replace(array('..',')','<','='),array('&#46;&#46;','&#41;','&#60;','&#61;'),$var);
	} elseif (str_replace(array('<iframe','<meta','<script'),'',$var)!=$var) {
		global $basename;
		$basename = 'javascript:history.go(-1);';
		adminmsg('word_error');
	}
}
function Add_S(&$array){
	if (is_array($array)) {
		foreach ($array as $key => $value) {
			if (is_array($value)) {
				Add_S($array[$key]);
			} else {
				$array[$key] = addslashes($value);
			}
		}
	}
}
function pwWritable($pathfile) {
	//Copyright (c) 2003-09 PHPWind
	//fix windows acls bug noizy
	$unlink = false;
	substr($pathfile,-1)=='/' && $pathfile = substr($pathfile,0,-1);
	if (is_dir($pathfile)) {
		$unlink = true;
		mt_srand((double)microtime()*1000000);
		$pathfile = $pathfile.'/pw_'.uniqid(mt_rand()).'.tmp';
	}
	$fp = @fopen($pathfile,'ab');
	if ($fp===false) return false;
	fclose($fp);
	if ($unlink) @unlink($pathfile);
	return true;
}
/*
 * 獲取論壇的普通版塊id
 */
function getCommonFid() {
	static $fids = null;

	if (!isset($fids)) {
		if (pwFilemtime(D_P.'data/bbscache/commonforum.php') < pwFilemtime(D_P.'data/bbscache/forum_cache.php')) {
			global $db;
			$query = $db->query("SELECT fid FROM pw_forums WHERE type<>'category' AND cms<>1 AND password='' AND forumsell='' AND f_type<>'hidden' AND allowvisit=''");
			while ($rt = $db->fetch_array($query)) {
				$fids .= ",'$rt[fid]'";
			}
			$fids && $fids = substr($fids,1);
			writeover(D_P.'data/bbscache/commonforum.php',"<?php\r\n\$fids = \"$fids\";\r\n?>");
		} else {
			include (D_P.'data/bbscache/commonforum.php');
		}
	}
	return $fids;
}
/*
 * 獲取論壇的特殊版塊id
 */
function getSpecialFid() {
	static $fids = null;

	if (!isset($fids)) {
		if (pwFilemtime(D_P.'data/bbscache/specialforum.php') < pwFilemtime(D_P.'data/bbscache/forum_cache.php')) {
			global $db;
			$query = $db->query("SELECT fid FROM pw_forums WHERE type<>'category' AND (cms=1 OR password!='' OR forumsell!='' OR f_type='hidden' OR allowvisit!='')");
			while ($rt = $db->fetch_array($query)) {
				$fids .= ",'$rt[fid]'";
			}
			$fids && $fids = substr($fids,1);
			writeover(D_P.'data/bbscache/specialforum.php',"<?php\r\n\$fids = \"$fids\";\r\n?>");
		} else {
			include (D_P.'data/bbscache/specialforum.php');
		}
	}
	return $fids;
}
/**
 * 當前登錄用戶版塊管理權限
 *
 * @param string $isBM 用戶是否為版主
 * @param string $rkey 指定要獲取的權限名
 * @param integer $fid 版塊FID
 * @return mixed 返回指定權限值
 */
function pwRights($isBM=false,$rkey='',$fid=false) {
	//Copyright (c) 2003-09 PHPWind
	static $_SYSTEM = null;

	if ($GLOBALS['gp_gptype']!='system' && $GLOBALS['gp_gptype']!='special') return false;

	$uid = (int)$GLOBALS['winduid'];
	$gid = (int)$GLOBALS['groupid'];
	$fid===false && $fid = (int)$GLOBALS['fid'];

	if (empty($uid) || empty($gid) || empty($fid)) return false;

	if (!isset($_SYSTEM[$fid])) {
		$_SYSTEM[$fid] = $BMSystem = array();
		$isUser = false;

		$pwSQL = 'uid='.pwEscape($uid,false).'AND fid='.pwEscape($fid,false)."AND gid='0'";
		if ($isBM && $gid != 5) {//獲取版主權限
			$pwSQL .= " OR uid='0' AND fid=".pwEscape($fid,false)."AND gid IN ('5',".pwEscape($gid,false).") OR uid='0' AND fid='0' AND gid='5'";
		} else {
			$pwSQL .= " OR uid='0' AND fid=".pwEscape($fid,false)."AND gid=".pwEscape($gid,false);
		}
		$query = $GLOBALS['db']->query("SELECT uid,fid,gid,rkey,rvalue FROM pw_permission WHERE ($pwSQL) AND type='systemforum' ORDER BY uid DESC,fid");
		while ($rt = $GLOBALS['db']->fetch_array($query)) {
			if ($rt['uid'] == $uid) {//用戶個人權限
				$_SYSTEM[$fid][$rt['rkey']] = $rt['rvalue'];
				$isUser = true;
			} elseif ($isUser) {//取得個人權限,結束
				break;
			} elseif ($isBM && $rt['gid'] && $gid != $rt['gid']) {//版主權限
				$BMSystem[$rt['rkey']] = $rt['rvalue'];
			} else {
				$_SYSTEM[$fid][$rt['rkey']] = $rt['rvalue'];
			}
		}
		if (!$isUser) {
			empty($_SYSTEM[$fid]) && ($GLOBALS['SYSTEM']['superright'] || $isBM && $gid == 5) && $_SYSTEM[$fid] = $GLOBALS['SYSTEM'];
			if ($BMSystem) {//版主權限加權
				foreach ($BMSystem as $key=>$value) {
					$_SYSTEM[$fid][$key] < $value && $_SYSTEM[$fid][$key] = $value;
				}
			}
		}
	}
	return empty($rkey) ? $_SYSTEM[$fid] : $_SYSTEM[$fid][$rkey];
}
function modeEot($template,$EXT='htm'){
	global $db_mode;
	if (pwFilemtime(D_P."data/tplcache/".$db_mode.'_'.$template.'.'.$EXT)>pwFilemtime(M_P."template/$template.$EXT")) {
		return D_P."data/tplcache/".$db_mode.'_'.$template.'.'.$EXT;
	} else {
		require_once(R_P.'require/parsetpl.php');
		return modeTemplate($template,$EXT);
	}
}

function getCateid($fid) {
	global $forum;
	if (in_array($forum[$fid]['type'],array('sub2','sub','forum'))) {
		return getCateid($forum[$fid]['fup']);
	} elseif ($forum[$fid]['type'] == 'category') {
		return $fid;
	} else {
		return false;
	}
}

function pwConvert($str,$to_encoding,$from_encoding,$ifmb=true) {
	global $pwconvert;
	if (strtolower($to_encoding) == strtolower($from_encoding)) {
		return $str;
	} elseif (function_exists('mb_convert_encoding') && $ifmb) {
		return mb_convert_encoding($str,$to_encoding,$from_encoding);
	} else {
		!$to_encoding && $to_encoding = 'GB2312';
		!$from_encoding && $from_encoding = 'GB2312';
		$type = strtoupper(substr($from_encoding,0,2).substr($to_encoding,0,2));
		if (!is_object($pwconvert) && $pwconvert->type != $type) {
			require_once(R_P.'wap/chinese.php');
			$pwconvert = new Chinese($from_encoding,$to_encoding);
		}
		return $pwconvert->Convert($str);
	}
}
function pwCreditNames($ctype = null) {
	static $creditnames = null;
	if (!isset($creditnames)) {
		$creditnames = array('money' => $GLOBALS['db_moneyname'], 'rvrc' => $GLOBALS['db_rvrcname'],'credit' => $GLOBALS['db_creditname'], 'currency' => $GLOBALS['db_currencyname']);
		foreach ($GLOBALS['_CREDITDB'] as $key => $value) {
			$creditnames[$key] = $value[0];
		}
	}
	return isset($ctype) ? $creditnames[$ctype] : $creditnames;
}
function minImage($sourceImg,$width,$height){
	static $mini = 0;
	global $db_bbsurl,$attachdir,$db_attachname;
	if (strpos($sourceImg,'://')) {
		return $sourceImg;
	}
	if ($mini == 0) {
		if (file_exists($attachdir."/mini")) {
			$mini = 1;
		} else {
			if (mkdir($attachdir."/mini")) {
				@chmod($attachdir."/mini",0777);
				$mini = 1;
			} else {
				$mini = 2;
			}
		}
	}
	if ($mini == 1) {
		$width = (int)$width;
		$height = (int)$height;
		if (!$width || !$height) {
			Showmsg('minimage_wh_error');
		}
		$file_ext	= end(explode('.',$sourceImg));
		$imgname	= substr(md5($sourceImg.$width.$height),10,10).'.'.$file_ext;
		if(file_exists($attachdir."/mini/".$imgname)) {
			return $db_bbsurl.'/'.$db_attachname."/mini/".$imgname;
		}
		$targtImg	= $attachdir."/mini/".$imgname;
		require_once(R_P.'require/imgfunc.php');
		$thumbsize = modeImageThumb($sourceImg,$targtImg,$width,$height);

		if ($thumbsize) {
			$fileurl = $db_bbsurl.'/'.$db_attachname."/mini/".$imgname;
			return $fileurl;
		} else {
			return $sourceImg;
		}
	} else {
		return $sourceImg;
	}
}
function ObContents($output){
	//Copyright (c) 2003-09 PHPWind
	ob_end_clean();
	if (!headers_sent() && $GLOBALS['db_obstart'] && GetServer('HTTP_ACCEPT_ENCODING') && N_output_zip()!='ob_gzhandler') {
		$encoding = '';
		if (strpos(' '.GetServer('HTTP_ACCEPT_ENCODING'),'gzip') !== false) {
			$encoding = 'gzip';
		} elseif (strpos(' '.GetServer('HTTP_ACCEPT_ENCODING'),'x-gzip') !== false) {
			$encoding = 'x-gzip';
		}
		if ($encoding && function_exists('crc32') && function_exists('gzcompress')) {
			header('Content-Encoding: '.$encoding);
			$outputlen  = strlen($output);
			$outputzip  = "\x1f\x8b\x08\x00\x00\x00\x00\x00";
			$outputzip .= substr(gzcompress($output,$GLOBALS['db_obstart']),0,-4);
			$outputzip .= @pack('V',crc32($output));
			$output = $outputzip.@pack('V',$outputlen);
		} else {
			ObStart();
		}
	} else {
		ObStart();
	}
	return $output;
}
function ObStart(){
	//Copyright (c) 2003-09 PHPWind
	ObGetMode() == 1 ? ob_start('ob_gzhandler') : ob_start();
}
function ObGetMode(){
	//Copyright (c) 2003-09 PHPWind
	static $mode = null;
	if ($mode!==null) {
		return $mode;
	}
	$mode = 0;
	if ($GLOBALS['db_obstart'] && function_exists('ob_gzhandler') && N_output_zip()!='ob_gzhandler' && (!function_exists('ob_get_level') || ob_get_level()<1)) {
		$mode = 1;
	}
	return $mode;
}
function N_flush(){
	//Copyright (c) 2003-09 PHPWind
	if (N_output_zip() == 'ob_gzhandler') {
		return;
	}
	if (php_sapi_name() != 'apache2handler' && php_sapi_name() != 'apache2filter') {
		flush();
	}
	if (function_exists('ob_get_status') && ob_get_status() && function_exists('ob_flush') && !ObGetMode($GLOBALS['db_obstart'])) {
		@ob_flush();
	}
}
function N_output_zip(){
	//Copyright (c) 2003-09 PHPWind
	static $output_handler = null;
	if ($output_handler === null) {
		if (@ini_get('zlib.output_compression')) {
			$output_handler = 'ob_gzhandler';
		} else {
			$output_handler = @ini_get('output_handler');
		}
	}
	return $output_handler;
}
function ajax_footer(){
	global $db_charset;
	$output = str_replace(array('<!--<!---->','<!---->'),array('',''),ob_get_contents());
	header("Content-Type: text/xml;charset=$db_charset");
	echo ObContents("<?xml version=\"1.0\" encoding=\"$db_charset\"?><ajax><![CDATA[".$output."]]></ajax>");exit;
}

function numofpage($count,$page,$numofpage,$url,$max=null) {
	global $tablecolor;
	$total = $numofpage;
	if (!empty($max)) {
		$max = (int)$max;
		$numofpage > $max && $numofpage = $max;
	}
	if ($numofpage <= 1 || !is_numeric($page)) {
		return '';
	} else {
		list($url,$mao) = explode('#',$url);
		$mao && $mao = '#'.$mao;
		$pages = "<div class=\"pages\"><ul><li><a href=\"{$url}page=1$mao\" style=\"font-weight:bold\">&laquo;</a></li>";
		for ($i = $page-3; $i <= $page-1; $i++) {
			if($i<1) continue;
			$pages .= "<li><a href=\"{$url}page=$i$mao\">$i</a></li>";
		}
		$pages .= "<li><b> $page </b></li>";
		if ($page < $numofpage) {
			$flag = 0;
			for ($i = $page+1; $i <= $numofpage; $i++) {
				$pages .= "<li><a href=\"{$url}page=$i$mao\">$i</a></li>";
				$flag++;
				if ($flag == 4) break;
			}
		}
		$pages .= "<li><a href=\"{$url}page=$numofpage$mao\" style=\"font-weight:bold\">&raquo;</a></li><li class=\"pagesone\">Pages: $page/$total&nbsp; &nbsp; &nbsp;Go <input type=\"text\" size=\"3\" onkeydown=\"javascript: if(event.keyCode==13){ location='{$url}page='+this.value+'{$mao}';return false;}\"></li></ul></div><div class=\"c\"></div>";
		return $pages;
	}
}
/**
 * 服務器時間校正後的文件修改時間
 *
 * @param string $file 文件路徑
 * @return int 返回修改時間
 */
function pwFilemtime($file) {
	return intval(filemtime($file) + $GLOBALS['db_cvtime']*60);
}
function pwDelatt($path,$ifftp) {
	if (!file_exists("$GLOBALS[attachdir]/$path")) {
		pwFtpNew($GLOBALS['ftp'],$ifftp) && $GLOBALS['ftp']->delete($path);
	} else {
		P_unlink("$GLOBALS[attachdir]/$path");
	}
}
function pwFtpNew(&$ftp,$ifftp) {
	if (!$ifftp) return false;
	static $ftp_server,$ftp_port,$ftp_user,$ftp_pass,$ftp_dir;
	if (!is_object($ftp)) {
		require_once(R_P.'require/ftp.php');
		$ftp = new FTP($ftp_server,$ftp_port,$ftp_user,$ftp_pass,$ftp_dir);
	}
	return true;
}
function pwFtpClose(&$ftp) {
	if (is_object($ftp) && method_exists($ftp,'close')) {
		$ftp->close();
		$ftp = null;
	}
}
function descriplog($message) {
	$message = str_replace(array("\n",'[b]','[/b]'),array('<br />','<b>','</b>'),$message);
	if (strpos($message,'[/URL]')!==false || strpos($message,'[/url]')!==false) {
		$message = preg_replace("/\[url=(https?)([^\[]+?)\](.+?)\[\/url\]/is","<a href=\"\\1\\2\" target=\"_blank\">\\3</a>",$message);
	}
	return $message;
}

/**
 * 社區模式下頭部版塊導航發帖導航彈出框生成函數
 * @param $type : thread(版塊導航)，post(發帖導航)
 * @param $menu_id : 導航框彈出框對應ID
 * @return $chtml : 整個彈出框HTML代碼
 */
function areaForumlist($type='thread',$menu_id='menu_cate_nav') {
	global $db_menu;
	@include(D_P.'data/bbscache/forum_cache.php');
	if ($db_menu%4<2 && $type == 'thread') return;
	$chtml = '';
	if (is_array($forum)) {
		$listdb = array();
		foreach ($forum as $value) {
			if ($value['cms'] || $value['f_type']=='hidden') continue;
			if ($value['type']=='category') {
				$listdb[$value['fid']] = array();
			} elseif ($forum[$value['fup']]['type']=='category' && !CkInArray($value['fid'],$listdb[$value['fup']])) {
				$listdb[$value['fup']][] = $value['fid'];
			}
		}
		foreach ($listdb as $key => $value) {
			if (!empty($value)) {
				$chtml .= '<tr><td class="menu-left"><a href="index.php?cateid='.$key.'">'.$forum[$key]['name'].'</a></td><td class="menu-right"><ul>';
				foreach ($value as $v) {
					$chtml .= '<li><a href="'.$type.'.php?fid='.$v.'" title="'.strip_tags($forum[$v]['name']).'">'.$forum[$v]['name'].'</a></li>';
				}
				$chtml .= '</ul></td></tr>';
			}
		}
	}
	$chtml && $chtml = '<div id="'.$menu_id.'" class="menu" style="display:none;"><div class="menu-post" style="width:700px;"><div class="menu-b"><table cellpadding="0" cellspacing="0" width="100%"><tr><td class="menu-top" colspan="2">'.getlanginfo('other','forumlist_'.$type).'</td></tr>'.$chtml.'<tr><td class="menu-left">&nbsp;</td><td class="tar" style="border-top:1px solid #fff;"><input type="submit" name="Submit" value="'.getLangInfo('other','cancle').'" class="btn" onclick="read.close();"></td></tr></table></div></div></div>';
	return $chtml;
}

/**
 * 將數組格式化成json格式
 *
 * @param  $type
 * @return string
 */
function pwJsonEncode($var){
	 switch (gettype($var)) {
		case 'boolean':
			return $var ? 'true' : 'false';
		case 'NULL':
			return 'null';
		case 'integer':
			return (int) $var;
		case 'double':
		case 'float':
			return (float) $var;
		case 'string':
			return '"'.addslashes($var).'"';
		case 'array':
			if (count($var) && (array_keys($var) !== range(0, sizeof($var) - 1))) {
				$properties = array();
				foreach ($var as $name=>$value) {
					$properties[] = pwJsonEncode(strval($name)) . ':' . pwJsonEncode($value);
				}
				return '{' . join(',', $properties) . '}';
			}
			$elements = array_map('pwJsonEncode', $var);
			return '[' . join(',', $elements) . ']';
	 }
}

/**
 * 獲取好友列表
 *
 * @param int $uid		需要查找的uid;
 * @param int $start	limit條件
 * @param int $num		limit條件
 * @param int $ftype	好友分組
 * @param int $show		是否需要詳細數據
 * @return array
 */
function getFriends($uid,$start=0,$num=0,$ftype=false,$show=false){
	global $db;
	$fild	= 'm.uid,m.username,f.ftid';
	$order  = $where = '';
	if ($show) {
		$fild .= ',f.joindate,m.icon as face,m.honor,md.f_num,md.thisvisit';
		$left = 'LEFT JOIN pw_memberdata md ON f.friendid=md.uid';
		$order = 'md.thisvisit';
	} else {
		$left = '';
		$order = 'f.joindate';
	}
	if ($ftype !== false) {
		$ftype	= (int)$ftype;
		$where = ' AND f.ftid='.pwEscape($ftype);
	}
	$start	= (int) $start;
	$num	= (int) $num;
	if ($start || $num) {
		!$num && $num = 8;
		$limit = pwLimit($start,$num);
	} else {
		$limit = '';
	}
	$rs = $db->query("SELECT $fild FROM pw_friends f LEFT JOIN pw_members m ON f.friendid=m.uid $left WHERE f.uid=".pwEscape($uid)." AND f.status=0 $where ORDER BY $order DESC $limit");
	$result = array();
	if ($show) {
		require_once(R_P.'require/showimg.php');
		while ($one = $db->fetch_array($rs)) {
			list($one['face']) = showfacedesign($one['face'],1);
			$one['honor'] = substrs($one['honor'],90);
			$one['joindate'] = get_date($one['joindate']);
			$result[$one['uid']] = $one;
		}
	} else {
		while ($one = $db->fetch_array($rs)) {
			$result[$one['uid']] = $one;
		}
	}
	count($result) == 0 && $result = false;
	return $result;
}

?>