<?php
class Functions{
	public $config;
    private $runStart;
    private $isPhpVersion;
	public function __construct( ){
		global $config;
		$this->config = $config;

		$this->runStart = $this->time( true);
	}

	/**
	 * 设置COOKIE
	 * @param unknown_type $name
	 * @param unknown_type $value
	 * @param unknown_type $time 过期时间,�?则关闭浏览器失效getFlashVars
	 */
	public function setCookie($name, $value, $time=0){
	    $expires = $time ? $this->time()+(int)$time : 0;
	    setcookie( $name, $value, $expires, '/');
    }

    public function header(){
		header( "Content-Type:text/html; charset=utf-8" );
    }

    public function nocache(){
        header("Pragma:no-cache");
        header("Cache-Type:no-cache, must-revalidate");
        header("Expires: -1");
    }

    public function dp3p(){
	   header("P3P:CP='ALL DSP CURa ADMa DEVa CONi OUT DELa IND PHY ONL PUR COM NAV DEM CNT STA PRE'");
    }
	
    /**
     * 获取IP
     * @return IP
     */
	function getip() {
		if ($_SERVER ["HTTP_X_FORWARDED_FOR"])
			$ip = $_SERVER ["HTTP_X_FORWARDED_FOR"];
		else if ($_SERVER ["HTTP_CLIENT_IP"])
			$ip = $_SERVER ["HTTP_CLIENT_IP"];
		else if ($_SERVER ["REMOTE_ADDR"])
			$ip = $_SERVER ["REMOTE_ADDR"];
		else if (getenv ( "HTTP_X_FORWARDED_FOR" ))
			$ip = getenv ( "HTTP_X_FORWARDED_FOR" );
		else if (getenv ( "HTTP_CLIENT_IP" ))
			$ip = getenv ( "HTTP_CLIENT_IP" );
		else if (getenv ( "REMOTE_ADDR" ))
			$ip = getenv ( "REMOTE_ADDR" );
		else
			$ip = "Unknown";
		return $ip;
	}

    /**
     * 返回浏览器信�?ver为版本号,nav为浏览器�?     */
    function getbrowser(){
    	$browsers = "mozilla msie gecko firefox ";
		$browsers.= "konqueror safari netscape navigator ";
		$browsers.= "opera mosaic lynx amaya omniweb";
		$browsers = split(" ", $browsers);
		$nua = strToLower( $_SERVER['HTTP_USER_AGENT']);
		$l = strlen($nua);
		for ($i=0; $i<count($browsers); $i++){
		  $browser = $browsers[$i];
		  $n = stristr($nua, $browser);
		  if(strlen($n)>0){
		   $arrInfo["ver"] = "";
		   $arrInfo["nav"] = $browser;
		   $j=strpos($nua, $arrInfo["nav"])+$n+strlen($arrInfo["nav"])+1;
		   for (; $j<=$l; $j++){
		     $s = substr ($nua, $j, 1);
		     if(is_numeric($arrInfo["ver"].$s) )
		     $arrInfo["ver"] .= $s;
		     else
		     break;
		   }
		  }
		}
		return $arrInfo;
    }


    public function magic_quote( $mixVar){
        if( get_magic_quotes_gpc()){
            if(is_array( $mixVar)){
                foreach ( $mixVar as $key => $value){
                    $temp[$key] = $this->magic_quote( $value);
                }
            }else{
                $temp = stripslashes( $mixVar);
            }
            return $temp;
        }else{
        	return $mixVar;
        }
    }

    public function stripslashes_deep($value)
	{
	    $value = is_array($value) ?
	                array_map('stripslashes_deep', $value) :
	                stripslashes($value);
	    return $value;
	}

    /**
     * 数组分页
     * @param unknown_type $array
     * @param unknown_type $num 每页显示个数
     * @param unknown_type $now 当前页码,0开�?     * @param unknown_type $url 除去p=后的url
     * @return unknown
     */
    function apart_page( $array, $num, $now, $url){
		$count = count( $array);
		$now = min($now, floor($count/$num));
		if($count < $num){
			return array($array, '');
		}else{
			if($now!=0){
				$str .= '<a href="'.$url.'">|&lt;</a> <a href="'.$url.'?p='.($now-1).'">&lt;</a> ';
			}
			$str .= $num*$now+1;
			$str .= "~";
			$str .= ($num*$now)+$num;
			if($now!=floor($count/$num)){
				$str .= '<a href="'.$url.'?p='.($now+1).'">&gt;</a> <a href="'.$url.'?p='.floor($count/$num).'">&gt;|</a> ';
			}
			return array(array_slice($array, $num*$now, $num), $str);
		}
	}

