<?php
use think\Controller;
use think\Db;
//模块公共函数

    function md5_sign($data, $key)
    {
        ksort($data);
        $str1 = '';
        foreach ($data as $k => $v) {
            $str1 .= '&' . $k . "=" . $v;
        }
        $sign = md5(trim($str1) . $key);
        return $sign;
    }
    
    function async_get_url($url_array, $wait_usec = 0)
    {
      if (!is_array($url_array))
      return false;
      $wait_usec = intval($wait_usec);
      $data  = array();
      $handle = array();
      $running = 0;
      $mh = curl_multi_init(); //multi curl handler
      $i = 0;
      foreach($url_array as $url) {
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // return don't print
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // 302 redirect
        curl_setopt($ch, CURLOPT_MAXREDIRS, 7);
        curl_multi_add_handle($mh, $ch); // 把 curl resource 放进 multi curl handler 里
        $handle[$i++] = $ch;
      }
      /* 执行 */
      do {
        curl_multi_exec($mh, $running);
        if ($wait_usec > 0) /* 每个 connect 要间隔多久 */
          usleep($wait_usec); // 250000 = 0.25 sec
      } while ($running > 0);
      /* 读取资料 */
      foreach($handle as $i => $ch) {
        $content = curl_multi_getcontent($ch);
        $data[$i] = (curl_errno($ch) == 0) ? $content : false;
      }
      /* 移除 handle*/
      foreach($handle as $ch) {
        curl_multi_remove_handle($mh, $ch);
      }
      curl_multi_close($mh);
      return $data;
    }
    
    //检测密码长度
    function ispwd($pwd){
            $length = mb_strlen($pwd,"utf-8");
            if ($length < 26 && $length >= 6){
                return true;
            }else{
                return false;
            }
    }
    
    function config_set($key){
        $config_Set = Db::name('set')->where('key',$key)->find();
        return $config_Set;
    }
    
    //检测用户名
    function isuser($mobile){
            if(!preg_match("/^(?![^a-zA-Z]+$)(?!\D+$).{6,}$/",$mobile)){
               return false;
            }{
                return true;
            }
    }
    
    function is_weixin()
    {
        $ua = $_SERVER['HTTP_USER_AGENT'];
        if (strpos($ua, 'MicroMessenger') == false && strpos($ua, 'Windows Phone') == false) {
            return 1;
            //微信外
        } else {
            return 2;
            //微信
        }
    }
    
    function CheckSubstrs($substrs,$text){
            foreach($substrs as $substr)
                if(false!==strpos($text,$substr)){
                    return true;
            }
            return false;
    }
    
    //检测是否手机访问
    function isMobile(){
        $useragent=isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
        $useragent_commentsblock=preg_match('|\(.*?\)|',$useragent,$matches)>0?$matches[0]:'';
        
        $mobile_os_list=array('Google Wireless Transcoder','Windows CE','WindowsCE','Symbian','Android','armv6l','armv5','Mobile','CentOS','mowser','AvantGo','Opera Mobi','J2ME/MIDP','Smartphone','Go.Web','Palm','iPAQ');
        $mobile_token_list=array('Profile/MIDP','Configuration/CLDC-','160×160','176×220','240×240','240×320','320×240','UP.Browser','UP.Link','SymbianOS','PalmOS','PocketPC','SonyEricsson','Nokia','BlackBerry','Vodafone','BenQ','Novarra-Vision','Iris','NetFront','HTC_','Xda_','SAMSUNG-SGH','Wapaka','DoCoMo','iPhone','iPod');
        
        $found_mobile=CheckSubstrs($mobile_os_list,$useragent_commentsblock) ||
        CheckSubstrs($mobile_token_list,$useragent);
        
        if ($found_mobile){
            return true;
        }else{
            return false;
        }
    }
     //xss攻击过滤     
    function xss($val)
    {
         $val = preg_replace('/([\\x00-\\x08,\\x0b-\\x0c,\\x0e-\\x19])/', '', $val);
         $search = 'abcdefghijklmnopqrstuvwxyz';
         $search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
         $search .= '12     34567890!@#$%^&*()';
         $search .= '~`";:?+/={}[]-_|\'\\';
         for ($i = 0; $i < strlen($search); $i++) {
             $val = preg_replace('/(&#[xX]0{0,8}' . dechex(ord($search[$i])) . ';?)/i', $search[$i], $val);
             //
             $val = preg_replace('/(&#0{0,8}' . ord($search[$i]) . ';?)/', $search[$i], $val);
             //
         }
         $ra1 = array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'style', 'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound', 'title', 'base');
         $ra2 = array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterchange', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload');
         $ra = array_merge($ra1, $ra2);
         $found = true;
    //
         while ($found == true) {
             $val_before = $val;
             for ($i = 0; $i < sizeof($ra); $i++) {
                 $pattern = '/';
                 for ($j = 0; $j < strlen($ra[$i]); $j++) {
                     if ($j > 0) {
                         $pattern .= '(';
                    $pattern .= '(&#[xX]0{0,8}([9ab]);)';
                    $pattern .= '|';
                    $pattern .= '|(&#0{0,8}([9|10|13]);)';
                    $pattern .= ')*';
                }
                $pattern .= $ra[$i][$j];
            }
         $pattern .= '/i';
         $replacement = substr($ra[$i], 0, 2) . '<x>' . substr($ra[$i], 2);
            //
         $val = preg_replace($pattern, $replacement, $val);
            //
         if ($val_before == $val) {
                $found = false;
         }
         }
         }
         return $val;
        }
        
        
     
      function msgJson($type, $code, $msg){
            if ($type == 'json') {
                functions::json($code, $msg);
            } else {
                exit('<!DOCTYPE html>
        <html>
        <head>
            <meta charset="utf-8"/>
            <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
            <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
            <title>支付中心 - 6gym.com 6G源码 </title>
            <link rel="stylesheet" href="/static/assets/libs/layui/css/layui.css"/>
            <link rel="stylesheet" href="/static/assets/module/admin.css?v=318"/>
        </head>
        <body>
        <!-- 正文开始 -->
        <div class="error-page">
            <img class="error-page-img" src="/static/assets/images/ic_403.png">
            <div class="error-page-info">
                <h1>' . $code . '</h1>
                <p>' . $msg . '</p>
                
            </div>
        </div>
        <style>
            .error-page {
                position: absolute;
                top: 50%;
                width: 100%;
                text-align: center;
                -o-transform: translateY(-50%);
                -ms-transform: translateY(-50%);
                -moz-transform: translateY(-50%);
                -webkit-transform: translateY(-50%);
                transform: translateY(-50%);
            }
        
            .error-page .error-page-img {
                display: inline-block;
                height: 260px;
                margin: 10px 15px;
            }
        
            .error-page .error-page-info {
                vertical-align: middle;
                display: inline-block;
                margin: 10px 15px;
            }
        
            .error-page .error-page-info > h1 {
                color: #434e59;
                font-size: 58px;
                font-weight: 400;
            }
        
            .error-page .error-page-info > p {
                color: #777;
            font-size: 24px;
            margin-top: 5px;
        }
        
        .error-page .error-page-info > div {
                margin-top: 30px;
            }
        </style>
        </body>
        </html>');
            }
        }
        

        
        function getSubstr($str, $leftStr, $rightStr)
        {
            $left = strpos($str, $leftStr);
            //echo '左边:'.$left;
            $right = strpos($str, $rightStr, $left);
            //echo '<br>右边:'.$right;
            if ($left < 0 or $right < $left) {
                return '';
            }
            return substr($str, $left + strlen($leftStr), $right - $left - strlen($leftStr));
        }
        
        function dm_html($game_dm,$order_num,$sy_order,$refer,$type)
        {
            if ($game_dm == "alipay_dmf_pay" || $game_dm == "dy_db_pay") {
                $is_weixin = is_weixin();
                if ($is_weixin == 2) {
                    
                    echo '<!DOCTYPE html>
                             <html xmlns="http://www.w3.org/1999/xhtml" style="font-size: 100px;">
                             <head id="Head1"><meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
                             <title>温馨提示 - 6gym.com 6G源码 </title>
                                 <!--禁止全屏缩放-->
                                 <meta name="viewport" content="width=device-width,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no" />
                                 <!--不显示成手机号-->
                                 <meta name="format-detection" content="telephone=no" />
                                 <!--删除默认的苹果工具栏和菜单栏-->
                                 <meta name="apple-mobile-web-app-capable" content="yes" />
                                 <!--解决UC手机字体变大的问题-->
                                 <meta name="wap-font-scale" content="no" />
                                 <!--控制状态栏显示样式-->
                                 <meta name="apple-mobile-web-app-status-bar-style" content="black" />
                             	<link href="http://cdn.2014516.cn/index.css" rel="stylesheet" type="text/css" />
                                <script type="text/javascript" src="//cdn.bootcss.com/jquery/1.12.4/jquery.min.js"></script>
                                <script type="text/javascript" src="/static/public/pay/layer/layer.js"></script>
                                 <script type="text/javascript">
                             $(function ($) {
                                  setRootFontSize();
                             });
                             window.onresize = function () {
                                 setRootFontSize();
                             }
                             function setRootFontSize() {
                                 $(\'html\').css(\'font-size\', document.body.clientWidth / 15 + \'px\');
                             }
                                 </script>
                             </head>
                             <body style="background-color: #f5f5f5;">
                                 <div id="Pan_WX">
                                     <!--微信访问-->
                                     <div class="fc_jt">
                                         <img src="http://cdn.2014516.cn/jt.png"></div>
                                            <div class="fc_wz">
                                             点击屏幕右上角[...]<br />
                                             用 浏览器 打开 
                                         </div>  
                                       <div class="fc_tp">
                                         <img src="http://cdn.2014516.cn/wx_az.png"></div>
                             		</div>
                             </body>
                             </html>
                             <script>
                             //订单监控  {订单监控}
            function order(){
            	$.get("../pay/orders?num='.$order_num.'&syorder='.$sy_order.'", function(result){
            		//成功
            		if(result.code == "200"){
        				//回调页面
                		window.clearInterval(orderlst);
            			layer.confirm(result.msg, {
            			  icon: 1,
            			  title: "支付成功",
          				  btn: ["我知道了"] //按钮
          				}, function(){
          					location.href="'.$refer.'";
          				});
          				return false;
            		}
            		//订单被销毁
            		if(result.code == "1001"){
            			window.clearInterval(orderlst);
            			layer.confirm(result.msg, {
            			  icon: 2,
            			  title: "订单错误",
          				  btn: ["确认"] //按钮
          				}, function(){
          					location.href="'.$refer.'";
          				});
          				return false;
                	}
                	//订单已经超时
            		if(result.code == "1002"){
            			window.clearInterval(orderlst);
            			layer.confirm(result.msg, {
            			  icon: 2,
            			  title: "支付超时",
          				  btn: ["确认"] //按钮
          				}, function(){
          					location.href="'.$refer.'";
          				});
          				return false;
                	}
            	  });
             }
            //周期监听
            var orderlst = setInterval("order()",5000+Math.floor(Math.random()*10) );
            </script>';
            if($type==1){
              exit;  
            }
           }
            
            }
        }
        
        function json_msg($code,$msg,$data = null){
            header('Content-type: application/json');
            exit(json_encode(array("code"=>$code, "msg"=>$msg, "data"=>$data)));
        }

        function obj_array($array){
            if(is_object($array)){
            $array = (array)$array;
            }
           if(is_array($array)){
              foreach($array as $key=>$value){
                $array[$key] = obj_array($value);
              }
             }
           return $array;
        } 
        
         // RC4加密和解密  action 1加密 2解密
        function encode($data,$action=1){
                if ($action == 1){
                    return base64_encode(RC4('f5624bac9df1db7b9d6c8fabdb77706d', $data));
                }
                if ($action == 2){
                    return iconv("UTF-8", "GB2312//IGNORE", RC4('f5624bac9df1db7b9d6c8fabdb77706d', base64_decode($data)));
                }
        }
    
        //RC4加密
        function RC4 ($pwd, $data)
            {
                $key[] ="";
                $box[] ="";
                $cipher = "";
                $pwd_length = strlen($pwd);
                $data_length = strlen($data);
                
                for ($i = 0; $i < 256; $i++)
                {
                    $key[$i] = ord($pwd[$i % $pwd_length]);
                    $box[$i] = $i;
                }
                
                for ($j = $i = 0; $i < 256; $i++)
                {
                    $j = ($j + $box[$i] + $key[$i]) % 256;
                    $tmp = $box[$i];
                    $box[$i] = $box[$j];
                    $box[$j] = $tmp;
                }
                
                for ($a = $j = $i = 0; $i < $data_length; $i++)
                {
                    $a = ($a + 1) % 256;
                    $j = ($j + $box[$a]) % 256;
                    
                    $tmp = $box[$a];
                    $box[$a] = $box[$j];
                    $box[$j] = $tmp;
                    
                    $k = $box[(($box[$a] + $box[$j]) % 256)];
                    $cipher .= chr(ord($data[$i]) ^ $k);
                }
                
                return $cipher;
        }
        
        
        function api_request($orderId,$user){
        
             $order = Db::name('orders')->where('id',$orderId)->find();
             
             if (!$order) return false;
             //查询收款账号
             $land = Db::name('land')->where('id',$order['land_id'])->find();
             if (!$land) return false;
            
             $poundage = 0; //初始化手续费
             //扣除手续费
             if ($poundage== 0){
                 
                 if($user['pay_sxf']!='0'){    

                $poundage = round($order['money'] * ($user['pay_sxf']/100),2);
		     	//最低手续费
		     	if($poundage<'0.01'){
		     	    $poundage = '0.01';
		     	}
		     	
		     
		     	if($order['api_state']!=2){
		     	
                 $userMoney = Db::name('user')->where('id',$order['userid'])->find();
                 $tempMoney = round($userMoney['balance'] - $poundage,2);
                 if ($tempMoney < 0) return false;
		     	//判断这笔订单号手续费订单是否存在
		     	Db::name('log')->insert(array(
                 "userid"=>$order['userid'],
                 "time"=>time(),
                 "money"=>$poundage,
                 "land"=>$land['id'],
                 "num"=>$order['num'],
                 "payc"=>$land['typec'],
		         "beizhu"=>'商户收款手续费'
                  ));
                  
                  Db::name('user')->where('id',$order['userid'])->update(array("balance"=>$tempMoney));
		     	}
		     	}
             }
     
             //获取回掉地址
             $rebak = json_decode(encode($land['reback'],2));
             $url = $order['notify_url'];//回掉接口地址
             $method = $rebak->method;//请求方式
             $data = $rebak->data;//请求数据
             $header = $rebak->header;//header头
             $cookie = $rebak->cookie;//cookies
             $data = str_replace("[money]",$order['money'],$data);//金额替换
             $data = str_replace("[amount]",$order['money'],$data);//发起金额
             $data = str_replace("[order]",$order['num'],$data);//订单号
             $data = str_replace("[record]",$order['remark'],$data);//附加信息
             $data = str_replace("[remark]",trim($order['remark']),$data);//备注
             $data = str_replace("[key]",$user['api_key'],$data);//keyid
     
             $sign_data = [
             'api_id' => $user['api_id'],
             'record' => $order['remark'],
             'money' => sprintf("%.2f",$order['money'])
             ];
     
      
             $sign_index = md5_sign($sign_data,$user['api_key']);
             
             $data = str_replace("[sign]",$sign_index,$data);//验证签名
             $header = explode(PHP_EOL,trim($header,PHP_EOL));//header头 array数组
             if ($method == 'get'){
                 $row = curl($url . '?' . $data,null,null,$header,$cookie);
                 
             }
             if ($method == 'post'){
                 $row = curl($url,$data,null,$header,$cookie);
                 
             }
            
             //置订单已经请求api
             Db::name('orders')->where('id',$order['id'])->update(array(
                 'api_state'=>2,
                 'http'=>$row,
                 'request_time'=>time(),
                 'payment'=>$poundage
                 
             ));
             
             return true;
       }
       
        //检测字符串长度
        function islang_str($str,$mix,$max){
            $length = mb_strlen($str,"utf-8");
            if ($length < $max && $length >= $mix){
                return true;
            }else{
                return false;
            }
        }

        
        function curl($url,$post='',$cookies='',$header='',$referer='',$ip=0) {
        
            $curl = curl_init();
            curl_setopt($curl, CURLOPT_URL, $url);
            
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST,FALSE);
            if($ip==1){
            $proxyServer = "http://113.31.114.190:11031";
            
            curl_setopt($curl, CURLOPT_PROXYTYPE, 0);
            curl_setopt($curl, CURLOPT_PROXY, $proxyServer);
            curl_setopt($curl, CURLOPT_PROXYAUTH, CURLAUTH_BASIC);
            }
            if($post!=''){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
            }
            curl_setopt($curl, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36");
            curl_setopt($curl, CURLOPT_REFERER,$referer);
		          curl_setopt($curl, CURLOPT_COOKIE, $cookies);
		          if($header){
               curl_setopt($curl, CURLOPT_HTTPHEADER,$header);
            }
            
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
            $data = curl_exec($curl);
            return $data;
            curl_close($curl);
    
        }
        
     function curl_1($url,$post='',$cookies='',$header='',$referer='') {
        
            $curl = curl_init();
            curl_setopt($curl, CURLOPT_URL, $url);
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST,FALSE);
            if($post!=''){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
            }
            curl_setopt($curl, CURLOPT_USERAGENT, "");
            curl_setopt($curl, CURLOPT_REFERER,$referer);
		    curl_setopt($curl, CURLOPT_COOKIE, $cookies);
		    if($header){
               curl_setopt($curl, CURLOPT_HTTPHEADER,$header);
            }
            
            curl_setopt($curl, CURLOPT_HEADER,1); // 显示返回的Header区域内容
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
            
            $data = curl_exec($curl);
            $info = curl_getinfo($curl);
            return $info;
            curl_close($curl);
    
        }
        
        
        
        
        
        
        
        