<?php if( !defined( 'ONGPHP')) exit( 'Error OngSoft');

function zstixain($value){
    
    $post_data = array (
        'mid' => $value['linguid'], //在掌上零钱里面获取的uid
        'jine' => $value['jine'], //要请求发放的金额
        'openid'=>$value['txopenid'], //第二步获取的openid
        'tixianid'=>$value['tixianid'], //本地的提现id【要求唯一】字符串类型的数字，最大长度11位数
        'lailu' =>$value['lailu'], //可选参数
    );
    
    $mkey = md5($post_data['mid'].$post_data['jine'].$post_data['openid'].$value['lingkey']);
    
    $post_data['mkey'] = $mkey;
    $post_data['lx'] = 8;//4是时间夺宝 5是是采水果8尾号竞猜
    
    $url = $value['lingurl'].'jieru.php';
    $da = post($post_data,$url);
    
    $result = is_not_json($da);
    if($result){
        //不是json
        $info['success'] = false;
        $info['msg'] = "未知错误4稍后再试";
    
        exit(json_encode($info));
    }
    
    
    $daa = json_decode($da,true);
    
    //dump($daa );exit;
    if($daa['o']!='yes'){
    
    
        $info['success'] = false;
        $info['msg'] = $daa['msg'];
        
        exit(json_encode($info));
    
    
    }
    $info['data'] = $daa;
    $info['success'] = true;
    $info['msg'] = $daa['msg'];
    
    return $info;
    
}
function weixintixian($value){
    
    $mch_appid = $value['appid'];//公众账号appid
    
    $mchid = $value['mchid'];//商户号 1488033902
    
    $nonce_str='whjc'.rand(100000, 999999);//随机数
    
    $partner_trade_no = $value['partner_trade_no'];//商户订单号
    
    $openid = $value['openid']; //用户唯一标识,上一步授权中获取  o33R41o3lF8zDMx-giIqE_LOG-CQ
    
    $check_name='NO_CHECK';//校验用户姓名选项，NO_CHECK：不校验真实姓名， FORCE_CHECK：强校验真实姓名（未实名认证的用户会校验失败，无法转账），OPTION_CHECK：针对已实名认证的用户才校验真实姓名（未实名认证用户不校验，可以转账成功）
    
    $re_user_name = $value['name'];//用户姓名
    
    $amount = $value['amount'];//企业金额，这里是以分为单位（必须大于100分）
    
    $desc='VNSCMS.COM-H5游戏';//描述
    
    $spbill_create_ip = $value['ip'];//请求ip
    
    $dataArr=array();
    
    $dataArr['amount']=$amount;
    
    $dataArr['check_name']=$check_name;
    
    $dataArr['desc']=$desc;
    
    $dataArr['mch_appid']=$mch_appid;
    
    $dataArr['mchid']=$mchid;
    
    $dataArr['nonce_str']=$nonce_str;
    
    $dataArr['openid']=$openid;
    
    $dataArr['partner_trade_no']=$partner_trade_no;
    
    $dataArr['re_user_name']=$re_user_name;
    
    $dataArr['spbill_create_ip']=$spbill_create_ip;
    
    $sign=getSign2($dataArr,$value['partnerkey']);//getSign($dataArr);见结尾
    //拼写正确的xml参数
    $data="<xml>
    
<mch_appid>".$mch_appid."</mch_appid>
    
<mchid>".$mchid."</mchid>
    
<nonce_str>".$nonce_str."</nonce_str>
    
<partner_trade_no>".$partner_trade_no."</partner_trade_no>
    
<openid>".$openid."</openid>
    
<check_name>".$check_name."</check_name>
    
<re_user_name>".$re_user_name."</re_user_name>
    
<amount>".$amount."</amount>
    
<desc>".$desc."</desc>
    
<spbill_create_ip>".$spbill_create_ip."</spbill_create_ip>
    
<sign>".$sign."</sign>
    
</xml>";
    
    $ch = curl_init ();
    
    $MENU_URL="https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers";
    
    curl_setopt ( $ch, CURLOPT_URL, $MENU_URL );
    curl_setopt ( $ch, CURLOPT_CUSTOMREQUEST, "POST" );
    curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, FALSE );
    curl_setopt ( $ch, CURLOPT_SSL_VERIFYHOST, FALSE );
    
    //两个证书（必填，请求需要双向证书。）
    
    $zs1="./ong/moudl/cert/apiclient_cert.pem";
    $zs2="./ong/moudl/cert/apiclient_key.pem";
    
    curl_setopt($ch,CURLOPT_SSLCERT,$zs1);
    
    curl_setopt($ch,CURLOPT_SSLKEY,$zs2);
    
    curl_setopt ( $ch, CURLOPT_FOLLOWLOCATION, 1 );
    
    curl_setopt ( $ch, CURLOPT_AUTOREFERER, 1 );
    
    curl_setopt ( $ch, CURLOPT_POSTFIELDS, $data );
    
    curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
    
    
    
    $info = curl_exec ( $ch );
    
    
    
    if (curl_errno ( $ch )) {
    
        echo 'Errno' . curl_error ( $ch );
        exit;
    
    }
    curl_close ( $ch );
    
    
    $result = xmlToArray($info);
    
    if(isset($result['result_code'])){
        
        if($result['result_code'] == SUCCESS){
            //
            $array['success'] = true;
            $array['msg'] = "成功";
            
            $array['data'] = $result;
        }else{
            
            $array['success'] = false;
            $array['msg'] = $result['err_code_des'];
            
            exit(json_encode($array));
            
        }
        
    }
    
    return $array;
    
    //dump($info);
    
}