	/**
     * �?arr的长和宽等比例缩小至$arrTo resize(array($array['width'],$array['height']), array(160,120))
     * @return unknown
     */
    function resize($arr, $arrTo ){
        $arr[0] = $arr[0]>10 ? $arr[0] : $arrTo[0];
        $arr[1] = $arr[1]>10 ? $arr[1] : $arrTo[1];
        $arrTo[0] = $arrTo[0]<=0 ? 160 : $arrTo[0];
        $arrTo[1] = $arrTo[1]<=0 ? 120 : $arrTo[1];
        $temp = $arr;
        //如果宽度超出
        if( $arr[0] > $arrTo[0]){
            $temp[0] = $arrTo[0];
            $temp[1] = (int)($temp[0]*$arr[1]/$arr[0]);
            if( $temp[1] > $arrTo[1]){
                $temp[1] = $arrTo[1];
                $temp[0] = (int)($arr[0]*$temp[1]/$arr[1]);
            }
        }
        //如果高度超出
        if( $arr[1] > $arrTo[1] ){
            $temp[1] = $arrTo[1];
            $temp[0] = (int)($arr[0]*$temp[1]/$arr[1]);
            if( $temp[0] > $arrTo[0]){
                $temp[0] = $arrTo[0];
                $temp[1] = (int)($temp[0]*$arr[1]/$arr[0]);
            }
        }
        return $temp;
    }

    /**
     * 返回UNIX时间�?     * @param boolen $float 是否精确到微�?     * @return int/float
     */
	public function time( $float=false){
		return $float ? microtime( true) : time();
	}

	public function runTime(){
	    return $this->time( true) - $this->runStart;
	}


    /**
	 * @param int $uid
	 * @return string
	 */
	function get_avatar($mid, $size=0) {
		$size = in_array($size, array(0, 1, 2)) ? $size : 1;
		$mid = abs(intval($mid));
		$mid = sprintf("%09d", $mid);
		$dir1 = substr($mid, 0, 3);
		$dir2 = substr($mid, 3, 2);
		$dir3 = substr($mid, 5, 2);
		return $dir1.'/'.$dir2.'/'.$dir3.'/'.substr($mid, -2)."$size.jpg";
	}

	//获取个人主页
	function get_site($sid, $sitemid, $url=''){
		if( $sid > 99){ //漫游个人主页地址
			return 'http://uchome.manyou.com/profile/' . $sitemid;
		}elseif ( $sid==19){ //雅虎
            return 'http://guanxi.koubei.com/showprofile.php?uid=0' . $sitemid;
        }elseif ( $sid==1){ //校内
            return 'http://xiaonei.com/profile.do?id=' . $sitemid;
        }
		return 'http://uchome.manyou.com/profile/' . $sitemid;
	}
	/**
	 * 	制作flash参数
	 */
	function getFlashVars( $aLoad) {
		$aVars['uid'] 		= $aLoad['uid'];
		$aVars['sid'] 		= $aLoad['sid'];
		$aVars['sesskey'] 	= $aLoad['sesskey'];
		$aVars['name'] 		= $aLoad['name'];
		$aVars['gateway'] 	= $aLoad['gateway'];
		$aVars['flashUrl'] 	= $aLoad['flashUrl'];
		$aVars['dataUrl'] 	= $aLoad['dataUrl'];
		$aVars['imageUrl'] 	= $aLoad['imageUrl'];
		$aVars['webroot'] 	= $aLoad['webroot'];
		$aVars['isFirst'] 	= $aLoad['isFirst'];
		$aVars['flashver'] 	= json_encode($aLoad['flashver']);
		$aVars['hallip'] 	= json_encode($aLoad['hallip']);
		$aVars['other'] 	= json_encode($aLoad['other']);
		$aVars['time'] 		= NOW;
		$aVars['isFans'] 	= $aLoad['isFans'];
		$aVars['isCreate'] 	= $aLoad['isCreate'];
		$aVars['isPayUrl']	= $aLoad['isPayUrl'];
		$aVars['ispay']		= $aLoad['ispay'];
		$aVars['img']		= $aLoad['img'];
		$aVars['money']		= $aLoad['money'];
		$aVars['mtkey']		= $aLoad['mtkey'];
		$aVars['skey']		= $aLoad['skey'];
		
		foreach ( $aVars as $key => $value){
			$flashvars .= $key . '=' . urlencode($value) . '&';
		}
		return substr( $flashvars, 0, -1);
	}

