<?php
namespace App;

use Exception;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Validator;


class Util {
    /**
     * 根据南美国家（两位字母缩写）验证电话号码
     *
     * 以下规则示例（号码为不含国际区号和本地区号的订户号码）：
     *
     * - AR (阿根廷)：固定电话 7～8 位；移动电话 10 位
     * - BO (玻利维亚)：固定电话 7 位；移动电话 8 位
     * - BR (巴西)：固定电话 8 位（首位 2～8）；移动电话 9 位（以 9 开头）
     * - CL (智利)：固定电话 8 位；移动电话 9 位（以 9 开头）
     * - CO (哥伦比亚)：固定电话 7 位（首位非 0）；移动电话 10 位（以 3 开头）
     * - EC (厄瓜多尔)：固定电话 7 位；移动电话 9 位（以 9 开头）
     * - GY (圭亚那)：7 位数字
     * - PY (巴拉圭)：固定电话 7 位；移动电话 9 位（以 9 开头）
     * - PE (秘鲁)：固定电话 7 位；移动电话 9 位（以 9 开头）
     * - SR (苏里南)：7 位数字
     * - UY (乌拉圭)：固定电话 7 位；移动电话 8 位
     * - VE (委内瑞拉)：固定电话 7 位；移动电话 10 位（以 4 开头）
     *
     * @param string $country 两位国家代码（如 "AR", "BR", "CL", 等）
     * @param string $number 纯数字的电话号码（不含区号及区号分隔符）
     * @return bool 返回是否符合该国规则
     * @throws Exception 当提供不支持的国家代码时
     */
    function validateSouthAmericanPhone($country, $number) {
        // 定义各国的正则表达式规则
        $rules = [
            'AR' => '/^(?:\d{7,8}|\d{10})$/',          // 阿根廷：固定电话 7～8 位或移动电话 10 位
            'BO' => '/^(?:\d{7}|\d{8})$/',              // 玻利维亚：固定 7 位或移动 8 位
            'BR' => '/^(?:[2-8]\d{7}|9\d{8})$/',         // 巴西：固定 8 位（首位 2-8）或移动 9 位（以 9 开头）
            'CL' => '/^(?:\d{8}|9\d{8})$/',              // 智利：固定 8 位或移动 9 位（以 9 开头）
            'CO' => '/^(?:[1-9]\d{6}|3\d{9})$/',         // 哥伦比亚：固定 7 位（首位非 0）或移动 10 位（以 3 开头）
            'EC' => '/^(?:\d{7}|9\d{8})$/',              // 厄瓜多尔：固定 7 位或移动 9 位（以 9 开头）
            'GY' => '/^\d{7}$/',                        // 圭亚那：7 位数字
            'PY' => '/^(?:\d{7}|9\d{8})$/',              // 巴拉圭：固定 7 位或移动 9 位（以 9 开头）
            'PE' => '/^(?:\d{7}|9\d{8})$/',              // 秘鲁：固定 7 位或移动 9 位（以 9 开头）
            'SR' => '/^\d{7}$/',                        // 苏里南：7 位数字
            'UY' => '/^(?:\d{7}|\d{8})$/',              // 乌拉圭：固定 7 位或移动 8 位
            'VE' => '/^(?:\d{7}|4\d{9})$/',              // 委内瑞拉：固定 7 位或移动 10 位（以 4 开头）
        ];

        $country = strtoupper($country);
        if (!isset($rules[$country])) {
            throw new Exception("不支持的国家代码: {$country}");
        }

        // 清除号码中的空格和连字符
        $number = preg_replace('/[\s-]+/', '', $number);

        return (bool) preg_match($rules[$country], $number);
    }
    public static function sanitize($value): string
    {
        return empty($value) ? "" : preg_replace('/[^\d]/', '', $value);
    }
    public static function cleanEmptyString($value): string
    {
        return preg_replace('/[\n\r\t\v\0]/', '', $value);
    }
    public static function validatePhone($phone) {
        // 正则表达式：允许空格、加号、括号、连字符、点号等符号
        $pattern = '/^\+?(\d{1,3})?[-.\s()]?\(?\d{1,4}\)?[-.\s()]?\d{1,4}[-.\s()]?\d{1,9}$/';

        return preg_match($pattern, $phone) === 1;
    }
    public static function validateEmail( $EmailAddress): bool
    {
        $validator = Validator::make(
            ['email' => $EmailAddress],
            ['email' => 'required|email']
        );

        if ($validator->fails()) {
            self::WriteLog('emailfail',$validator->fails());
           return false;
        }
        return true;
    }
    public static function validateCpf( $value): bool
    {
        $c = self::sanitize($value);

        if (mb_strlen($c) != 11 || preg_match("/^{$c[0]}{11}$/", $c)) {
            return false;
        }

        for (
            $s = 10, $n = 0, $i = 0; $s >= 2; $n += $c[$i++] * $s--
        ) {
        }

        if ($c[9] != ((($n %= 11) < 2) ? 0 : 11 - $n)) {
            return false;
        }

        for (
            $s = 11, $n = 0, $i = 0; $s >= 2; $n += $c[$i++] * $s--
        ) {
        }

        if ($c[10] != ((($n %= 11) < 2) ? 0 : 11 - $n)) {
            return false;
        }

        return true;
    }
    public static $KIND_ID_DZPK= 917;              //德州扑克public static public static $
    public static $KIND_ID_TEXAS= 918;              //新德州扑克public static public static $
    public static $KIND_ID_BCBM=2009;               //奔驰宝马public static public static $
    public static $KIND_ID_BRTP= 2010;              //百人TPpublic static public static $
    public static $KIND_ID_BRAB= 2012;              //百人ABpublic static public static $
    public static $KIND_ID_BRDZ= 2013;              //百人德州public static public static $
    public static $KIND_ID_BRBYZB=2014;            //龙虎斗public static public static $
    public static $KIND_ID_LHD=6021;               //龙虎斗public static public static $

    public static $KIND_ID_FAKERABBIT= 3010;              //罗马 拉霸public static public static $
    public static $KIND_ID_LBROMAN= 3010;              //罗马 拉霸public static public static $
    public static $KIND_ID_LBFRUIT= 3011;              //水果 拉霸public static public static $
    public static $KIND_ID_FRUITSLOTS= 3013;              //水果机BBBpublic static public static $
    public static $KIND_ID_FRUIT9X= 3014;              //9线水果 拉霸public static public static $
    public static $KIND_ID_SGYYL= 3015;              //水果摇摇乐public static public static $
    public static $KIND_ID_FOOTBALL= 3016;              //足球拉霸public static public static $
    public static $KIND_ID_OLYMPUS= 3017;              //消除拉霸public static public static $
    public static $KIND_ID_TREASURE= 3018;              //消除拉霸public static public static $
    public static $KIND_ID_RAIO= 3019;              //闪电public static public static $
    public static $KIND_ID_HALLOWEEN= 3020;              //万圣节public static public static $
    public static $KIND_ID_HIVE= 3021;              //蜂巢public static public static $
    public static $KIND_ID_GRANDWHEEL= 3022;              //巨轮public static public static $
    public static $KIND_ID_ATHENA= 3067;              //雅典娜