function xmlToArray($xml){

    //禁止引用外部xml实体

    libxml_disable_entity_loader(true);

    $xmlstring = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);

    $val = json_decode(json_encode($xmlstring),true);

    return $val;

}

function getSign2($Obj,$key)
{
    //var_dump($Obj);//die;
    foreach ($Obj as $k => $v)
    {
        $Parameters[$k] = $v;
    }
    //签名步骤一：按字典序排序参数
    ksort($Parameters);
    $String = formatBizQueryParaMap($Parameters, false);//方法如下
    //echo '【string1】'.$String.'</br>';
    //签名步骤二：在string后加入KEY
    $String = $String."&key=".$key;//

    //echo "【string2】".$String."</br>";
    //签名步骤三：MD5加密
    $String = md5($String);
    //echo "【string3】 ".$String."</br>";
    //签名步骤四：所有字符转为大写
    $result_ = strtoupper($String);
    //echo "【result】 ".$result_."</br>";
    return $result_;
}

/**
 * 作用：格式化参数，签名过程需要使用
 */
function formatBizQueryParaMap($paraMap, $urlencode)
{
    //var_dump($paraMap);//die;
    $buff = "";
    ksort($paraMap);
    foreach ($paraMap as $k => $v)
    {
        if($urlencode)
        {
            $v = urlencode($v);
        }
        //$buff .= strtolower($k) . "=" . $v . "&";
        $buff .= $k . "=" . $v . "&";
    }
    $reqPar = '';
    if (strlen($buff) > 0)
    {
        $reqPar = substr($buff, 0, strlen($buff)-1);
    }
    //var_dump($reqPar);//die;
    return $reqPar;
}


function is_not_json($str){
    return is_null(json_decode($str));
}

function chajine($id){
    if(in_array($id,array(6,10,14))){

        $jine = 5;

    }
    if(in_array($id,array(7,11,15))){
    
        $jine =10;
    
    }
    if(in_array($id,array(8,12,16))){
    
        $jine =20;
    
    }
    if(in_array($id,array(9,13,17))){
    
        $jine =50;
    
    }
    
	if($id == 1){
		
		$jine = 2;
		
	}

    return $jine;
}

function chaimg($id){
   
switch ($id)
{
case 6:
  $img = "shouji-20.png";
  break;
case 7:
  $img = "shouji-50.png";
  break;
case 8:
  $img = "shouji-100.png";
  break;
case 9:
  $img = "shouji-300.png";
  break;
case 10:
 $img = "jingdong-20.png";
 break;
case 11:
 $img = "jingdong-50.png";
 break;
 case 12:
     $img = "jingdong-100.png";
     break;
 case 13:
     $img = "jingdong-300.png";
     break;
 case 14:
     $img = "shiyou-20.png";
     break;
 case 15:
     $img = "shiyou-50.png";
     break;
 case 16:
     $img = "shiyou-100.png";
     break;
 case 17:
     $img = "shouji-300.png";
     break;          
default:
  $img = "shouji-20.png";
}

$img = "/Public/Home/images/chongzhika/".$img;
    return $img;
}
//云寄售
function chanpin(){

    $url = 'http://www.yunpuhuo.com/chanpin.php';

    $chanpin = file_get_contents($url);
    $a = json_decode($chanpin,true);//['id'=>'','name'=>'','jine'=>'','image'=>'']

    dump($a);exit;


}

/*
 * 发卡
 */
function yunfaka($uid,$yunid,$orderid)
{

    global $CONN;

    $data = array(
        'mid' =>"44",//1
        'key'=>"610271", //$CONN['yunkey']
        'uid'=>$uid,//玩家id uid = 1
        'cpid'=>(int)$yunid,//云寄售商品id
        'orderid'=>$orderid,//商家订单号
    );

    $sign = getsign($data);

    $data['sign'] = $sign;

    unset($data['key']);

    $url = "http://www.yunpuhuo.com/request.php";

    $res = post($data,$url);

    //dump($res);exit;
    $response =  json_decode($res,true);

    return $response;
    //dump($response);exit;
    //return $response['data'];//['orderid'=>'','kahao'=>'','kami'=>'']

}

/*
 *寄售
 * 异步返回：成功的订单号(array)
 */


function jishou($uid,$orderids)
{

    global $CONN;

    $data = array(

        'mid' => '1',
        'key'=>"86768057",
        'uid'=>$uid,//玩家id
        'orderid'=>json_encode($orderids),//订单号，用‘,’隔开
        'tburl'=>WZHOST .'index.php?action=me',//同步返回地址
        'yburl'=>WZHOST .'jishouchuli.php',//异步返回地址
    );

    $sign = getsign($data);//签名

    $data['sign'] = $sign;

    unset($data['key']);

    $data = base64_encode(json_encode($data));

    $url = "http://www.yunpuhuo.com/jishou.php?data=".$data."&t=".rand(0,100000);

    header("location:".$url);


}


/*
 *兑换
 * 异步返回：成功的订单号(array)
 */

function duihuan($uid,$orderids)
{
    global $CONN;

    $data = array(

        'mid' => '1',
        'key'=>"86768057",
        'uid'=>$uid,
        'orderid'=>json_encode($orderids),
        'tburl'=>WZHOST .'index.php?action=me',
        'yburl'=>WZHOST .'duihuanlechuli.php',
    );

    $sign = getsign($data);

    $data['sign'] = $sign;

    unset($data['key']);

    $data = base64_encode(json_encode($data));

    $url = "http://www.yunpuhuo.com/duihuan.php?data=".$data."&t=".rand(0,100000);

    header("location:".$url);

}