	public function __destruct(){

	}
	
	public function writeErrorLog($msg){
		echo PATH_LOG;die;
	}
	
	static function uint( $num){
		return max(0, (int)$num);
	}
	/**
	 * 安全性检测.调用escape存入的,一定要调unescape取出
	 */
	static function escape( $string){
		if ( oo::functions()->isPhpVersion()) {
			return addslashes( trim($string));
		}
		return mysql_escape_string( trim($string));
	}
	/**
	 * 判断当前字符串是否为指定格式
	 * @param string $str 需要判断的字符串
	 * @param string $format 日期格式
	 */
	static function checkDateTimeFormat($str,$format='Y-m-d'){
		$unixTime=strtotime($str);
        $checkDate= date($format, $unixTime);
        if($checkDate==$str){
        	return true;
        }else{
        	return false;
        }
	}
	/**
	 * 判断当前环境php版本是否大于大于等于指定的一个版本
	 * @param sreing $version default=5.3.0
	 * @return boolean 大于true,小于false
	 */
	public function isPhpVersion( $version = '5.3.0' ) {
		if ( $this->isPhpVersion) {
			$php_version = $this->isPhpVersion;
		} else {
			$php_version = explode( '-', phpversion() );
		}
		$is_pass = strnatcasecmp( $php_version[0], $version ) >= 0 ? true : false;
		return $is_pass;
	}
	/** 
	 * 将字符串ID转换为对应的数字ID 不可逆  转换后不唯一
	 */
	public function midToNumber( $mid){
		return is_numeric($mid) ? $mid : abs( crc32($mid));
	}
	/**
	 * 把数组序列成Server识别的.有缺陷,不能是null类型的
	 * @param Array $array
	 */
	public static function serialize( $array ){
		return str_replace( '=', ':', http_build_query( $array, null, ',' ) );
	}

	/**
	 * 把字符串反序列成索引数组
	 * @param String $string
	 */
	public static function unserialize( $string ){
		parse_str( str_replace( array( ':', ',' ), array( '=', '&' ), $string ), $array );
		return (array) $array;
	}
	/**
     * 获取网页数据
     * @param string $url
     * @param array $post_data post的数据,为空时表示get请求
     * @param string $json 返回数据格式，0表示json 1原数据返回
     * @return array/int
     */
	public static function curl( $url, $post_data=array(), $json=1, $timeout=20) 
	{
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
		if(!empty($post_data))
		{
			curl_setopt($ch, CURLOPT_POST, true);
	        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
		}
		$result = curl_exec ( $ch );
		curl_close($ch);
		return $data = empty($json) ? $result : json_decode($result, true);
	}
	/**
	 * 返回
	 * @param unknown $array
	 */
	public function sendData( $array, $stime){
		$etime = oo::functions()->time( true);
		$aRet = array();
		$aRet['code'] = $array['code'];
		$aRet['codemsg'] = $array['codemsg'];
		$aRet['sid'] = oo::$config['sid'];
		$aRet['data'] = $array['data'];
		$aRet['time'] = NOW;
		$aRet['exetime'] = $etime - $stime; //脚本执行时间
// 		if (PRODUCTION_SERVER) {
// 			echo gzcompress( json_encode( $aRet), 9);
// 		} else {
			echo json_encode( $aRet);
// 		}
// 		echo json_encode( $aRet);
// 		exit();
	}
	/**
	 * 
	 * @param unknown $string
	 * @return boolean|number
	 */
	public static function phutil_is_utf8($string) {
		if (function_exists('mb_check_encoding')) {
			return mb_check_encoding($string, 'UTF-8');
		}
	
		$regex =
		"/^(".
		"[\x01-\x7F]+".
		"|([\xC2-\xDF][\x80-\xBF])".
		"|([\xE0-\xEF][\x80-\xBF][\x80-\xBF])".
		"|([\xF0-\xF4][\x80-\xBF][\x80-\xBF][\x80-\xBF]))*\$/";
		return preg_match($regex, $string);
	}
	/**
	 * 
	 * @param unknown $string
	 * @return unknown|string
	 */
	public function phutil_utf8ize($string) {
		if ($this->phutil_is_utf8($string)) {
			return $string;
		}
		$result = array();
		$regex =
		"/([\x01-\x7F]".
		"|[\xC2-\xDF][\x80-\xBF]".
		"|[\xE0-\xEF][\x80-\xBF][\x80-\xBF]".
		"|[\xF0-\xF4][\x80-\xBF][\x80-\xBF][\x80-\xBF])".
		"|(.)/";
	
		$offset = 0;
		$matches = null;
		while (preg_match($regex, $string, $matches, 0, $offset)) {
			if (!isset($matches[2])) {
				$result[] = $matches[1];
			} else {
				$result[] = "\xEF\xBF\xBD";
			}
			$offset += strlen($matches[0]);
		}
		return implode('', $result);
	}
	/**
	 * 验证是否有定义这个全局变量并且值是否为true
	 * @param unknown $constName
	 * @return mixed|boolean
	 */
	public function flag($constName)
	{
		if (defined($constName))
		{
			return constant($constName);
		}
		return false;
	}