    public static $KIND_ID_CACHETA= 4000;      //cachetapublic static public static $
    public static $KIND_ID_TRUCO= 4010;      //trucopublic static public static $
    public static $KIND_ID_CRASH= 4020;     //爆点public static public static $
    public static $KIND_ID_MINES= 4021;     //扫雷public static public static $
    public static $KIND_ID_AVIATOR= 4028;     //扫雷public static public static $
    public static $KIND_ID_AVIATOR2= 4029;     //扫雷public static public static $
    public static $KIND_ID_JOKER5x1= 5002;     //MasterJokerpublic static public static $
    public static $KIND_ID_TIGER= 5006;     //MasterJokerpublic static public static $
    public static $KIND_ID_JOKER3x3= 8001;     //SuperJokerpublic static public static $

    public static function getClientVer(){
        $cv=7;
        if(isset($_REQUEST['cv'])){
            $cvstr=explode('.',$_REQUEST['cv']);
            $cv=(int)array_pop($cvstr);
        }
        return $cv;
    }
    public static function getPackConfigs(){
        $ios1='https://apps.apple.com/br/app/id6448916752?l=pt-br';
        $ios2='https://apps.apple.com/br/app/id6449389054?l=pt-br';
        $configs=[
//            ['bundleid'=>"com.ouro777.online",'channel'=>100,'ios'=>$ios1,'name'=>'slotsouro_olmp','online'=>false,'sms'=>'OURO'],
        ];
        if(!Redis::exists('allpacks')) {
            $allpacks = DB::table('QPPlatformDB.dbo.ChannelPackageName')->select('PackageName', 'Channel', 'StoreName','Remarks')->get()->toArray();
            foreach ($allpacks as $pack){
                $configs[]=[
                    'bundleid'=>$pack->PackageName,
                    'channel'=>$pack->Channel,
                    'ios'=>$ios1,
                    'name'=>$pack->Remarks,
                    'online'=>false,
                    'sms'=>$pack->StoreName,
                ];
            }
            Redis::setex('allpacks',600,json_encode($configs));
        }else{
            $configs=json_decode(Redis::get('allpacks'),true);
        }
        return $configs;

    }
    public static function getPackageByURL($ihaveparam=null){
        $configs=self::getPackConfigs();
        $packInfos=[];
        foreach ($configs as $pack){
            $packInfos[$pack['bundleid']]=$pack;
            $packInfos[$pack['channel']]=$pack;
        }
        //直接返回
        if(isset($ihaveparam)&&isset($packInfos[$ihaveparam]))return $packInfos[$ihaveparam];

        $packInfo=$packInfos[100];
        if(isset($_REQUEST['Channel'])){
            $packInfo=$packInfos[$_REQUEST['Channel']];
            if(isset($packInfo))return $packInfo;
        }
        if(isset($_REQUEST['channel'])){
            $packInfo=$packInfos[$_REQUEST['channel']];
            if(isset($packInfo))return $packInfo;
        }
        if(isset($_REQUEST['ChannelNumber'])){
            $packInfo=$packInfos[$_REQUEST['ChannelNumber']];
            if(isset($packInfo))return $packInfo;
        }
        $packageName=null;
        if(isset($_REQUEST['PackageName']))$packageName=$_REQUEST['PackageName'];
        if(!isset($packageName)&&isset($_REQUEST['bundleid']))$packageName=$_REQUEST['bundleid'];
        if(isset($packageName)){
            if(isset($packInfos[$packageName])){
                $packInfo=$packInfos[$packageName];
            }
        }
        return $packInfo;
    }


    public static function arraySort( $arr, $key, $sort = SORT_ASC ) {
        $newArr = array();
        foreach ( $arr as $k => $v ) {
            $v=(array)$v;
            $newArr[$k] = $v[$key];
        }
        array_multisort( $newArr, $sort, $arr );
        return $arr;
    }


    public static function removePunctuationAndNumbers($string) {
        // 使用正则表达式替换所有标点符号和数字
        $result = preg_replace('/[[:punct:]\d]/', '', $string);
        return $result;
    }
    public static function removePunctuation($string) {
        // 使用正则表达式替换所有标点符号和数字
        $result = preg_replace('/[[:punct:]]/', '', $string);
        return $result;
    }
    /**
     * 过滤上传特殊表情符号的
     * @param $str
     * @return mixed
     */
    public static function filter_emoji($str)
    {
        preg_match_all('/[\x{4e00}-\x{9fff}\d\w\s[:punct:]]+/u',$str,$result);

        return join('',$result[0]);
    }

    /**
     * 过滤掉字符串中的表情字符
     *
     * @param string $text 输入字符串
     * @return string 过滤后的字符串
     */
    public static function filterEmoji($text)
    {
        // 定义匹配表情字符的正则表达式模式
        $emojiPattern = '/[\x{1F600}-\x{1F64F}|' . // 表情符号
            '\x{1F300}-\x{1F5FF}|' . // 符号&图标
            '\x{1F680}-\x{1F6FF}|' . // 运输&地图符号
            '\x{1F700}-\x{1F77F}|' . // 额外的符号
            '\x{1F780}-\x{1F7FF}|' . // 额外的符号
            '\x{1F800}-\x{1F8FF}|' . // 额外的符号
            '\x{1F900}-\x{1F9FF}|' . // 额外的符号
            '\x{1FA00}-\x{1FA6F}|' . // 额外的符号
            '\x{1FA70}-\x{1FAFF}|' . // 额外的符号
            '\x{2600}-\x{26FF}|' .   // 杂项符号
            '\x{2700}-\x{27BF}|' .   // 丁头
            '\x{2B50}|' .            // 星号
            '\x{1F004}|' .           // 麻将牌
            '\x{1F0CF}|' .           // 扑克牌
            '\x{1F18E}|' .           // 白色圈圈
            '\x{1F191}-\x{1F251}|' . // 按键符号
            '\x{2B06}-\x{2B07}|' .   // 箭头
            '\x{2934}-\x{2935}|' .   // 箭头
            '\x{2B05}-\x{2B07}|' .   // 箭头
            '\x{3297}|' .            // 杂项符号
            '\x{3299}]|\x{3030}|\x{00A9}|\x{00AE}|\x{2122}/u';

        // 使用正则表达式替换匹配到的表情字符为空字符串
        return preg_replace($emojiPattern, '', $text);
    }