function getSign($data)
{
    //签名步骤一：按字典序排序参数
    ksort($data);
    foreach ($data as $k=>$v){

        $data[$k] = (string)$v;

    }
    //echo '【string1】'.$String.'</br>';
    //签名步骤二：序列化
    $String = serialize($data);
    //签名步骤三：MD5加密
    $String = md5($String);
    //echo "【string3】 ".$String."</br>";
    //签名步骤四：所有字符转为大写
    $result_ = strtoupper($String);
    //echo "【result】 ".$result_."</br>";
    return $result_;
}

function unlock_thisfile($fp,$tmpFileStr){

    @flock($fp,LOCK_UN);

    @fclose($fp);

    @fclose($fp);

    @unlink($tmpFileStr.".lock");

}

function lock_thisfile($tmpFileStr,$locktype=false){

    if($locktype == false)

        $locktype = LOCK_EX|LOCK_NB;

    $can_write = 0;

    $lockfp = @fopen($tmpFileStr.".lock","w");

    if($lockfp){

        $can_write = @flock($lockfp,$locktype);

    }

    if($can_write){

        return $lockfp;

    }

    else{

        if($lockfp){

            @fclose($lockfp);

            @unlink($tmpFileStr.".lock");

        }

        return false;

    }

}

function randomFloat($min = 0, $max = 10)
{
    $num = rand(90,99);
    $num = (float)$num/100;
    return sprintf("%.2f", $num);

}

function get_rand_num(array $value,$begin,$end)
{
    $i = (int)$begin;
    $tiaojian = (int)$end;
    
    $chouqu = array();
    
    for($i;$i<=$tiaojian;$i++){
        
        if(in_array($i,$value)){
            
        }else{
            
            $chouqu[] = $i;
            
        }
        
    }
    
    $num = count($chouqu)-1;
    $suiji1 = mt_rand(0,$num);
    $num = $chouqu[$suiji1];
    
    
    return $num;
    
}

function get_rand_num11(array $value,$begin,$end)
{
    $num = rand($begin,$end);
    if(in_array($num, $value))
    {
        $num = get_rand_num($value,$begin,$end);
    }
    
    return $num;
    
}

function zhongjiangtype($array,$zhi,$number=''){
    
    $rand = (int)rand(1,100);
    //file_get_contents('text123123.txt',$rand);
    $sum = 0;
    
    if($zhi[0] == $zhi[1]){
        if($zhi[2] == $zhi[0]){
            return 5;
        }else{
            if($zhi[3] == $zhi[0])
             return 5;
        }
        
        return 4;
    }
    
    
    foreach($array as $key=>$value){
        
        
        if($value == 0){
            $tyrand[$key][b] = 0;
            $tyrand[$key][e] = 0;
        }else{
            $tyrand[$key][b] = (int)$sum+(int)1;
            $tyrand[$key][e] = (int)$sum+(int)$value;
        
        }
        
        if($tyrand[$key][b]<= $rand ){

            if($rand<=$tyrand[$key][e]){
                
                
                if($key==4){
                    
                        $key = 3;   
                }
                
                if($key==5){
                    
                        $key = 3;
                     
                }
                
                //file_get_contents('test11.txt',$key);
                return $key;
                break;
            }
            
        }
        
        $sum = (int)$sum+(int)$value;
        
    }
    
    
    
}

//zidingyi
function dump($var, $echo=true, $label=null, $strict=true) {
    $label = ($label === null) ? '' : rtrim($label) . ' ';
    if (!$strict) {
        if (ini_get('html_errors')) {
            $output = print_r($var, true);
            $output = '<pre>' . $label . htmlspecialchars($output, ENT_QUOTES) . '</pre>';
        } else {
            $output = $label . print_r($var, true);
        }
    } else {
        ob_start();
        var_dump($var);
        $output = ob_get_clean();
        if (!extension_loaded('xdebug')) {
            $output = preg_replace("/\]\=\>\n(\s+)/m", '] => ', $output);
            $output = '<pre>' . $label . htmlspecialchars($output, ENT_QUOTES) . '</pre>';
        }
    }
    if ($echo) {
        echo($output);
        return null;
    }else
        return $output;
}

function cut_str($string, $sublen, $start = 0, $code = 'UTF-8')
{
    if($code == 'UTF-8')
    {
        $pa = "/[\/x01-\/x7f]|[\/xc2-\/xdf][\/x80-\/xbf]|\/xe0[\/xa0-\/xbf][\/x80-\/xbf]|[\/xe1-\/xef][\/x80-\/xbf][\/x80-\/xbf]|/xf0[\/x90-\/xbf][\/x80-\/xbf][\/x80-\/xbf]|[\/xf1-\/xf7][\/x80-\/xbf][\/x80-\/xbf][\/x80-\/xbf]/";
        preg_match_all($pa, $string, $t_string);
        if(count($t_string[0]) - $start > $sublen) return join('', array_slice($t_string[0], $start, $sublen))."...";
        return join('', array_slice($t_string[0], $start, $sublen));
    }
    else
    {
        $start = $start*2;
        $sublen = $sublen*2;
        $strlen = strlen($string);
        $tmpstr = '';

        for($i=0; $i< $strlen; $i++)
        {
            if($i>=$start && $i< ($start+$sublen))
            {
            if(ord(substr($string, $i, 1))>129)
            {
            $tmpstr.= substr($string, $i, 2);
            }
            else
            {
            $tmpstr.= substr($string, $i, 1);
        }
    }
    if(ord(substr($string, $i, 1))>129) $i++;
}
if(strlen($tmpstr)< $strlen ) $tmpstr.= "...";
return $tmpstr;
}
}



//自定义
function isemail($data){

        /*验证邮箱*/
        return preg_match('/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/',$data);

}