	/**
	 * 客户端版本对比
	 *
	 * @param string $version1 版本号1，格式： 1.0.1
	 * @param string $version2 版本号2
	 * @return int 比较结果: 1>2结果大于0 1==2结果等于0 1<2结果小于0
	 */
	public static function version_compare( $version1, $version2 ){
		$version1_arr = explode( '.', (string) $version1, 3 );
		$version2_arr = explode( '.', (string) $version2, 3 );
		$version1_int = intval( $version1_arr[0] ) * 1000000 + intval( $version1_arr[1] ) * 1000 + intval( $version1_arr[2] );
		$version2_int = intval( $version2_arr[0] ) * 1000000 + intval( $version2_arr[1] ) * 1000 + intval( $version2_arr[2] );
		return ($version1_int - $version2_int);
	}

	/**
	 * 验证ip地址
	 * @param        string    $ip, ip地址
	 * @return        bool    正确返回true, 否则返回false
	 */
	public static function checkIP( $ip ){
		$ip = trim( $ip );
		$pt = '/^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/';
		if( preg_match( $pt, $ip ) === 1 ){
			return true;
		}
		return false;
	}

	/**
	 * @desc 检查来源IP是否属于boyaa公司网段
	 * @param String $ip IP地址
	 * @return Boolean 属于则返回true,否则返回false
	 */
	public function isBoyaaIp($ip=0){
		$ip = $ip ? $ip : $this->getip();
		if(!self::checkIP($ip)) return false;

		$cidrs = array(
			'127.0.0.1/32',			//表示：127.0.0.1
			'10.0.0.0/8',			//表示：10.0.0.0 ~ 10.255.255.255 A类内网
			'172.16.0.0/12',		//表示：172.16.0.0 ~ 172.31.255.255 B类内网
			'192.168.0.0/16',		//表示：192.168.0.0 ~ 192.168.255.255 C类内网
			'183.62.196.0/27',		//表示：183.62.196.0 ~ 183.62.196.31
			'103.29.141.72/30',		//表示：103.29.141.72 ~ 103.29.141.75
			'210.5.191.162/32',		//表示：210.5.191.162
			'202.60.204.52/32',	//表示：202.60.204.52
			'210.213.48.45/32',	//表示: 210.213.48.45
			'103.251.131.0/29', //新国际线路 14-11-10
			'119.81.169.160/27', //新增IP段 15-6-30
			'183.62.167.2/32',
			'203.160.93.103/32',
			'113.105.73.51/32',		//cms迁移机房
			'202.170.112.6/32',		//泰分公司
			'112.121.138.66/28',	//泰分公司备用IP
			'107.178.195.143/28',	
			//泰分IP调整，整理了下白名单，联系运维发现下属三个位置IP，先注释，没问题后删除 --- 2014.7.1
			//'202.153.93.171/32',	//表示：202.153.93.171
			//'119.81.15.146/32',		//表示：119.81.15.146
			//'59.152.235.224/27',	//表示：59.152.235.224 ~ 59.152.235.255
			'175.45.5.253/32',  //mf 机器
			'58.251.8.8/30',//联通线路
			'113.105.73.52/32', //cms迁移机房
			'119.81.186.192/28',//新加坡机房
			'119.81.149.240/29',
			'119.81.15.146/32',
			'119.81.87.28/32',
			'119.81.92.204/32',
			'103.61.193.12/32',
			'103.61.193.18/32',
			'103.61.193.125/32',
			'14.215.134.128/28',//内网服务器新增出口ip
		);

		foreach( $cidrs as $cidr ){
			list( $net, $mask ) = explode ( '/', $cidr );
			if( ( ip2long ( $ip ) & ~ ( ( 1 << ( 32 - $mask ) ) - 1) ) === ip2long ( $net ) ){
				return true;
			}
		}
		return false;
	}