    public static function filterSpecialChar($str)
    {

        // 要替换的数学字符
        $math_chars = [
            '𝐀', '𝐁', '𝐂', '𝐃', '𝐄', '𝐅', '𝐆', '𝐇', '𝐈', '𝐉', '𝐊', '𝐋', '𝐌',
            '𝐍', '𝐎', '𝐏', '𝐐', '𝐑', '𝐒', '𝐓', '𝐔', '𝐕', '𝐖', '𝐗', '𝐘', '𝐙',
            '𝐚', '𝐛', '𝐜', '𝐝', '𝐞', '𝐟', '𝐠', '𝐡', '𝐢', '𝐣', '𝐤', '𝐥', '𝐦',
            '𝐧', '𝐨', '𝐩', '𝐪', '𝐫', '𝐬', '𝐭', '𝐮', '𝐯', '𝐰', '𝐱', '𝐲', '𝐳',
            '𝓐', '𝓑', '𝓒', '𝓓', '𝓔', '𝓕', '𝓖', '𝓗', '𝓘', '𝓙', '𝓚', '𝓛', '𝓜',
            '𝓝', '𝓞', '𝓟', '𝓠', '𝓡', '𝓢', '𝓣', '𝓤', '𝓥', '𝓦', '𝓧', '𝓨', '𝓩',
            '𝓪', '𝓫', '𝓬', '𝓭', '𝓮', '𝓯', '𝓰', '𝓱', '𝓲', '𝓳', '𝓴', '𝓵', '𝓶',
            '𝓷', '𝓸', '𝓹', '𝓺', '𝓻', '𝓼', '𝓽', '𝓾', '𝓿', '𝔀', '𝔁', '𝔂', '𝔃',
            '𝔄', '𝔅', '', '𝔇', '𝔈', '𝔉', '𝔊', '', '', '𝔍', '𝔎', '𝔏', '𝔐', '𝔑', '𝔒', '𝔓',
            '𝔔', '', '𝔖', '𝔗', '𝔘', '𝔙', '𝔚', '𝔛', '𝔜', '',
            '𝔞', '𝔟', '𝔠', '𝔡', '𝔢', '𝔣', '𝔤', '𝔥', '𝔦', '𝔧', '𝔨', '𝔩', '𝔪',
            '𝔫', '𝔬', '𝔭', '𝔮', '𝔯', '𝔰', '𝔱', '𝔲', '𝔳', '𝔴', '𝔵', '𝔶', '𝔷',
            '𝕬', '𝕭', '𝕮', '𝕯', '𝕰', '𝕱', '𝕲', '𝕳', '𝕴', '𝕵', '𝕶', '𝕷', '𝕸',
            '𝕹', '𝕺', '𝕻', '𝕼', '𝕽', '𝕾', '𝕿', '𝖀', '𝖁', '𝖂', '𝖃', '𝖄', '𝖅',
            '𝖆', '𝖇', '𝖈', '𝖉', '𝖊', '𝖋', '𝖌', '𝖍', '𝖎', '𝖏', '𝖐', '𝖑', '𝖒',
            '𝖓', '𝖔', '𝖕', '𝖖', '𝖗', '𝖘', '𝖙', '𝖚', '𝖛', '𝖜', '𝖝', '𝖞', '𝖟',
            '𝘈', '𝘉', '𝘊', '𝘋', '𝘌', '𝘍', '𝘎', '𝘏', '𝘐', '𝘑', '𝘒', '𝘓', '𝘔',
            '𝘕', '𝘖', '𝘗', '𝘘', '𝘙', '𝘚', '𝘛', '𝘜', '𝘝', '𝘞', '𝘟', '𝘠', '𝘡',
            '𝘢', '𝘣', '𝘤', '𝘥', '𝘦', '𝘧', '𝘨', '𝘩', '𝘪', '𝘫', '𝘬', '𝘭', '𝘮',
            '𝘯', '𝘰', '𝘱', '𝘲', '𝘳', '𝘴', '𝘵', '𝘶', '𝘷', '𝘸', '𝘹', '𝘺', '𝘻',
            '𝙰', '𝙱', '𝙲', '𝙳', '𝙴', '𝙵', '𝙶', '𝙷', '𝙸', '𝙹', '𝙺', '𝙻', '𝙼',
            '𝙽', '𝙾', '𝙿', '𝚀', '𝚁', '𝚂', '𝚃', '𝚄', '𝚅', '𝚆', '𝚇', '𝚈', '𝚉',
            '𝚊', '𝚋', '𝚌', '𝚍', '𝚎', '𝚏', '𝚐', '𝚑', '𝚒', '𝚓', '𝚔', '𝚕', '𝚖',
            '𝚗', '𝚘', '𝚙', '𝚚', '𝚛', '𝚜', '𝚝', '𝚞', '𝚟', '𝚠', '𝚡', '𝚢', '𝚣'
        ];

        // 希望替换成的普通拉丁字符
        $latin_chars = array_merge(
            range('A', 'Z'), range('a', 'z'),
            range('A', 'Z'), range('a', 'z'),
            range('A', 'Z'), range('a', 'z'),
            range('A', 'Z'), range('a', 'z'),
            range('A', 'Z'), range('a', 'z'),
            range('A', 'Z'), range('a', 'z'),
            range('A', 'Z'), range('a', 'z'),
            range('A', 'Z'), range('a', 'z'),
            range('A', 'Z'), range('a', 'z'),
            range('A', 'Z'), range('a', 'z'),
            range('A', 'Z'), range('a', 'z')
        );
        return str_replace($math_chars, $latin_chars, $str);
    }

    public static function filterNickName( $nickname ) {
        $nickname = urldecode( urldecode( $nickname ) );
        $nickname = str_replace( "\\'s", '', $nickname );
        $nickname = str_replace( "\\'", '', $nickname );
        $nickname = str_replace( '\"s', '', $nickname );
        $nickname = str_replace( '\"', '', $nickname );
        $nickname = str_replace( '\\n', '', $nickname );
        $nickname = str_replace( '"', '', $nickname );
        $nickname = str_replace( "'", '', $nickname );
        $nickname = str_replace( "|", '', $nickname );
        $nickname = str_replace( '|', '', $nickname );

        $nickname = Util::filterSpecialChar( $nickname );
        $nickname = Util::killBadChar( $nickname );
        $nickname = Util::filterEmoji( $nickname );
        return trim( $nickname );
    }


    public static function getMobile() {
        $ua = @$_SERVER['HTTP_USER_AGENT'];
        if ( !$ua )
            return false;

        $data = array();
        $ua = strtolower( $ua );
        $android = strstr( $ua, 'android' );
        $data['android'] = $android !== false;

        //$wphone = strstr($ua, 'phone');
        //$data['wphone'] = $wphone !== false;

        $ipad = strstr( $ua, 'ipad' );
        $data['ipad'] = $ipad !== false;

        $iphone = strstr( $ua, 'iphone' );
        $data['iphone'] = $data['ipad'] ? false : $iphone !== false;

        Util::SmallLog( 'ua', $ua );

        return $data;
    }

