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

function Cookie($ck_Var,$ck_Value,$ck_Time='F',$p=true,$ck_Httponly=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 = '';
	}
	$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.0') {
		return setcookie($ck_Var,$ck_Value,$ck_Time,$ckpath,$ckdomain,$ck_Secure,$ck_Httponly);
	} else {
		return setcookie($ck_Var,$ck_Value,$ck_Time,$ckpath.($ck_Httponly ? '; HttpOnly' : ''),$ckdomain,$ck_Secure);
	}
}
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='$tid'");
		}
		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] = 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 额外变量
 * @return string
 */
function getLangInfo($T,$I,$L=array()) {
	static $lang;
	if (!isset($lang[$T])) {
		require Pcv(GetLang($T));
	}
	if (isset($lang[$T][$I])) {
		eval('$I="'.addcslashes($lang[$T][$I],'"').'";');
	}
	return $I;
}
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 = 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;
}
function getCommonFid() {
	global $db;
	static $fids = null;
	if (@filemtime(D_P.'data/bbscache/commonforum.php') < @filemtime(D_P.'data/bbscache/forum_cache.php')) {
		$query = $db->query("SELECT fid,allowvisit,password,f_type,forumsell FROM pw_forums WHERE type<>'category' AND cms<>1");
		while ($rt = $db->fetch_array($query)) {
			if ($rt['f_type'] != 'hidden' && !$rt['allowvisit'] && !$rt['password'] && !$rt['forumsell']) {
				$fids .= ",'$rt[fid]'";
			}
		}
		$fids && $fids = substr($fids,1);
		writeover(D_P.'data/bbscache/commonforum.php',"<?php\r\n\$fids = \"$fids\";\r\n?>");
	}

	if (!isset($fids)) {
		include (D_P.'data/bbscache/commonforum.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 (@filemtime(D_P."data/tplcache/$template.$EXT")>filemtime(M_P."template/$template.$EXT")) {
		return D_P."data/tplcache/$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) {
	if (strtolower($to_encoding) == strtolower($from_encoding)) {
		return $str;
	} elseif (function_exists('mb_convert_encoding')) {
		return mb_convert_encoding($str,$to_encoding,$from_encoding);
	} else {
		require_once(R_P.'wap/chinese.php');
		$chs = new Chinese($from_encoding,$to_encoding);
		return $chs->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;
	}

}
?>