	/**
	 * 是否为国内的IP
	 * @param string $ip
	 * @return bool
	 */
	public function isCnIP($ip = 0) {
		$ip = $ip ? $ip : $this->getip();
		if(!self::checkIP($ip)) return false;

		$cidrs = oo::cfg('cniplist');
		if (!$cidrs) return false;

		foreach( $cidrs as $cidr ){
			list( $net, $mask ) = explode ( '/', $cidr );
			if( ( ip2long ( $ip ) & ~ ( ( 1 << ( 32 - $mask ) ) - 1) ) === ip2long ( $net ) ){
				return true;
			}
		}
		return false;
	}



    /**
     * 是否泰国内的IP
     * @param string $ip
     * @return bool
     */
    public function isThIP($ip = 0) {
        $ip = $ip ? $ip : $this->getip();
        if(!self::checkIP($ip)) return false;

        $cidrs = oo::cfg('thiplist');
        if (!$cidrs) return false;

        foreach( $cidrs as $cidr ){
            list( $net, $mask ) = explode ( '/', $cidr );
            if( ( ip2long ( $ip ) & ~ ( ( 1 << ( 32 - $mask ) ) - 1) ) === ip2long ( $net ) ){
                return true;
            }
        }
        return false;
    }


    /**
     * 通过Ip获取国家信息
     * @param null $ip
     * @param string $purpose
     * @param bool $deep_detect
     * @return array|null|string
     */
    function ip_info($ip = NULL, $purpose = "location", $deep_detect = TRUE) {
        $output = NULL;
        if (filter_var($ip, FILTER_VALIDATE_IP) === FALSE) {
            $ip = $_SERVER["REMOTE_ADDR"];
            if ($deep_detect) {
                if (filter_var(@$_SERVER['HTTP_X_FORWARDED_FOR'], FILTER_VALIDATE_IP))
                    $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
                if (filter_var(@$_SERVER['HTTP_CLIENT_IP'], FILTER_VALIDATE_IP))
                    $ip = $_SERVER['HTTP_CLIENT_IP'];
            }
        }
        $purpose  = str_replace(array("name", "\n", "\t", " ", "-", "_"), NULL, strtolower(trim($purpose)));
        $support  = array("country", "countrycode", "state", "region", "city", "location", "address");
        $continents = array(
            "AF" => "Africa",
            "AN" => "Antarctica",
            "AS" => "Asia",
            "EU" => "Europe",
            "OC" => "Australia (Oceania)",
            "NA" => "North America",
            "SA" => "South America"
        );
        if (filter_var($ip, FILTER_VALIDATE_IP) && in_array($purpose, $support)) {
            $ipdat = @json_decode(file_get_contents("http://www.geoplugin.net/json.gp?ip=" . $ip));
            if (@strlen(trim($ipdat->geoplugin_countryCode)) == 2) {
                switch ($purpose) {
                    case "location":
                        $output = array(
                            "city"      => @$ipdat->geoplugin_city,
                            "state"     => @$ipdat->geoplugin_regionName,
                            "country"    => @$ipdat->geoplugin_countryName,
                            "country_code"  => @$ipdat->geoplugin_countryCode,
                            "continent"   => @$continents[strtoupper($ipdat->geoplugin_continentCode)],
                            "continent_code" => @$ipdat->geoplugin_continentCode
                        );
                        break;
                    case "address":
                        $address = array($ipdat->geoplugin_countryName);
                        if (@strlen($ipdat->geoplugin_regionName) >= 1)
                            $address[] = $ipdat->geoplugin_regionName;
                        if (@strlen($ipdat->geoplugin_city) >= 1)
                            $address[] = $ipdat->geoplugin_city;
                        $output = implode(", ", array_reverse($address));
                        break;
                    case "city":
                        $output = @$ipdat->geoplugin_city;
                        break;
                    case "state":
                        $output = @$ipdat->geoplugin_regionName;
                        break;
                    case "region":
                        $output = @$ipdat->geoplugin_regionName;
                        break;
                    case "country":
                        $output = @$ipdat->geoplugin_countryName;
                        break;
                    case "countrycode":
                        $output = @$ipdat->geoplugin_countryCode;
                        break;
                }
            }
        }
        return $output;
    }