function isshouji($data){

        /*验证手机*/
        return preg_match('/^1\d{10}$/',$data);
}


function duanxin( $shouji , $shuju ){

        /* 1 注册通知
           2 找回通知
           3 绑定通知
           4 购买通知
           5 发货通知
           6 确认通知
        */


        //return 'success:11111';

        $neirong = '';
        $IP = IP();
        $DUQU = include QTLANG ;
        if(!isset( $shuju['type'] )) $shuju['type'] = 1;
        if(!isset( $shuju['YZM'] )) $shuju['YZM'] = '';
        if(!isset( $shuju['ZH'] )) $shuju['ZH'] = '';
        if(!isset( $shuju['NC'] )) $shuju['NC'] = '';
        if(!isset( $shuju['DDID'] )) $shuju['DDID'] = '';
        if(!isset( $shuju['IP'] )) $shuju['IP'] = '';
        if(!isset( $shuju['TIME'] )) $shuju['TIME'] = '';
        if(!isset( $shuju['KDFS'] )) $shuju['KDFS'] = '';
        if(!isset( $shuju['KDHM'] )) $shuju['KDHM'] = '';
        if(!isset( $shuju['JINE'] )) $shuju['JINE'] = '';
        if(!isset( $shuju['UID'] )) $shuju['UID'] = '';
        if(!isset( $shuju['BT'] )) $biaoti = ''; else $biaoti = $shuju['BT'];
        
        $neirong  = str_replace(   array(         'YZM',        'ZH' ,       'NC' ,       'DDID',        'IP',    'TIME' ,        'KDFS' ,       'KDHM'   ,     'JINE'   ,     'UID')  , 
                                    array( $shuju['YZM'],$shuju['ZH'],$shuju['NC'],$shuju['DDID'],       $IP ,     time() ,$shuju['KDFS'],$shuju['KDHM'],$shuju['JINE'],$shuju['UID']
                        ) ,$DUQU['sms'.$shuju['type']]);
        




        $time = time() ;
        $woqu = qfopen('http://222.73.117.156/msg/HttpBatchSendSM?account='.$DUQU['duanxinid'].'&pswd='.$DUQU['duanxinkey'].'&needstatus=false&mobile='.$shouji.'&msg='.urlencode(iconv('UTF-8', 'UTF-8//IGNORE',$neirong)).'&timestamp='.$time);

 
        $cansh = explode( ',' , $woqu );

        if( $cansh['1'] =='0' ) return 'success:'.$cansh['0'];
        else return 'error:'.$cansh['1'];


}


function youxiang( $zhanghao , $shuju ){

       $neirong = '';

        $DUQU = include QTLANG ;
        if(!isset( $shuju['type'] )) $shuju['type'] = 1;
        if(!isset( $shuju['YZM'] )) $shuju['YZM'] = '';
        if(!isset( $shuju['ZH'] )) $shuju['ZH'] = '';
        if(!isset( $shuju['NC'] )) $shuju['NC'] = '';
        if(!isset( $shuju['DDID'] )) $shuju['DDID'] = '';
        if(!isset( $shuju['IP'] )) $shuju['IP'] = '';
        if(!isset( $shuju['TIME'] )) $shuju['TIME'] = '';
        if(!isset( $shuju['KDFS'] )) $shuju['KDFS'] = '';
        if(!isset( $shuju['KDHM'] )) $shuju['KDHM'] = '';
        if(!isset( $shuju['JINE'] )) $shuju['JINE'] = '';
        if(!isset( $shuju['UID'] )) $shuju['UID'] = '';
        if(!isset( $shuju['BT'] )) $biaoti = ''; else $biaoti = $shuju['BT'];

        $fajian = $DUQU['mailfa'];
        
         $IP = IP();
     
        
        $neirong  = str_replace(   array(         'YZM',        'ZH' ,       'NC' ,       'DDID',        'IP',    'TIME' ,        'KDFS' ,       'KDHM'   ,     'JINE'   ,     'UID')  , 
                                    array( $shuju['YZM'],$shuju['ZH'],$shuju['NC'],$shuju['DDID'],       $IP ,     time() ,$shuju['KDFS'],$shuju['KDHM'],$shuju['JINE'],$shuju['UID']
                        ) ,$DUQU['sms'.$shuju['type']]);

                                    

        $headers = 'From: '.$fajian .'<'.$fajian .'>' . "\r\n" .
                 'Reply-To: '.$fajian . "\r\n" . 
                 'Content-type: text/html;charset=UTF-8'."\r\n".
                 'X-Mailer: PHP/' . phpversion();
        if (mail($zhanghao, $biaoti, $neirong, $headers))  
             return 'success:ok';
        else return 'error:no';

}


function pichttp( $url ){

        if($url == '') return  WZHOST.ltrim( '/tpl/font/noimg.png' ,'/');
        if( strstr( $url , "://" ) )return $url;
        else return WZHOST.ltrim( $url,'/');

}


function regsong( $USER ){

    /* 注册赠送
       $USER 用户最新信息
    */


}


function czthongzhi( $USER , $JINE , $DDID  ){
        /*  充值成功通知处理
            $USER 用户最新信息
            $JINE 充值金额
            $DDID 充值的订单
        */


}


function zchongzhifan( $D  = '' , $USER , $JINE , $DDID ){
    /*  扩展处理通知
        $D  数据表结构
        $USER 用户最新信息
        $JINE 用户金额
    */
     


}