    public static function jsonp( $data, $callback = 'callback' ) {
        @header( 'Content-Type: application/json' );
        @header( "Expires:-1" );
        @header( "Cache-Control:no-cache" );
        @header( "Pragma:no-cache" );
        if ( isset( $_REQUEST[$callback] ) ) {
            header( "Access-Control-Allow-Origin:*" );
            echo $_REQUEST[$callback] . '(' . json_encode( $data, JSON_UNESCAPED_UNICODE ) . ')';
        } else echo json_encode( $data, JSON_UNESCAPED_UNICODE );
        exit;
    }



    public static function randOrderID() {
        return date( 'YmdHis' ) . rand( 10000, 99999 );
    }


    public static function isMobile() {
        $userAgent = @$_SERVER['HTTP_USER_AGENT'] ?: '';
        if ( !$userAgent )
            return false;
        $result = ( preg_match( '/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino|ipad/i', $userAgent ) || preg_match( '/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i', substr( $userAgent, 0, 4 ) ) );
        return $result ? 1 : 0;
    }


    public static function p3p() {
        header( 'P3P: CP="CAO DSP COR CUR ADM DEV TAI PSA PSD IVAi IVDi CONi TELo OTPi OUR DELi SAMi OTRi UNRi PUBi IND PHY ONL UNI PUR FIN COM NAV INT DEM CNT STA POL HEA PRE GOV"' );
    }

    public static function fbredirect( $url ) {
        echo "<script type=\"text/javascript\">\ntop.location.href = \"$url\";\n</script>";
        exit;
    }

    public static function getNowUrl() {
        $nowurl = $_SERVER['REQUEST_URI'] ? $_SERVER['REQUEST_URI'] : ( $_SERVER['PHP_SELF'] ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME'] );
        $nowurl = ROOTURL . $nowurl;
        return $nowurl;
    }

    public static function killBadChar( $str ) {
        preg_match_all( '/[0-9a-zA-Z \x{4e00}-\x{9fff}]+/u', $str, $matches );
        $str = join( '', $matches[0] );
        return trim( $str );
    }


    public static function der2pem( $der_data ) {
        $pem = chunk_split( $der_data, 64, "\n" );
        $pem = "-----BEGIN PUBLIC KEY-----\n" . $pem . "-----END PUBLIC KEY-----\n";
        return $pem;
    }

    public static function appleValidateReceipt( $receipt, $isSandbox = true ) {
        $endpoint = $isSandbox ? 'https://sandbox.itunes.apple.com/verifyReceipt' : 'https://buy.itunes.apple.com/verifyReceipt';
        $postData = json_encode( array( 'receipt-data' => $receipt ) );

        $ch = curl_init( $endpoint );
        curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, 0 );
        curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, 0 );
        curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
        curl_setopt( $ch, CURLOPT_POST, true );
        curl_setopt( $ch, CURLOPT_POSTFIELDS, $postData );

        $response = curl_exec( $ch );
        $errno = curl_errno( $ch );
        $errmsg = curl_error( $ch );
        curl_close( $ch );

        if ( $errno != 0 )
            throw new Exception ( $errmsg, $errno );
        $data = json_decode( $response, true );
        if ( !is_array( $data ) )
            throw new Exception ( 'Invalid response data' );

        if ( !isset( $data ['status'] ) || $data['status'] != 0 ) {
            if ( !empty( $data['status'] ) && $data['status'] == "21007" && !$isSandbox )
                return Util::appleValidateReceipt( $receipt, true );
            Util::WriteLog( 'appstore_err', 'appleValidateReceipt error!' . $endpoint );
            Util::SmallLog( 'appstore_err', $data );
            throw new Exception ( 'Invalid receipt' );
        }