	/**
	 * 连接复杂数组.用于生成验证字串等
	 * @param Mixed $params
	 * @param String $key key前缀
	 * @param Boolean $strip 是否要判断magic_quotes执行去反斜杠操作
	 * @param Boolean $iskrsort 是否要排序
	 * @return String
	 */
	public static function joins( $params, $key = null, $strip = false, $iskrsort = true ){
		$ret = array( );
		if( is_array( $params ) ){
			$iskrsort && krsort( $params, SORT_STRING );
			foreach( $params as $k => $v ){
				if( (!empty( $key )) || ($key === 0) ){
					$k = $key . '[' . urlencode( $strip && get_magic_quotes_gpc() ? stripslashes( $k ) : $k  ) . ']';
				}
				if( is_array( $v ) || is_object( $v ) ){
					array_push( $ret, self::joins( $v, $k, $strip ) );
				}else{
					array_push( $ret, $k . '=' . urlencode( $strip && get_magic_quotes_gpc() ? stripslashes( $v ) : $v  ) );
				}
			}
		}
		return implode( '&', $ret );
	}

	/**
	 * 从URL参数中获取有效
	 * @param Array $param 键值对.如$_GET
	 * @param int $expire 过期时间如7天内有效 7*24*60*60
	 * @param String $prefix 前缀.对应生成方法
	 * @param String $secret 密钥
	 * @return Array 键值对(如果未通过验证则为空数组)
	 */
	public static function get( $param, $expire = 0, $prefix = 'by_', $secret = '^$_$^' ){
		if( !(is_array( $param ) && count( $param )) ){ //没有参数
			return array( );
		}
		foreach( (array) $param as $k => $v ){
			if( strpos( $k, $prefix ) === 0 ){
				$aParams[$k] = $aReturn[str_replace( $prefix, '', $k )] = $v; //临时存储和需要返回的原始键值对
			}
		}
		$sig = $aParams[$prefix . 'sig'];
		unset( $aParams[$prefix . 'sig'] );
		if( $sig !== md5( $secret . self::joins( $aParams, null, true ) . $secret ) ){ //签名未通过验证
			return array( );
		}
		if( $expire && (time() - $aParams[$prefix . 'time'] > $expire) ){//有超时设置
			return array( );
		}
		return (array) $aReturn;
	}

	/**
	 * 泰语单音节昵称问题
	 * @param string $nick
	 * @return string
	 */
	public function escapeNick($nick) {
		if (empty($nick)) {
			return $nick;
		}
		$arr = array("ั", "ิ", "ี", "ึ", "ื", "ุ", "ู", "ฺ", "็", "่", "้", "๊", "๋", "์", "ํ", "๎");
		$str = str_replace($arr, "", $nick);
		if (empty($str)) {
			return $nick . '.';
		} else {
			return $nick;
		}
	}

	/**
	 * 游戏币数量格式化
	 * @param int $num
	 * @return string
	 */
	public function numFormat($num) {
		if (!$num || $num < 1000) return $num;
		if ($num < 1000000) {
			$c = array(1000, 'K');
		} elseif ($num < 1000000000) {
			$c = array(1000000, 'M');
		} else {
			$c = array(1000000000, 'B');
		}
		if ($num % $c[0] == 0) {
			$ret = number_format($num / $c[0], -3, ',', ',') . $c[1];
		} else {
			$tmp = floor($num / $c[0]);
			$n = floor(($num % $c[0]) * 10 / $c[0]);
			if ($n != 0) {
				$ret = sprintf("%s.%s%s", number_format($tmp, -3, ',', ','), $n, $c[1]);
			} else {
				$ret = number_format($tmp, -3, ',', ',') . $c[1];
			}
		}
		return $ret;
	}