function kjreg( $lx = 0 , $uid = '' , $nc = '' , $tx ='' , $uindd = ''){

         /* 快捷注册 */

        global $CONN;
        $WHere = array('off' =>  1,
                        'ip' =>  IP(),
                      'level' => 1,
                 'yanzhengip' =>  $CONN['yanzhengip'],
                      'atime' =>  time());

         if( kjcha( $lx , $uid , $uindd ) ) return false;

         $D = db('user');
         if($lx == 1) $WHere['qqopen'] = $uid;
         else if($lx == 2) $WHere['weixin'] = $uid;
         else if($lx == 3) $WHere['weibo'] = $uid;
         else if($lx == 4) $WHere['zhifubaoopen'] = $uid;
         else if($lx == 5) $WHere['openid'] = $uid;
         else if($lx == 6) $WHere['openidd'] = $uid;

        if( ( $lx == 2 ||  $lx == 5 ) && $uindd != '' ) $WHere['weixinui'] = $uindd;
       
         $nc = ( anquanqu(  $nc ) );
         if($nc == '') $nc = mima( rand(1,888888));
         $WHere['name'] =  $nc;

         $WHere['touxiang'] = touxiang( $tx );

         if( isset( $_SESSION['tuid'] )){

             if( $_SESSION['tuid']  > 0){

                 $tuid =  uid( $_SESSION['tuid'] );

                 if( $tuid ){

                     $WHere['tuid'] = $_SESSION['tuid'];

                     for( $i = 1 ; $i < $CONN['tujishu'] ; $i++ ){
                             $wds = $i-1;
                             if($wds < 1) $wds= '' ;
                             $WHere['tuid'.$i] = $tuid['tuid'.$wds];
                    }
                 }
             }
         }



        $sql = $D -> setshiwu('1')  -> insert( $WHere );

        return $D -> qurey( $sql ,'shiwu');

}




function bangding( $lx = 0 , $UID = '' , $uid = '' , $nc = '' , $tx ='', $weixinui = '' ){

         /* 快捷登录绑定查询
           2 weixin          用户微信登录openid   唯一
             ( 2,5 )  weixinui 微信uiopenid         唯一
           1 qqopen          用户QQ登录openid     唯一
           3 weibo           新浪微博登录openid   唯一
           4 zhifubaoopen        支付宝登录openid     唯一
           5 openid          备用openid           唯一
           6 openidd         备用openid1          唯一
         */

         $WHere = array();

         if( kjcha( $lx , $uid  , $weixinui ) ) return false;


         $D = db('user');
         if($lx == 1) $WHere['qqopen'] = $uid;
         else if($lx == 2) $WHere['weixin'] = $uid;
         else if($lx == 3) $WHere['weibo'] = $uid;
         else if($lx == 4) $WHere['zhifubaoopen'] = $uid;
         else if($lx == 5) $WHere['openid'] = $uid;
         else if($lx == 6) $WHere['openidd'] = $uid;
        if( $nc != ''){
            $nc = ( anquanqu(  $nc ) );
            if($nc == '') $nc = mima( rand(1,888888));
            $WHere['name'] =  $nc;
        }

        if( ( $lx == 2 ||  $lx == 5 ) && $weixinui != '' ) $WHere['weixinui'] = $weixinui;

        if( $tx != '') $WHere['touxiang'] = touxiang( $tx );

        $sql = $D -> setshiwu('1') -> where( array( 'uid' => $UID) ) -> update( $WHere );

        $fan = $D -> qurey( $sql ,'shiwu');

        if($fan && isset ( $_GET['state'] ) &&  strlen( $_GET['state']) == 32){

                 global $Mem;
                 $HASH = 'kjdenglu/'.mima( $_GET['state']  );
                 $Mem -> s($HASH, $UID ,20);
         }

        return $fan ;

        
}


function kjcha( $lx = 0 , $uid = '' , $unopid = '' ){

         /* 快捷登录绑定查询
           2 weixin          用户微信登录openid   唯一
             ( 2,5 )  weixinui 微信uiopenid       唯一
           1 qqopen          用户QQ登录openid     唯一
           3 weibo           新浪微博登录openid   唯一
           4 zhifubaoopen        支付宝登录openid 唯一
           5 openid          app openid           唯一
           6 openidd         备用openid1          唯一
             weixinui        微信uiopenid         唯一
            
         
         */

         if( $uid == '' ) msgbox( '' , WZHOST );

         $WHere = array();
         $D = db('user');
         if($lx == 1) $WHere['qqopen'] = $uid;
         else if($lx == 2) $WHere['weixin'] = $uid;
         else if($lx == 3) $WHere['weibo'] = $uid;
         else if($lx == 4) $WHere['zhifubaoopen'] = $uid;
         else if($lx == 5) $WHere['openid'] = $uid;
         else if($lx == 6) $WHere['openidd'] = $uid;

        if( ( $lx == 2 ||  $lx == 5 ) && $unopid != '') $WHere['weixinui OR'] = $unopid;

        $fan = $D ->where( $WHere )-> find();

        if( $fan &&  isset( $WHere['weixinui OR'] ) && $fan['weixinui'] == '' ){



            $sql  = $D ->setshiwu(1) -> where(array('uid' => $fan['uid'] ) )-> update( array( 'weixinui' =>  $unopid ) );

            $mywo = $D -> qurey( $sql );

            if($mywo ) uid(  $fan['uid'] ,1 );



        }

         if($fan && isset ( $_GET['state'] ) &&  strlen( $_GET['state']) == 32){

                 global $Mem;
                 $HASH = 'kjdenglu/'.mima( $_GET['state']  );
                 $Mem -> s($HASH, $fan['uid'] ,20);
         }

         return $fan ;


}


function touxiang( $tx = ''){

         if($tx != '') return pichttp( $tx) ;
         else return '/attachment/touxiang/'.rand(0,13).'.gif';
}