        return $data ['receipt'];
    }


    public static function encode36( $num ) {
        $str = "";
        $typelen = 36;
        $k = str_split( "ABCDEFGHIJKLMN123456789OPQRSTUVWXYZ0", 1 );
        $num += 10000000;
        while ( $num > 0 ) {
            $char = $num % $typelen;
            $str = $k [$char] . $str;
            $num = ( $num - $char ) / $typelen;
        }
        return $str;
    }

    public static function decode36( $str ) {
        $str = strtoupper( $str );
        $typelen = 36;
        $k = "ABCDEFGHIJKLMN123456789OPQRSTUVWXYZ0";
        $num = 0;
        for ( $i = 0; $i < strlen( $str ); ++$i ) {
            $num = $num * $typelen + strpos( $k, substr( $str, $i, 1 ) );
        }
        return $num -= 10000000;
    }


    public static function validate_email( $email ) {
        if ( !preg_match( '/([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)/', $email ) )
            unset( $email );
        return @$email;
    }

    public static function objectToArray($object)
    {
        // 处理stdClass对象
        if ($object instanceof \stdClass) {
            $object = (array) $object;
        }

        // 处理数组
        if (is_array($object)) {
            foreach ($object as $key => $value) {
                $object[$key] = self::objectToArray($value);
            }
        }

        return $object;
    }

    //object to array
    public static function getKeyValue( $obj, $key, $delKey = true ) {
        $list = array();
        foreach ( $obj as $info ) {
            $info = get_object_vars( $info );
            $id = $info[$key];
            if ( $delKey )
                unset( $info[$key] );
            $list[$id] = $info;
        }
        return $list;
    }

    //is utf8
    public static function is_utf8( $string ) {
        return preg_match( '%^(?:
		 [\x09\x0A\x0D\x20-\x7E]			# ASCII
	   | [\xC2-\xDF][\x80-\xBF]			# non-overlong 2-byte
	   |  \xE0[\xA0-\xBF][\x80-\xBF]		# excluding overlongs
	   | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}  # straight 3-byte
	   |  \xED[\x80-\x9F][\x80-\xBF]		# excluding surrogates
	   |  \xF0[\x90-\xBF][\x80-\xBF]{2}	# planes 1-3
	   | [\xF1-\xF3][\x80-\xBF]{3}		  # planes 4-15
	   |  \xF4[\x80-\x8F][\x80-\xBF]{2}	# plane 16
   )*$%xs', $string );
    }

    //安全encode
    public static function safeEncoding( $string, $outEncoding = 'UTF-8' ) {
        $string = Util::safeEncoding3( $string );

        if ( Util::is_utf8( $string ) )
            return $string;

        $encoding = "UTF-8";
        $encoding = mb_detect_encoding( $string, array( 'ASCII', 'GB2312', 'CP936', 'BIG5' ) );

        if ( strtoupper( $encoding ) == strtoupper( $outEncoding ) ) {
            return $string;
        } else {
            return mb_convert_encoding( $string, $outEncoding, $encoding );
        }
    }

    //安全encode
    public static function safeEncoding3( $string, $outEncoding = 'UTF-8' ) {
        $encoding = "UTF-8";
        for ( $i = 0; $i < strlen( $string ); $i++ ) {
            if ( ord( $string[$i] ) < 128 )
                continue;

            if ( ( ord( $string[$i] ) & 224 ) == 224 ) {
                //第一个字节判断通过
                $char = $string[++$i];
                if ( ( ord( $char ) & 128 ) == 128 ) {
                    //第二个字节判断通过
                    $char = $string[++$i];
                    if ( ( ord( $char ) & 128 ) == 128 ) {
                        $encoding = "UTF-8";
                        break;
                    }
                }
            }
            if ( ( ord( $string[$i] ) & 192 ) == 192 ) {
                //第一个字节判断通过
                $char = $string[++$i];
                if ( ( ord( $char ) & 128 ) == 128 ) {
                    // 第二个字节判断通过
                    $encoding = "GB2312";
                    break;
                }
            }
        }

        if ( strtoupper( $encoding ) == strtoupper( $outEncoding ) )
            return $string;
        else
            return mb_convert_encoding( $string, $outEncoding, $encoding );
        return iconv( $encoding, $outEncoding, $string );
    }

    //取浏览器语言
    public static function determineLang() {
        $lang = substr( @$_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 5 ); //只取前4位，这样只判断最优先的语言。如果取前5位，可能出现en,zh的情况，影响判断。
        if ( preg_match( "/zh/i", $lang ) )
            return "zh_CN";
        else return 'en_US';
    }

    //过滤语言
    public static function getLocale( $lang ) {
        $locale = '';
        $shortLangEN = array( 'en', 'US', 'UK', "en_US", 'en_UK', 'en_GB', 'en_us' );
        $shortLangTW = array( 'zh', 'TW', 'HK', "zh_TW", 'zh_HK', "jp", 'ja_JP', 'ko_KR', "th", "TH", 'th_TH', 'zh_tw' );
        $shortLangCN = array( 'zh_CN', 'CN', 'zh_cn' );
        if ( in_array( $lang, $shortLangEN ) ) {
            $locale = "en_us";
        } else if ( in_array( $lang, $shortLangTW ) ) {
            $locale = "zh_tw";
        } else if ( in_array( $lang, $shortLangCN ) ) {
            $locale = "zh_cn";
        } else {
            $locale = "en_us";
        }
        return $locale;
    }

    //urlencode
    public static function encode_url_substr_UTF8( $str, $lenlimit ) {
        $mblen = mb_strlen( $str, "UTF8" );
        $realencodelen = 0;
        $outstr = '';
        for ( $i = 0; $i < $mblen; $i++ ) {
            $char = mb_substr( $str, $i, 1, 'UTF8' );
            if ( strlen( $char ) > 1 ) {
                $addlen = strlen( $char ) * 3;
            } else {
                $addlen = 1;
            }
            if ( $realencodelen + $addlen < $lenlimit ) {
                $outstr .= $char;
                $realencodelen += $addlen;
            }
        }
        return $outstr;
    }

    //转意数据
    public static function saddslashes( $string ) {
        if ( is_array( $string ) ) {
            foreach ( $string as $key => $val ) {
                $string[$key] = Util::saddslashes( $val );
            }
        } else {
            $string = addslashes( $string );
        }
        return $string;
    }

    //日志
    public static function WriteLog( $key, $data ) {
        $ymd = date( "Ymd" );
        $date = date( 'Y-m-d H:i:s' );
        $file = storage_path( 'logs' ) . "/{$ymd}_{$key}.log";
        $ip = IpLocation::getRealIp();
        $agent=@$_SERVER['HTTP_USER_AGENT']??"";
        $locale=@$_SERVER['HTTP_ACCEPT_LANGUAGE']??"";
        $ref = @$_SERVER['HTTP_REFERER'];
        $url = @$_SERVER['REQUEST_URI'];
        $host = @$_SERVER['HTTP_HOST'];

        if ( !is_string( $data ) )
            $data = json_encode( $data, JSON_UNESCAPED_UNICODE );
        $uid = isset( $GLOBALS['user_id'] ) ? $GLOBALS['user_id'] : 0;

//        $params = array( 'POST' => $_POST );
        $params = empty( $_REQUEST ) ? '' : json_encode( $_REQUEST, JSON_UNESCAPED_UNICODE );

        $content = "date: {$date}\n";
        $content .= "ip: {$ip}({$uid})   agent:".$agent."   locale:".$locale."\n";
        if ( !empty( $ref ) )
            $content .= "referer: {$ref}\n";
        if ( !empty( $url ) )
            $content .= "request: {$host}{$url}\n";
        if ( !empty( $params ) )
            $content .= "params: {$params}\n";
        if ( !empty( $data ) )
            $content .= "content: {$data}\n";
        $content .= "\n";
        try {
            error_log($content, 3, $file);
        }catch ( \Exception $e ) {
            error_log($e->getMessage(), 3, storage_path( 'logs' ) . "/util_error.log");
            error_log($content, 3, storage_path( 'logs' ) . "/util_error.log");
        }
    }

    //写简单日志
    public static function SmallLog( $key, $content ) {
        $ymd = date( "Ymd" );
        $date = date( 'Y-m-d H:i:s' );
        $file = storage_path( 'logs' ) . "/{$ymd}_{$key}.log";
        $ip = IpLocation::getIP();

        if ( !is_string( $content ) )
            $content = json_encode( $content, JSON_UNESCAPED_UNICODE );
        $uid = isset( $GLOBALS['user_id'] ) ? $GLOBALS['user_id'] : 0;
        $content = "date:{$date}\tip:{$ip}({$uid})\tcontent:{$content}\n";

        error_log( $content, 3, $file );
    }

    public static function SmallLog2( $key, $content ) {
        $ymd = date( "Ymd" );
        $date = date( 'Y-m-d H:i:s' );
        $file = storage_path( 'logs' ) . "/{$ymd}_{$key}.log";

        if ( !is_string( $content ) )
            $content = json_encode( $content, JSON_UNESCAPED_UNICODE );
        $content = "date:{$date}\t {$content}\n";

        error_log( $content, 3, $file );
    }

    //验证昵称
    public static function check_nickname( $username, $isNick = false ) {
        $guestexp = '\xA1\xA1|\xAC\xA3|^Guest|^\xD3\xCE\xBF\xCD|\xB9\x43\xAB\xC8';
        $len = strlen( $username );
        if ( $len > 20 || $len < 1 || preg_match( "/^c:\\con\\con|[%,\|\*\"\<\>\&\`\']|$guestexp/is", $username ) ) {
            return FALSE;
        } else if ( preg_match( '/^(?!_|\s\')[A-Za-z0-9_\x80-\xff\s\']+$/', $username ) ) {
            return TRUE;
        }

        return FALSE;
    }

    //验证用户名
    public static function check_username( $username ) {
        $guestexp = '\xA1\xA1|\xAC\xA3|^Guest|^\xD3\xCE\xBF\xCD|\xB9\x43\xAB\xC8';
        $len = strlen( $username );
        if ( $len > 20 || $len < 3 || preg_match( "/\s+|^c:\\con\\con|[%,\|\*\"\s\<\>\&]|$guestexp/is", $username ) || !preg_match( "/^[0-9@A-Z_a-z]*$/", $username ) ) {
            return FALSE;
        } else if ( strstr( ' ', $username ) ) {
            return FALSE;
        } else {
            return TRUE;
        }
    }

    //发送手机验证码
    public static function sendSMS($phone, $text) {
        $ch = curl_init();
        $post_data = array(
            "account" => SMSAccount,
            "password" => SMSPassword,
            "destmobile" => $phone,
            "msgText" => $text,
            "sendDateTime" => ""
        );
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch,CURLOPT_BINARYTRANSFER,true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $post_data = http_build_query($post_data);
        curl_setopt($ch, CURLOPT_POSTFIELDS,$post_data);
        curl_setopt($ch, CURLOPT_URL, 'http://www.jianzhou.sh.cn/JianzhouSMSWSServer/http/sendBatchMessage');
        $reponse = curl_exec($ch);
        curl_close($ch);
        return $reponse;
    }

    public static function validate_mobile($mobile) {
        if (!is_bool(strpos($mobile, '+'))) return false;
        if (!is_bool(strpos($mobile, ' '))) return false;
        if (!is_bool(strpos($mobile, '('))) return false;
        return is_numeric($mobile) && strlen($mobile) == 11;
    }

    //验证email
    public static function check_emailformat( $email ) {
        return strlen( $email ) > 6 && preg_match( '/^[\w\-\.]+@[\w\-\.]+(\.\w+)+$/', $email );
    }

    //curl
    public static function curl( $url, $timeout = 0 ) {
        if ( !strstr( $url, 'http' ) ) {
            return '';
        }
        $ch = curl_init();
        curl_setopt( $ch, CURLOPT_URL, $url );
        curl_setopt( $ch, CURLOPT_FAILONERROR, false );
        curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );

        if ( $timeout > 0 ) {
            curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, $timeout );
            curl_setopt( $ch, CURLOPT_TIMEOUT, $timeout );
        }

        if ( strlen( $url ) > 5 && strtolower( substr( $url, 0, 5 ) ) == "https" ) {
            curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false );
            curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, false );
        }

        $reponse = curl_exec( $ch );

        if ( curl_errno( $ch ) ) {
            throw new Exception( curl_error( $ch ), 0 );
        } else {
            $httpStatusCode = curl_getinfo( $ch, CURLINFO_HTTP_CODE );
            if ( 200 !== $httpStatusCode ) {
                throw new Exception( $reponse, $httpStatusCode );
            }
        }
        curl_close( $ch );
        return $reponse;
    }

    //生成密码
    public static function password( $user_password, $user_salt ) {
        return md5( md5( $user_password ) . strval( $user_salt ) );
    }

    //生成sessionKey
    public static function makePkey( $uid, $timestamp, $locale, $ismobile = 0, $gss = 0, $appID = 1, $bundleid = '' ) {
        $pkey = array( 'u' => $uid, 't' => $timestamp, 'l' => $locale, 'm' => $ismobile, 'g' => $gss, 'a' => $appID, 'b' => $bundleid );
        $pkey = Util::up_encode( $pkey );
        return $pkey;
    }

    //加密
    public static function up_encode( $str ) {
        if ( is_array( $str ) || is_object( $str ) )
            $str = json_encode( $str );
        $cr = new Crypt3Des ( Crypt3DesKey, Crypt3DesIV );
        $str = $cr->encrypt( $str );
        $str = str_replace( '+', '-', $str );
        $str = str_replace( '/', '.', $str );
        $str = str_replace( '=', '!', $str );
        return $str;
    }

    //解密
    public static function up_decode( $str ) {
        if ( !$str )
            return $str;
        $str = urldecode( $str );
        $str = trim( $str );
        $cr = new Crypt3Des ( Crypt3DesKey, Crypt3DesIV );
        $str = str_replace( '-', '+', $str );
        $str = str_replace( '.', '/', $str );
        $str = str_replace( '!', '=', $str );
        $str = $cr->decrypt( $str );
        $couldbeA = json_decode( $str, true );
        if ( is_array( $couldbeA ) )
            return $couldbeA;
        return false;
    }

    public static function getCDNFile( $file ) {
        if ( Util::startsWith( $file, 'client/' ) )
            return CDNSERVER . $file;
        if ( Util::startsWith( $file, 'upload/' ) )
            return CDNRESOURCE . $file;
        if ( Util::startsWith( $file, 'images/' ) )
            return CDNRESOURCE . $file;
        return CDNSERVER . $file;
    }

    public static function getTaobaoData( $ip ) {
        try {
            $data = self::curl( "http://ip.taobao.com/service/getIpInfo.php?ip=$ip", 2 );
        } catch ( Exception $e ) {
            $data = null;
        }

        if ( !empty( $data ) && Util::startsWith( $data, '{' ) ) {
            $data = json_decode( $data, true );
            if ( $data['code'] == 0 ) {
                $city = array( 'country' => @$data['data']['country'], 'region' => @$data['data']['region'], 'city' => @$data['data']['city'], 'county' => @$data['data']['county'], 'source' => 'taobao' );
                return $city;
            }
        }
        return false;
    }

    public static function getTaobaoData2( $ip ) {
        try {
            $data = self::curl( "http://ip.taobao.com/service/getIpInfo2.php?ip=$ip", 2 );
        } catch ( Exception $e ) {
            $data = null;
        }

        if ( !empty( $data ) && Util::startsWith( $data, '{' ) ) {
            $data = json_decode( $data, true );
            if ( $data['code'] == 0 ) {
                $city = array( 'country' => @$data['data']['country'], 'region' => @$data['data']['region'], 'city' => @$data['data']['city'], 'county' => @$data['data']['county'], 'source' => 'taobao2' );
                return $city;
            }
        }
        return false;

    }

    public static function getBaiduData( $ip ) {
        try {
            $data = self::curl( "http://api.map.baidu.com/location/ip?ak=F454f8a5efe5e577997931cc01de3974&ip=$ip", 2 );
        } catch ( Exception $e ) {
            $data = null;
        }

        if ( !empty( $data ) && Util::startsWith( $data, '{' ) ) {
            $data = json_decode( $data, true );
            if ( !empty( $data['content']['address_detail'] ) ) {
                $data = $data['content']['address_detail'];
                $city = array( 'country' => '', 'region' => @$data['province'], 'city' => @$data['city'], 'county' => @$data['district'], 'source' => 'baidu' );
                return $city;
            }
        }
        return false;
    }

    public static function getSinaData( $ip ) {
        try {
            $data = self::curl( "http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip=$ip", 2 );
        } catch ( Exception $e ) {
            $data = null;
        }

        if ( !empty( $data ) ) {
            $data = str_replace( 'var remote_ip_info = {', '{', $data );
            $data = str_replace( '};', '}', $data );
        }
        if ( !empty( $data ) && Util::startsWith( $data, '{' ) ) {
            $data = json_decode( $data, true );
            if ( $data && $data['ret'] == 1 ) {
                $city = array( 'country' => @$data['country'], 'region' => @$data['province'], 'city' => @$data['city'], 'county' => @$data['district'], 'source' => 'sina' );
                return $city;
            }
        }
        return false;
    }

    public static function getIpipData( $ip ) {
        try {
            $data = self::curl( "http://freeapi.ipip.net/$ip", 2 );
        } catch ( Exception $e ) {
            $data = null;
        }

        if ( !empty( $data ) && Util::startsWith( $data, '[' ) ) {
            $data = json_decode( $data, true );
            if ( $data ) {
                $city = array( 'country' => @$data[0], 'region' => @$data[1], 'city' => @$data[2], 'county' => @$data[3], 'source' => 'ipip' );
                return $city;
            }
        }
        return false;
    }

    public static function randIp2Address( $ip ) {
        $rand = rand( 1, 3 );
        switch ( $rand ) {
            case 1:
                return self::getTaobaoData( $ip );
            case 2:
                return self::getTaobaoData2( $ip );
            case 3:
                return self::getBaiduData( $ip );
        }
        return self::getTaobaoData( $ip );
    }

    public static function getIp2Address( $ip ) {
        $city = self::randIp2Address( $ip );
        if ( empty( $city ) )
            $city = self::getBaiduData( $ip );
        if ( empty( $city ) )
            $city = self::getTaobaoData( $ip );
        if ( empty( $city ) )
            $city = self::getTaobaoData2( $ip );
        if ( empty( $city ) )
            $city = self::getSinaData( $ip );
        if ( empty( $city ) )
            $city = self::getIpipData( $ip );
        return $city;
    }

    public static function getIp2AddressFullName( $ip ) {
        $city = Util::getIp2Address( $ip );
        if ( empty( $city['region'] ) )
            return '';

        $data = array();
        $data['province'] = $city['region'];
        $data['city'] = $city['city'];
        $data['area'] = $city['county'];
        if ( !empty( $city['region'] ) && !empty( $city['city'] ) && !empty( $city['county'] ) && !empty( $city['country'] ) )
            $data['city'] = $city['country'];
        if ( !empty( $city['city'] ) && !empty( $city['county'] ) && !empty( $city['region'] ) )
            $data['city'] = $city['region'];

        if ( $data['province'] == $data['city'] && $data['city'] == $data['area'] )
            return trim( $data['province'] );
        if ( $data['province'] == $data['city'] )
            return trim( $data['city'] . ' ' . $data['area'] );
        return trim( $data['province'] . ' ' . $data['city'] . ' ' . $data['area'] );
    }


    public static function imageResize( $src_file, $dst_file, $new_width = 798, $new_height = 450, $opType = 1, $quality = 90 ) {
        ini_set( 'memory_limit', '1024M' );
        // 图像类型
        //        $type = exif_imagetype( $src_file );
        list( $objWidth, $objHeight, $type ) = getimagesize( $src_file );
        $support_type = array( IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_GIF, IMAGETYPE_BMP );
        if ( !in_array( $type, $support_type, true ) ) {
            return false;
        }
        //Load image
        switch ( $type ) {
            case IMAGETYPE_JPEG :
                $src_img = imagecreatefromjpeg( $src_file );
                break;
            case IMAGETYPE_PNG :
                $src_img = imagecreatefrompng( $src_file );
                break;
            case IMAGETYPE_GIF :
                $src_img = imagecreatefromgif( $src_file );
                break;
            default:
                $src_img = imagecreatefromjpeg( $src_file );
                break;
        }
        $w = imagesx( $src_img );
        $h = imagesy( $src_img );

        if ( $new_width / $w > $new_height / $h ) {
            $opType = 1;
        } else {
            $opType = 2;
        }

        //固定高度，宽度自适应
        if ( $opType == 1 ) {
            $new_width = $new_height * $w / $h;
        }
        if ( $opType == 2 ) {
            //固定宽度，高度自适应
            $new_height = $new_width * $h / $w;
        }
        //TODO 根据高宽比自适应调节
        $ratio_w = 1.0 * $new_width / $w;
        $ratio_h = 1.0 * $new_height / $h;
        $ratio = 1.0;
        // 生成的图像的高宽比原来的都小，或都大 ，原则是 取大比例放大，取大比例缩小（缩小的比例就比较小了）
        //原图比较小不处理
        if ( $ratio_w > 1 && $ratio_h > 1 ) {
            $inter_img = imagecreatetruecolor( $w, $h );
            imagecopy( $inter_img, $src_img, 0, 0, 0, 0, $w, $h );
            // 生成一个以最大边长度为大小的是目标图像$ratio比例的临时图像
            // 定义一个新的图像
            $new_img = imagecreatetruecolor( $w, $h );
            imagecopyresampled( $new_img, $inter_img, 0, 0, 0, 0, $w, $h, $w, $h );
        } elseif ( $ratio_w < 1 && $ratio_h < 1 ) {
            if ( $ratio_w < $ratio_h ) {
                $ratio = $ratio_h; // 情况一，宽度的比例比高度方向的小，按照高度的比例标准来裁剪或放大
            } else {
                $ratio = $ratio_w;
            }
            // 定义一个中间的临时图像，该图像的宽高比 正好满足目标要求
            $inter_w = (int)( $new_width / $ratio );
            $inter_h = (int)( $new_height / $ratio );
            $inter_img = imagecreatetruecolor( $inter_w, $inter_h );
            imagecopy( $inter_img, $src_img, 0, 0, 0, 0, $inter_w, $inter_h );
            // 生成一个以最大边长度为大小的是目标图像$ratio比例的临时图像
            // 定义一个新的图像
            $new_img = imagecreatetruecolor( $new_width, $new_height );
            imagecopyresampled( $new_img, $inter_img, 0, 0, 0, 0, $new_width, $new_height, $inter_w, $inter_h );
        } else {
            // 2 目标图像 的一个边大于原图，一个边小于原图 ，先放大平普图像，然后裁剪
            $ratio = $ratio_h > $ratio_w ? $ratio_h : $ratio_w; //取比例大的那个值
            // 定义一个中间的大图像，该图像的高或宽和目标图像相等，然后对原图放大
            $inter_w = (int)( $w * $ratio );
            $inter_h = (int)( $h * $ratio );
            $inter_img = imagecreatetruecolor( $inter_w, $inter_h );
            //将原图缩放比例后裁剪
            imagecopyresampled( $inter_img, $src_img, 0, 0, 0, 0, $inter_w, $inter_h, $w, $h );
            // 定义一个新的图像
            $new_img = imagecreatetruecolor( $new_width, $new_height );
            imagecopy( $new_img, $inter_img, 0, 0, 0, 0, $new_width, $new_height );
        }
        switch ( $type ) {
            case IMAGETYPE_JPEG :
                imagejpeg( $new_img, $dst_file, $quality ); // 存储图像
                break;
            case IMAGETYPE_PNG :
                imagejpeg( $new_img, $dst_file, $quality );
                break;
            default:
                imagejpeg( $new_img, $dst_file, $quality );
                break;
        }
        return $dst_file;
    }


    public static function chargeTel( $tel, $money = 10, $key, $openid, $orderId ) {
        $sign = md5( $openid . $key . $tel . $money . $orderId );
        $api = "http://op.juhe.cn/ofpay/mobile/onlineorder?key=$key&phoneno=$tel&cardnum=$money&orderid=$orderId&sign=$sign";
        $data = file_get_contents( $api );
        return json_decode( $data, true );
    }


    //POST请求
    public static function curlPost($url, $data = null) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }
    public static function curlPost2($url, $data, $post = true, $header = array()) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        if ($post) {
            if ($header) {
                curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
            }
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
            curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        }
        curl_setopt($ch, CURLOPT_TIMEOUT,30);   //超时
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($ch);
        curl_close($ch);
        return $response;
    }

    public static function list_to_tree($list, $pk='id',$pid = 'parent_id',$child = '_child',$root=0) {
        $tree = array();
        if(is_array($list)) {
            $refer = array();
            foreach ($list as $key => $data) {
                $refer[$data[$pk]] =& $list[$key];
            }

            foreach ($list as $key => $data) {
                $parentId = $data[$pid];
                if ($root == $parentId) {
                    $tree[] =& $list[$key];
                }else{
                    if (isset($refer[$parentId])) {
                        $parent =& $refer[$parentId];
                        $parent[$child][] =& $list[$key];
                    }
                }
            }
        }

        return $tree;
    }


     public static function getGameType ($tid) {
        switch($tid) {

            case 1: return '拼罗松轮状('.$tid.')';
            case 2: return '拼罗松通比('.$tid.')';
            case 3: return '拼罗松黑桃A坐庄('.$tid.')';
            case 50: return '斗牛经典抢庄('.$tid.')';
            case 51: return '斗牛经典轮庄('.$tid.')';
            case 52: return '斗牛经典定庄('.$tid.')';
            case 53: return '斗牛经典焖牌('.$tid.')';
            case 54: return '斗牛经典通比('.$tid.')';
            case 55: return '斗牛疯狂抢庄('.$tid.')';
            case 56: return '斗牛疯狂轮庄('.$tid.')';
            case 57: return '斗牛疯狂定庄('.$tid.')';
            case 58: return '斗牛疯狂焖牌('.$tid.')';
            case 59: return '斗牛疯狂通比('.$tid.')';
            case 60: return '斗牛随机庄家('.$tid.')';
            case 70: return '经典拼罗松('.$tid.')';
            case 68: return '扎金花('.$tid.')';
            case 81: return '嵊州十三水轮庄('.$tid.')';
            case 82: return '嵊州十三水通比('.$tid.')';
            case 100: return '﻿清墩('.$tid.')';

        }
        return $tid;
    }
    public static function postXmlCurl( $url, $xml, $cert, $key, $ca ) {
        $ch = curl_init();
        //设置超时
        curl_setopt( $ch, CURLOPT_TIMEOUT, 30 );

        curl_setopt( $ch, CURLOPT_URL, $url );
        curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false );
        curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, false );//严格校验
        curl_setopt( $ch, CURLOPT_SSLCERT, $cert );//加入证书
        curl_setopt( $ch, CURLOPT_SSLKEY, $key );//加入证书
        curl_setopt( $ch, CURLOPT_CAINFO, $ca );//加入证书
        //设置header
        curl_setopt( $ch, CURLOPT_HEADER, FALSE );
        //要求结果为字符串且输出到屏幕上
        curl_setopt( $ch, CURLOPT_RETURNTRANSFER, TRUE );

        //post提交方式
        curl_setopt( $ch, CURLOPT_POST, TRUE );
        curl_setopt( $ch, CURLOPT_POSTFIELDS, $xml );
        //运行curl
        $data = curl_exec( $ch );

        //返回结果
        if ( $data ) {
            curl_close( $ch );
            return self::xmlToArr( $data );
        } else {
            $error = curl_error( $ch );
            curl_close( $ch );
            return $error;
        }
    }
    public static function getNonceStr( $length = 16 ) {
        $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
        $str = "";
        for ( $i = 0; $i < $length; $i++ ) {
            $str .= substr( $chars, mt_rand( 0, strlen( $chars ) - 1 ), 1 );
        }
        return $str;
    }

    public static function generateRandomString($length = 8) {
        // 扩展字符集合，包括小写字母、大写字母和数字
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $charactersLength = strlen($characters);
        $randomString = '';
        // 生成随机字符串
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[random_int(0, $charactersLength - 1)];
        }
        return $randomString;
    }

    /**
     * 生成sign
     * @param array $data
     * @param string $key
     * @return string
     */
    public static function getSign( $data, $skey ) {
        ksort( $data );
        $str = '';
        foreach ( $data as $key => $val ) {
            $str .= $str ? '&' . $key . '=' . $val : $key . '=' . $val;
        }
        $str .= '&key=' . $skey;
        $data['sign'] = strtoupper( md5( $str ) );
        return $data;
    }


    /**
     * 输出xml字符
     * @param array $data
     */
    public static function toXml( $data ) {
        $xml = "<xml>";
        foreach ( $data as $key => $val ) {
            if ( is_numeric( $val ) ) {
                $xml .= "<" . $key . ">" . $val . "</" . $key . ">";
            } else {
                $xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
            }
        }
        $xml .= "</xml>";
        return $xml;
    }

    public static function getUnixTimestampMillis() {
        // Get the current time in seconds and microseconds
        $microtime = microtime(true);

        // Convert to milliseconds
        $millis = $microtime * 1000;

        // Return as an integer (to remove decimal points)
        return (int)$millis;
    }


}