	/**
	 * 黑名单，默认是为支付第三方，兑换实物添加
	 * MikeMei
	 * @param int $type
	 * 加type为1是为了防止以后有扩展
	 */
	public function checkBlackIp($type = 1){
		$blackIpList = array('58.8.176.68', '124.120.191.139', '104.132.115.99'); //黑名单
		$myip = $this->getip();//PHP获取到的IP
		$longIp = ip2long($myip);
		if( $longIp == -1 || $longIp === FALSE ){ //获取IP错误
			return false;
		}
		$isblackip = false;
		foreach( $blackIpList as $ip ){
			if( sprintf("%u", $longIp) == sprintf("%u", ip2long($ip)) ){
				$isblackip = true;
				break;
			}
		}

		return $isblackip;
	}

	public static function recall_inner()
	{
		return array(
			'uid',
			'lasttime'
		);
	}

	/**
	 * 压缩
	 * $metas 被压缩的key, example: ovalue::table()
	 * $data  被压缩的数组,example: array('tid'=>1002, 'sb'=>50)
	 */
	public static function compress($metas, $data)
	{
		$temp = array();
		foreach($metas as $index => $name)
		{
			if (!isset($data[$name]))
			{
				continue;
			}
			if ($data[$name] === null)
			{
				$data[$name] = '';
			}
			$temp[$index] = $data[$name];
		}
		return $temp;
	}

	/**
	 * 解压
	 * $metas 被解压的key, example: ovalue::table()
	 * $data  被解压的数组,example: array(0=>1002, 0=>50)
	 */
	public static function decompress($metas, $data)
	{
		$temp = array();
		foreach($data as $index => $value)
		{
			if (isset($metas[$index]))
			{
				$temp[$metas[$index]] = $value;
			}
		}
		return $temp;
	}

	/**
	* 获取server的GameSid
	* 方法: redis拿到GameSid后
		$gid = 6619292;
		$hex =  0x0000FFFF;
		$a = $gid & $hex;
		echo $a;
	*/
	public static function getServerGameSid($gamesid = 0)
	{
		if( !$gamesid ){
			return 0;
		}
		$gamesid = intval($gamesid);
		$hex = 0x0000FFFF;
		return $gamesid & $hex;
	}


    /**
     * Notes:批量写入
     * User: wsc
     * Time: 2020/12/24 10:42
     * @param $tb
     * @param $fieldArr array 字段
     * @param $dataArr  array 数据
     * @param int $dataArrIsJson int|bool 是否json数组
     * @return string
     */
    static function db_intsertArrSQL($tb,$fieldArr,$dataArr,$dataArrIsJson=0){
        foreach ($dataArr as $data){
            if($dataArrIsJson){
                $data = json_decode($data,true);
            }
            $value = "(";
            foreach ($data as $key=>$val){
                $value .="'{$val}',";
            }
            $value = trim($value,',');
            $value .=")";
            $datas[] = $value;
        }
        $keys = array_values($fieldArr);
        $fields = '(`'.implode('`, `',$keys).'`)';
        $values = implode(',',$datas);
        $sql= "INSERT INTO {$tb} {$fields} VALUES {$values}";
        return $sql;
    }
    /**
     * Notes:过滤非法字符
     * User: wsc
     * Time: 2020/5/15 16:03
     * @param $data
     * @return mixed
     */
    public  static function db_fieldAllow($data){
        foreach ($data as $key=>$val) {
            if (is_int($val)) {
                $val = intval($val);
            } elseif (is_float($val)) {
                $val = floatval($val);
            } elseif (preg_match('/^\(\w*(\+|\-|\*|\/)?\w*\)$/i', $val)) {
                // 支持在字段的值里面直接使用其它字段 ,例如 (score+1) (name) 必须包含括号
                $val = $val;
            } elseif (is_string($val)) {
                //将字符串中的单引号（'）、双引号（"）、反斜线（\）与 NUL（NULL 字符转义
                $val = "'".addslashes($val)."'";

            }
            $ret[$key] = $val;
        }
        return $ret;
    }
}