function faduanxin( $shouji , $neirong ,$duanxinid,$duanxinkey){

        /* 短信发送脚本

           $shouji  手机号码
           $neirong 发送的内容
        */
        $DUQU = include QTLANG ;
        $time = time() ;
        $woqu = qfopen('http://222.73.117.156/msg/HttpBatchSendSM?account='.$duanxinid.'&pswd='.$duanxinkey.'&needstatus=false&mobile='.$shouji.'&msg='.urlencode(iconv('UTF-8', 'UTF-8//IGNORE',$neirong)).'&timestamp='.$time);
        $cansh = explode( ',' , $woqu );
        if( $cansh['1'] =='0' ) return 'success:'.$cansh['0'];
        else return 'error:'.$cansh['1'];
}




 function tongjiqian( $bili,$maxedu,$fenbao,$zuida ){

    

    $D = db('');
    $order = '  ';
    $tiaojian = array(
        'type' => 1
        );
    $chongz = $D -> setbiao('jinelog') -> order(  )->where( $tiaojian )-> select();
    /*统计总充值*/

    if ($chongz) {  /*如果存在的话*/

        /*计算充值金额*/
        $chongqianarr = array();
        foreach($chongz as  $k => $v){

            $chongqianarr[] = $v['jine'];

        }

        $zongchongzhi = array_sum( $chongqianarr );


        /*然后计算抓取娃娃的支出*/

        $order = '  ';
        $tiaojian = array(
            'type IN' => '4,5,6,7,8',
            );

        $zhichu = $D -> setbiao('jinelog') -> order(  )->where( $tiaojian )-> select();


        if ($zhichu) {

            $zhichuarr = array();
            foreach($zhichu as  $k => $v){

                $zhichuarr[] = $v['jine'] ;

            }

            $zhichuzong = array_sum( $zhichuarr );

        }else{

            $zhichuzong = 0;

        }


            /*计算现在的钱*/
            $xianzaide = (float)$zongchongzhi - (float)$zhichuzong;





            if ($xianzaide>0) { /*如果大于零的话，说明是盈利的*/
                    /*获取奖池金额*/
                    $bi = ( 1-$bili );
                    /*计算钱奖池金额*/
                    $jiangchi = ( (float)$zongchongzhi * $bi) -   (float)$zhichuzong ;



                    if ($jiangchi>0) {

                        if ($jiangchi > (float)$maxedu) {  /*如果奖池内的钱大于最高额度的话执行*/

                             $fen = mt_rand(1,3);

                         #分散度
                        $reward=new reward();
                        $rewardArr=$reward->splitReward($maxedu,$fen,100);

                        /*过滤掉值为0的项*/
                        $guo = array_filter($rewardArr);
                        $num = count($guo);
                        $suiji = mt_rand(0,$num-1);
                        $suijideqian = $guo[$suiji];

                    }else{

                        $reward=new reward();
                        $rewardArr=$reward->splitReward($jiangchi,$fenbao,100);

                        /*过滤掉值为0的项*/
                        $guo = @array_filter($rewardArr);
                        $num = count($guo);
                        $suiji = @mt_rand(0,$num-1);
                        $suijideqian = $guo[$suiji];

                    }

                    return $suijideqian;


                }else{


                    return 0;

                }

                

            }else{  /*如果小于零的话，说明是不盈利的*/

                return 0;

            }

    }else{

        return 0;

    }




 }



 
/*
 *Author:Kermit
 *Time:2015-8-26
 *Note:红包生成随机算法
 */ 


#红包生成的算法程序
class reward
{
     public $rewardMoney;        #红包金额、单位元
     public $rewardNum;                  #红包数量
     public $scatter;            #分散度值1-10000
     public $rewardArray;        #红包结果集
     
     #初始化红包类
     public function __construct()
     {
            $this->rewardArray=array();
     }
     
     #执行红包生成算法
     public function splitReward($rewardMoney,$rewardNum,$scatter=100)
     {
             #传入红包金额和数量
             $this->rewardMoney=$rewardMoney;
            $this->rewardNum=$rewardNum;
            $this->scatter=$scatter;
            $this->realscatter=$this->scatter/100;
            
            /*
             *前言：今天我突然这样一想，比如要把1个红包分给N个人，实际上就是相当于要得到N个百分比数据
             *     条件是这N个百分比之和=100/100。这N个百分比的平均值是1/N。
             *     并且这N个百分比数据符合一种正态分布（多数值比较靠近平均值）
             *观点：微信红包里很多0.01的红包，我觉得这是微信程序里的人为控制，目的是为了防止总红包数超过总额，先分了几个0.01的红包。
             *     不然不管是以随机概率还是正态分布都很难会出现非常多的0.01元红包。
             */
            
            #我的思路：正如上面说的，比如：1个红包发给5个人，我要得出5个小数，它们的和是1，他们的平均值是1/5
            #计算出发出红包的平均概率值、精确到小数4位。即上面的1/N值。
            $avgRand=round(1/$this->rewardNum,4);
             
            #红包的向平均数集中的分布正像数学上的抛物线。抛物线y=ax2，|a|越大则抛物线的开口就越小，|a|越小则抛物线的开口就越大,a>0时开口向上，我们这都是正数，就以a>0来考虑吧。
            #程序里的$scatter值即为上方的a，此值除以100，当做100为基准，
            #通过开方(数学里的抛物线模型，开方可缩小变化值)得出一个小数字较多（小数字多即小红包多）的随机分布,据此生成随机数
            $randArr=array();
            while(count($randArr)<$rewardNum)
            {
                    $t=round(sqrt(mt_rand(1,10000)/$this->realscatter));
                    $randArr[]=$t;
            }
            
            #计算当前生成的随机数的平均值，保留4位小数
            $randAll=round(array_sum($randArr)/count($randArr),4);
            
            #为将生成的随机数的平均值变成我们要的1/N，计算一下生成的每个随机数都需要除以的值。我们可以在最后一个红包进行单独处理，所以此处可约等于处理。
            $mixrand=round($randAll/$avgRand,4);
            
            #对每一个随机数进行处理，并剩以总金额数来得出这个红包的金额。
            $rewardArr=array();
            foreach($randArr as $key=>$randVal)
            {
                    $randVal=round($randVal/$mixrand,4);
                    $rewardArr[]=round($this->rewardMoney*$randVal,2);
            }
            
            #对比红包总数的差异、修正最后一个大红包
            sort($rewardArr);
            $rewardAll=array_sum($rewardArr);
            $rewardArr[$this->rewardNum-1]=$this->rewardMoney-($rewardAll-$rewardArr[$this->rewardNum-1]);
            rsort($rewardArr);

            #对红包进行排序一下以方便在前台图示展示
            foreach($rewardArr as $k=>$value)
            {
                    $t=$k%2;
                    if($t) array_push($this->rewardArray,$value);
                    else array_unshift($this->rewardArray,$value);
            }
            $rewardArr=NULL;
            return $this->rewardArray;
     }
    
}

function tongjiz(){

    $D = db('');
    /*计算所有的充值金额*/

    $WHERE = array(
        'type' => 0
        );
    $order = 'id desc';
    $chongzhiz = $D ->setbiao('jinelog')->order( $order )->where( $WHERE )-> select();

    if (is_array($chongzhiz)) {
            
        $jj = array();
        foreach($chongzhiz as  $k => $v){
            $jj[] = $v['jine'];
        }
        $chongzhizong = 0-array_sum($jj) ;
        $chongzhizong = sprintf("%0.2f",$chongzhizong);
        

    }else{
        $chongzhizong = 0;
    }

    file_put_contents('test11.txt', $chongzhizong);

    $WHERE['type'] = 1;
    $order = 'id desc';
    $daili = $D ->setbiao('admin')->order( $order )->where( $WHERE )-> select();
    
    if (is_array($daili)) {
    
        $jj = array();
        foreach($daili as  $k => $v){
            $jj[] = $v['huobi'];
        }
        $dailimoney = array_sum($jj) ;
        $dailimoney = sprintf("%0.2f",$dailimoney);
    
    
    }else{
        $dailimoney = 0;
    }
    
    
    /*计算佣金*/
    $WHERE['type'] = 1;
    $order = 'id desc';
    $yongs = $D ->setbiao('huobilog')->order( $order )->where( $WHERE )-> select();
    if ( $yongs ) {
        $yongarr = array();
        foreach($yongs as  $k => $v){
            $yongarr[] = $v['jine'];
        }
        $yongzong = array_sum( $yongarr );
        $yongzong = sprintf("%0.2f",$yongzong);


    }else{
        $yongzong = 0;
    }

   
    /*计算用户得钱*/
    $order = 'id desc';
    $yonghude = $D ->setbiao('jinelog')->order( $order )->where( array(

        'type  IN ' => '3'

        ) )-> select();


    if ($yonghude) {
        $yonghuzong = array();
        foreach($yonghude as  $k => $v){
            $yonghuzong[] = $v['jine'];
        }
        $yonghude1 = array_sum($yonghuzong);
        $yonghude1 = sprintf("%0.2f",$yonghude1);
    }else{
        $yonghude1 = 0;
    }
    
    //计算红包总额
    $hongbao = $D ->setbiao('jinelog')->order( $order )->where( array(
    
        'type  IN ' => '4'
    
    ) )-> select();

    if ($hongbao) {
        $hongbaozong = array();
        foreach($hongbao as  $k => $v){
            $hongbaozong[] = $v['jine'];
        }
        $hongbaozong1 = array_sum($hongbaozong);
        $hongbaozong1 = sprintf("%0.2f",$hongbaozong1);
    }else{
        $hongbaozong1 = 0;
    }
    /*当前奖池额度*/

   $fanhui = array(

    'chongzhiz' =>$chongzhizong,
    'yongjinz' => $yongzong,
    'yonghude' => $yonghude1,
    'dailimoney' =>$dailimoney,
    'hongbao' => $hongbaozong1,
       
    );
   return $fanhui;

}


function  shuiguodianshu($qishu,$dengji='1'){

    $D = db('');
    // $jiangchi = $D ->setbiao('jiangchi')-> where( array( "id" => $qishu ) ) -> find();
    // if ($jiangchi['iskaijiang']) {

    // 	return $jiangchi['dianshu'];

    // }



    /*查看奖池详细*/
    $order = 'id desc';
    $jiangxs = $D ->setbiao('jiangchix')->order( $order )->where( array(
        'jiangchiid' => $qishu,
    ) )-> select();


    if ($jiangxs) {	/*如果有投入的话*/
        file_put_contents("test11.txt","Hello World. Testing!");
        $tong = array();
        foreach($jiangxs as  $k => $v){

            $userdian = $v['dianshu'];
            $userqian = $v['jine'];
            /*假如他们都中奖的话*/
            /**/
            $tong[$userdian][] = $userqian;

        }


    }else{  /*说明本期没有人投钱,那么就随机返回点数1,2,3*/

        $arr = array(
            1,2,3
        );

        $num = count($arr)-1;
        $suiji1 = mt_rand(0,$num);
        $suijishu = $arr[$suiji1];
        return $suijishu;

    }


    if (is_array($tong)) {

        $dian = array();
        foreach($tong as  $k => $v){
            $zz = array_sum($v);
            $dian[$k] = $zz;
        }
    }

    if(!isset($dian[1])){
        $dian[1] = 0;
    }
    if(!isset($dian[2])){
        $dian[2] = 0;
    }
    if(!isset($dian[3])){
        $dian[3] = 0;
    }

    $tiaojian = array(
        'id IN' => '441,442,443'
    );
    $bili = $D -> setbiao('center') -> order(  )->where( $tiaojian )-> select();
    if ($bili) {

        $shuk = array();
        foreach($bili as  $k => $v){
             
            $shuk[$v['id']] = $v;

        }

    }

    /*如果计算都都得钱的话*/
    if (is_array($dian)) {

        $dechi  = array();

        foreach($dian as  $k => $v){


            if ($k==3) {

                $bili = $shuk[443]['guanjian'];

                $zzz = $v*$bili;

                /*计算总得钱*/
                $dechi[$k] = $zzz;

            }elseif ($k==2) {


                $bili = $shuk[442]['guanjian'];

                $zzz = $v*$bili;

                /*计算总得钱*/
                $dechi[$k] = $zzz;

            }elseif ($k==1) {

                $bili = $shuk[441]['guanjian'];
                $zzz = $v*$bili;
                /*计算总得钱*/
                $dechi[$k] = $zzz;
            }
        }
    }

    /*将数组进行排序*/
    arsort($dechi);
    /*去除掉*/

    if ($dechi) {
        $ff = array();
        foreach($dechi as  $k => $v){

            $ff[] = $k;

        }

    }
    file_put_contents("test.txt",implode('-',$ff));

    if($dechi[$ff[0]]>($dian[$ff[0]]+$dian[$ff[1]]+$dian[$ff[2]])){
        if($dechi[$ff[1]]>($dian[$ff[0]]+$dian[$ff[1]]+$dian[$ff[2]])){
            return $ff[2];
        }else{
            
            if($dengji == 1){
                return $ff[1];
            }else{
                return $ff[2];
            }
            
        }
        
        
    }else{
        
    }
    
    if($dengji == 1){
       return $ff[0];
    }
    
    if($dengji == 2){
        return $ff[1];
    }
    if($dengji == 3){
        return $ff[2];
    }
    
    

}


// function  shuiguodianshu($qishu,$dengji='1'){

//     $D = db('');
//     // $jiangchi = $D ->setbiao('jiangchi')-> where( array( "id" => $qishu ) ) -> find();
//     // if ($jiangchi['iskaijiang']) {

//     // 	return $jiangchi['dianshu'];

//     // }



//     /*查看奖池详细*/
//     $order = 'id desc';
//     $jiangxs = $D ->setbiao('jiangchix')->order( $order )->where( array(
//         'jiangchiid' => $qishu,
//     ) )-> select();


//     if ($jiangxs) {	/*如果有投入的话*/
//         file_put_contents("test11.txt","Hello World. Testing!");
//         $tong = array();
//         foreach($jiangxs as  $k => $v){

//             $userdian = $v['dianshu'];
//             $userqian = $v['jine'];
//             /*假如他们都中奖的话*/
//             /**/
//             $tong[$userdian][] = $userqian;

//         }


//     }else{  /*说明本期没有人投钱,那么就随机返回点数1,2,3*/

//         $arr = array(
//             1,2,3
//         );

//         $num = count($arr)-1;
//         $suiji1 = mt_rand(0,$num);
//         $suijishu = $arr[$suiji1];
//         return $suijishu;

//     }


//     if (is_array($tong)) {

//         $dian = array();
//         foreach($tong as  $k => $v){
//             $zz = array_sum($v);
//             $dian[$k] = $zz;
//         }
//     }

//     if(!isset($dian[1])){
//         $dian[1] = 0;
//     }
//     if(!isset($dian[2])){
//         $dian[2] = 0;
//     }
//     if(!isset($dian[3])){
//         $dian[3] = 0;
//     }

//     $tiaojian = array(
//         'id IN' => '441,442,443'
//     );
//     $bili = $D -> setbiao('center') -> order(  )->where( $tiaojian )-> select();
//     if ($bili) {

//         $shuk = array();
//         foreach($bili as  $k => $v){
             
//             $shuk[$v['id']] = $v;

//         }

//     }

//     /*如果计算都都得钱的话*/
//     if (is_array($dian)) {

//         $dechi  = array();

//         foreach($dian as  $k => $v){


//             if ($k==3) {

//                 $bili = $shuk[443]['guanjian'];

//                 $zzz = $v*$bili;

//                 /*计算总得钱*/
//                 $dechi[$k] = $zzz;

//             }elseif ($k==2) {


//                 $bili = $shuk[442]['guanjian'];

//                 $zzz = $v*$bili;

//                 /*计算总得钱*/
//                 $dechi[$k] = $zzz;

//             }elseif ($k==1) {

//                 $bili = $shuk[441]['guanjian'];
//                 $zzz = $v*$bili;
//                 /*计算总得钱*/
//                 $dechi[$k] = $zzz;
//             }
//         }
//     }

//     /*将数组进行排序*/
//     arsort($dechi);
//     /*去除掉*/

//     if ($dechi) {
//         $ff = array();
//         foreach($dechi as  $k => $v){

//             $ff[] = $k;

//         }

//     }
//     file_put_contents("test.txt",implode('-',$ff));

//     if($dengji == 1){
//         if($dechi[$ff[0]]<$dechi[$ff[1]]+$dechi[$ff[2]]){
//             return $ff[0];
//         }else{
//             return $ff[1];
//         }
//     }
//     if($dengji == 2){

//         return $ff[1];

//     }
//     if($dengji == 3){

//         return $ff[2];

//     }

// }


