<?php
// +—————————————————————————————————————————————————————————————————————
// | Created by Yunbao
// +—————————————————————————————————————————————————————————————————————
// | Copyright (c) 2013~2022 http://www.yunbaokj.com All rights reserved.
// +—————————————————————————————————————————————————————————————————————
// | Author: https://gitee.com/yunbaokeji
// +—————————————————————————————————————————————————————————————————————
// | Date: 2022-02-17
// +—————————————————————————————————————————————————————————————————————

    use think\Db;
    use cmf\lib\Storage;
    // 应用公共文件
    error_reporting(E_ALL);
    //ini_set('display_errors','On');
    //error_reporting(E_ERROR | E_WARNING | E_PARSE);
    require_once dirname(__FILE__).'/redis.php';

	/* 去除NULL 判断空处理 主要针对字符串类型*/
	function checkNull($checkstr){
		$checkstr=urldecode($checkstr);
		$checkstr=htmlspecialchars($checkstr);
		$checkstr=trim($checkstr);

		if( strstr($checkstr,'null') || (!$checkstr && $checkstr!=0 ) ){
			$str='';
		}else{
			$str=$checkstr;
		}
		return $str;	
	}
	
	/* 去除emoji表情 */
	function filterEmoji($str){
		$str = preg_replace_callback(
			'/./u',
			function (array $match) {
				return strlen($match[0]) >= 4 ? '' : $match[0];
			},
			$str);
		return $str;
	}

	/* 获取公共配置 */
	function getConfigPub() {
		$key='getConfigPub';
		$config=getcaches($key);
		if(!$config){
			$config=Db::name("option")
                    ->field('option_value')
                    ->where("option_name='site_info'")
                    ->find();
            $config=json_decode($config['option_value'],true);
            
            if($config){
                setcaches($key,$config);
            }
            
		}
        
        if(isset($config['live_time_coin'])){
            if(is_array($config['live_time_coin'])){
                
            }else if($config['live_time_coin']){
                $config['live_time_coin']=preg_split('/,|,/',$config['live_time_coin']);
            }else{
                $config['live_time_coin']=array();
            }
        }else{
            $config['live_time_coin']=array();
        }
        
        if(isset($config['login_type'])){
            if(is_array($config['login_type'])){
                
            }else if($config['login_type']){
                $config['login_type']=preg_split('/,|,/',$config['login_type']);
            }else{
                $config['login_type']=array();
            }
        }else{
            $config['login_type']=array();
        }
        

        
        if(isset($config['live_type'])){
            if(is_array($config['live_type'])){
                
            }else if($config['live_type']){
                $live_type=preg_split('/,|,/',$config['live_type']);
                foreach($live_type as $k=>$v){
                    $live_type[$k]=preg_split('/;|;/',$v);
                }
                $config['live_type']=$live_type;
            }else{
                $config['live_type']=array();
            }
        }else{
            $config['live_type']=array();
        }
            
		return 	$config;
	}	
	
	/* 获取私密配置 */
	function getConfigPri() {
		$key='getConfigPri';
		$config=getcaches($key);
		if(!$config){
			$config=Db::name("option")
                ->field('option_value')
                ->where("option_name='configpri'")
                ->find();
            $config=json_decode($config['option_value'],true);
			if($config){
                setcaches($key,$config);
            }
			
		}
        

        
		return 	$config;
	}
    
	/**
	 * 转化数据库保存的文件路径,为可以访问的url
	 */
	function get_upload_path($file){
        if($file==''){
            return $file;
        }
		if(strpos($file,"http")===0){
			return $file;
		}else if(strpos($file,"/")===0){
            $configpub=getConfigPub();
			$filepath= $configpub['site'].$file;
			return $filepath;
		}else{
/*
			$fileinfo=explode("_",$file);//上传云存储标识:qiniu:七牛云;
			$storage_type=$fileinfo[0];
			$start=strlen($storage_type)+1;
			if($storage_type=='qiniu'){ //七牛云
				$storage = Storage::instance();
				$file=substr($file,$start);
				return html_entity_decode($storage->getImageUrl($file));
			}else{

				$style='';

	            $storage = Storage::instance();
	            return $storage->getImageUrl($file, $style);
			}*/

            //minio
            $minio_domain_url = 'http://43.239.167.134:9000/';
            $storage_type = 'minio';
            $start=strlen($storage_type)+1;
            if($storage_type=='minio'){ //七牛云
                $file=substr($file,$start);
                return $minio_domain_url.$file;
            }else{

                $style='';
                $storage = Storage::instance();
                return $storage->getImageUrl($file, $style);
            }


            
		}
	}

    /*
    单文件云存储
    files  单个文件上传信息(包含键值)   $files['file']=$_FILES["file"]
    type  文件类型 img图片 video视频 music音乐

    */
	function adminUploadFiles($files=[]){
        // 要上传文件的本地路径
        $filePath = $files['file']['tmp_name'];
        $minio_domain_url = 'http://43.239.167.134:9000/';
        $minio_key = '6kUBnBRda9mes83brwEP';
        $minio_secret = 'AEPLazYp82HSMNlua3OCzXFo8rNxSQjgCdHD3bPT';
        $ext=strtolower(pathinfo($files['file']['name'], PATHINFO_EXTENSION));
        $key = date('Ymd').'/'.uniqid().'.'.$ext;
        /* 存放文件的桶 */
        $bucket = 'live';

        if (!function_exists('Aws\constantly')) {
            require CMF_ROOT . 'sdk/aws/aws-autoloader.php';
        }
        $s3 = new Aws\S3\S3Client([
            'version' => 'latest',
            'region' => 'us-east-1',
            'endpoint' => $minio_domain_url,
            'use_path_style_endpoint' => true,
            'credentials' => [
                'key' => $minio_key,
                'secret' => $minio_secret,
            ],
        ]);

        $result = $s3->putObject([
            'Bucket' => $bucket,
            'Key' => $key,
            'Body' => 'this is the body!',
            'SourceFile' => $filePath,
        ]);

        return $bucket.'/'.$key;
    }

	/* 获取等级 */
	function getLevelList(){
        $key='level';
		$level=getcaches($key);
		if(!$level){
			$level= Db::name("level")->order("level_up asc")->select();
            if($level){
                setcaches($key,$level);
            }else{
				delcache($key);
			}
		}
        
        foreach($level as $k=>$v){
            $v['thumb']=get_upload_path($v['thumb']);
            $v['thumb_mark']=get_upload_path($v['thumb_mark']);
            $v['bg']=get_upload_path($v['bg']);                 
            if($v['colour']){
                $v['colour']='#'.$v['colour'];
            }else{
                $v['colour']='#ffdd00';
            }
            $level[$k]=$v;
        }
        
        return $level;
    }
	function getLevel($experience){
		$level_a=1;
		$levelid=1;
		
        $level=getLevelList();

		foreach($level as $k=>$v){
			if( $v['level_up']>=$experience){
				$levelid=$v['levelid'];
				break;
			}else{
				$level_a = $v['levelid'];
			}
		}
		$levelid = $levelid < $level_a ? $level_a:$levelid;
		
		return (string)$levelid;
	}
	/* 主播等级 */
	function getLevelAnchorList(){
		$key='levelanchor';
		$level=getcaches($key);
		if(!$level){
			$level= Db::name("level_anchor")->order("level_up asc")->select();
            if($level){
                setcaches($key,$level);
            }else{
				delcache($key);
			}
		}
        
        foreach($level as $k=>$v){
            $v['thumb']=get_upload_path($v['thumb']);
            $v['thumb_mark']=get_upload_path($v['thumb_mark']);
            $v['bg']=get_upload_path($v['bg']);
            $level[$k]=$v;
        }
            
        return $level;
    }
	function getLevelAnchor($experience){
		$levelid=1;
		$level_a=1;
        $level=getLevelAnchorList();
        
		foreach($level as $k=>$v){
			if( $v['level_up']>=$experience){
				$levelid=$v['levelid'];
				break;
			}else{
				$level_a = $v['levelid'];
			}
		}
		$levelid = $levelid < $level_a ? $level_a:$levelid;
		
		return $levelid;
	}



	/* 用户基本信息 */
    function getUserInfo($uid) {
        $where['id']=$uid;
        $info= Db::name("user")->field("id,user_nicename,avatar,avatar_thumb,sex,signature,consumption,votestotal,province,user_status,city,birthday")->where($where)->find();
		if(!$info){
            $info['id']=$uid;
            $info['user_nicename']='用户不存在';
            $info['avatar']='/default.jpg';
            $info['avatar_thumb']='/default_thumb.jpg';
            $info['sex']='0';
            $info['signature']='';
            $info['consumption']='0';
            $info['votestotal']='0';
            $info['province']='';
            $info['city']='';
            $info['birthday']='';

			$info['user_status']='1';
        }
        
        if($info){
            $info['avatar']=get_upload_path($info['avatar']);
			$info['avatar_thumb']=get_upload_path($info['avatar_thumb']);
			$info['level']=getLevel($info['consumption']);
			$info['level_anchor']=getLevelAnchor($info['votestotal']);

            
            if($info['birthday']){
                $info['birthday']=date('Y-m-d',$info['birthday']);   
            }else{
                $info['birthday']='';
            }

            $token=Db::name("user_token")->where("user_id={$uid}")->value("token");
            $info['token']=$token;
            
        }
				
		return 	$info;		
    }	 
	/*获取收到礼物数量(tsd) 以及送出的礼物数量(tsc) */
	function getgif($uid){
		
		$count=Db::query('select sum(case when touid='.$uid.' then 1 else 0 end) as tsd,sum(case when uid='.$uid.' then 1 else 0 end) as tsc from cmf_user_coinrecord');
		return 	$count;		
	}
	/* 用户信息 含有私密信息 */
   function getUserPrivateInfo($uid) {
       $where['id']=$uid;
        $info= Db::name("user")->field('id,user_login,user_nicename,avatar,avatar_thumb,sex,signature,consumption,votestotal,province,city,coin,votes,birthday,issuper')->where($where)->find();
		if($info){
			$info['lighttime']="0";
			$info['light']=0;
			$info['level']=getLevel($info['consumption']);
			$info['level_anchor']=getLevelAnchor($info['votestotal']);
			$info['avatar']=get_upload_path($info['avatar']);
			$info['avatar_thumb']=get_upload_path($info['avatar_thumb']);
			
		
            
            if($info['birthday']){
                $info['birthday']=date('Y-m-d',$info['birthday']);   
            }else{
                $info['birthday']='';
            }

            $token=Db::name("user_token")->where("user_id={$uid}")->value("token");
            $info['token']=$token;
		}
		return 	$info;		
    }			
		
		/* 用户信息 含有私密信息 */
    function getUserToken($uid) {
        $where['user_id']=$uid;
		$info= Db::name("user_token")->field('token')->where($where)->find();
        if(!$info){
            return '';
        }
		return 	$info['token'];		
    }				

	/*判断token是否过期*/
	function checkToken($uid,$token){

		if(!$uid || !$token){
            session('uid',null);		
            session('token',null);
            session('user',null);
            cookie('uid',null);
            cookie('token',null);
			return 700;	
		}
        
        $key="token_".$uid;
		$userinfo=getcaches($key);


		if(!$userinfo){
            $where['user_id']=$uid;
			$userinfo=Db::name("user_token")->field('token,expire_time')->where($where)->find();	
            if($userinfo){
                setcaches($key,$userinfo);
            }else{
				delcache($key);
			}
		}
        
		if(!$userinfo || $userinfo['token']!=$token || $userinfo['expire_time']<time()){
            session('uid',null);		
            session('token',null);
            session('user',null);
            cookie('uid',null);
            cookie('token',null);
			return 700;				
		}else{
			return 	0;				
		} 
	}
	/*前台个人中心判断是否登录*/
	function LogIn()
	{
		$uid=session("uid");
		if($uid<=0)
		{
			header("Location: /"); 
			exit;
		}
	}


	
	/* 过滤关键词 */
	function filterField($field){
		$configpri=getConfigPri();
		
		$sensitive_field=$configpri['sensitive_field'];
		
		$sensitive=explode(",",$sensitive_field);
		$replace=array();
		$preg=array();
		foreach($sensitive as $k=>$v){
			if($v){
				$re='';
				$num=mb_strlen($v);
				for($i=0;$i<$num;$i++){
					$re.='*';
				}
				$replace[$k]=$re;
				$preg[$k]='/'.$v.'/';
			}else{
				unset($sensitive[$k]);
			}
		}
		
		return preg_replace($preg,$replace,$field);
	}
	
	/* 检验手机号 */
	function checkMobile($mobile){
		$ismobile = preg_match("/^1[3|4|5|6|7|8|9]\d{9}$/",$mobile);
		if($ismobile){
			return 1;
		}else{
			return 0;
		}
	}
	

	/* 时间差计算 */
	function datetime($time){
		$cha=time()-$time;
		$iz=floor($cha/60);
		$hz=floor($iz/60);
		$dz=floor($hz/24);
		/* 秒 */
		$s=$cha%60;
		/* 分 */
		$i=floor($iz%60);
		/* 时 */
		$h=floor($hz/24);
		/* 天 */
		
		if($cha<60){
			 return $cha.'秒前';
		}else if($iz<60){
			return $iz.'分钟前';
		}else if($hz<24){
			return $hz.'小时'.$i.'分钟前';
		}else if($dz<30){
			return $dz.'天前';
		}else{
			return date("Y-m-d",$time);
		}
	}
    


	/* 时长格式化 */
	function getSeconds($time,$type=0){

		if(!$time){
			return (string)$time;
		}

	    $value = array(
	      "years"   => 0,
	      "days"    => 0,
	      "hours"   => 0,
	      "minutes" => 0,
	      "seconds" => 0
	    );
	    
	    if($time >= 31556926){
	      $value["years"] = floor($time/31556926);
	      $time = ($time%31556926);
	    }
	    if($time >= 86400){
	      $value["days"] = floor($time/86400);
	      $time = ($time%86400);
	    }
	    if($time >= 3600){
	      $value["hours"] = floor($time/3600);
	      $time = ($time%3600);
	    }
	    if($time >= 60){
	      $value["minutes"] = floor($time/60);
	      $time = ($time%60);
	    }
	    $value["seconds"] = floor($time);

	    if($value['years']){
	    	if($type==1&&$value['years']<10){
	    		$value['years']='0'.$value['years'];
	    	}
	    }

	    if($value['days']){
	    	if($type==1&&$value['days']<10){
	    		$value['days']='0'.$value['days'];
	    	}
	    }

	    if($value['hours']){
	    	if($type==1&&$value['hours']<10){
	    		$value['hours']='0'.$value['hours'];
	    	}
	    }

	    if($value['minutes']){
	    	if($type==1&&$value['minutes']<10){
	    		$value['minutes']='0'.$value['minutes'];
	    	}
	    }

	    if($value['seconds']){
	    	if($type==1&&$value['seconds']<10){
	    		$value['seconds']='0'.$value['seconds'];
	    	}
	    }

	    if($value['years']){
	    	$t=$value["years"] ."年".$value["days"] ."天". $value["hours"] ."小时". $value["minutes"] ."分".$value["seconds"]."秒";
	    }else if($value['days']){
	    	$t=$value["days"] ."天". $value["hours"] ."小时". $value["minutes"] ."分".$value["seconds"]."秒";
	    }else if($value['hours']){
	    	$t=$value["hours"] ."小时". $value["minutes"] ."分".$value["seconds"]."秒";
	    }else if($value['minutes']){
	    	$t=$value["minutes"] ."分".$value["seconds"]."秒";
	    }else if($value['seconds']){
	    	$t=$value["seconds"]."秒";
	    }
	    
	    return $t;

	}


	/* 获取指定长度的随机字符串 */
	function random($length = 6 , $numeric = 0) {
		PHP_VERSION < '4.2.0' && mt_srand((double)microtime() * 1000000);
		if($numeric) {
			$hash = sprintf('%0'.$length.'d', mt_rand(0, pow(10, $length) - 1));
		} else {
			$hash = '';
			$chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789abcdefghjkmnpqrstuvwxyz';
			$max = strlen($chars) - 1;
			for($i = 0; $i < $length; $i++) {
				$hash .= $chars[mt_rand(0, $max)];
			}
		}
		return $hash;
	}
	

	function Post($curlPost,$url){
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_URL, $url);
		curl_setopt($curl, CURLOPT_HEADER, false);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($curl, CURLOPT_NOBODY, true);
		curl_setopt($curl, CURLOPT_POST, true);
		curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
		$return_str = curl_exec($curl);
		curl_close($curl);
		return $return_str;
	}
	
	function xml_to_array($xml){
		$reg = "/<(\w+)[^>]*>([\\x00-\\xFF]*)<\\/\\1>/";
		if(preg_match_all($reg, $xml, $matches)){
			$count = count($matches[0]);
			for($i = 0; $i < $count; $i++){
			$subxml= $matches[2][$i];
			$key = $matches[1][$i];
				if(preg_match( $reg, $subxml )){
					$arr[$key] = xml_to_array( $subxml );
				}else{
					$arr[$key] = $subxml;
				}
			}
		}
		return $arr;
	}
	/* 发送验证码 */
	
  



	//腾讯云短信
    function sendCodeByTencentSms($nationCode,$mobile,$code){
        require_once CMF_ROOT."sdk/tencentSms/index.php";
        $rs=array();
        $configpri = getConfigPri();
        
        $appid=$configpri['tencent_sms_appid'];
        $appkey=$configpri['tencent_sms_appkey'];


        $smsSign_dl = $configpri['tencent_sms_signName'];
        $templateId_dl=$configpri['tencent_sms_templateCode'];
  

        $tencent_sendcode_type=$configpri['tencent_sendcode_type'];

     
            $smsSign = $smsSign_dl;
            $templateId = $templateId_dl;

    

    
        $sender = new \Qcloud\Sms\SmsSingleSender($appid,$appkey);

        $params = [$code]; //参数列表与腾讯云后台创建模板时加的参数列表保持一致
        $result = $sender->sendWithParam($nationCode, $mobile, $templateId, $params, $smsSign, "", "");  // 签名参数未提供或者为空时,会使用默认签名发送短信
                
        //file_put_contents(API_ROOT.'/../log/sendCode_tencent_'.date('Y-m-d').'.txt',date('Y-m-d H:i:s').' 提交参数信息 result:'.json_encode($result)."\r\n",FILE_APPEND);
        $arr=json_decode($result,TRUE);

        if($arr['result']==0 && $arr['errmsg']=='OK'){
            //setSendcode(array('type'=>'1','account'=>$mobile,'content'=>"验证码:".$code."---国家区号:".$nationCode));
            $rs['code']=0;
        }else{
            $rs['code']=1002;
            $rs['msg']=$arr['errmsg'];
            // $rs['msg']='验证码发送失败';
        } 
        return $rs;     
                
    }

	/* 发送验证码 */
	function sendCode($country_code,$mobile,$code){
        
		$rs = array('code' => 0, 'msg' => '', 'info' => array());
        
		$config = getConfigPri();
        
        if(!$config['sendcode_switch']){
            $rs['code']=667;
			$rs['msg']='123456';
            return $rs;
        }

   
		$res=sendCodeByTencentSms($country_code,$mobile,$code);//腾讯云
  

		return $res;
	}
	
	/**导出Excel 表格
   * @param $expTitle 名称
   * @param $expCellName 参数
   * @param $expTableData 内容
   * @throws \PHPExcel_Exception
   * @throws \PHPExcel_Reader_Exception
   */
	function exportExcel($expTitle,$expCellName,$expTableData,$cellName)
	{
		//$xlsTitle = iconv('utf-8', 'gb2312', $expTitle);//文件名称
		$xlsTitle =  $expTitle;//文件名称
		$fileName = $xlsTitle.'_'.date('YmdHis');//or $xlsTitle 文件名称可根据自己情况设定
		$cellNum = count($expCellName);
		$dataNum = count($expTableData);
		
        $path= CMF_ROOT.'sdk/PHPExcel/';
        require_once( $path ."PHPExcel.php");
        
		$objPHPExcel = new \PHPExcel();
		$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(10);
		for($i=0;$i<$cellNum;$i++){
			$objPHPExcel->setActiveSheetIndex(0)->setCellValue($cellName[$i].'1', $expCellName[$i][1]);
		}
		for($i=0;$i<$dataNum;$i++){
			for($j=0;$j<$cellNum;$j++){
				$objPHPExcel->getActiveSheet(0)->setCellValue($cellName[$j].($i+2), filterEmoji( $expTableData[$i][$expCellName[$j][0]] ) );
			}
		}
		header('pragma:public');
		header('Content-type:application/vnd.ms-excel;charset=utf-8;name="'.$xlsTitle.'.xlsx"');
		header("Content-Disposition:attachment;filename={$fileName}.xlsx");//attachment新窗口打印inline本窗口打印
		$objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');//Excel5为xls格式,excel2007为xlsx格式
		$objWriter->save('php://output');
		exit;
	}
    
	/* 密码检查 */
	function passcheck($user_pass) {
        /* 必须包含字母、数字 */
        $preg='/^(?=.*[A-Za-z])(?=.*[0-9])[a-zA-Z0-9~!@&%#_]{6,20}$/';
        $isok=preg_match($preg,$user_pass);
        if($isok){
            return 1;
        }
        return 0;
	}	
	
	/**
	*  @desc 获取推拉流地址
	*  @param string $host 协议,如:http、rtmp
	*  @param string $stream 流名,如有则包含 .flv、.m3u8
	*  @param int $type 类型,0表示播流,1表示推流
	*/
	function PrivateKeyA($host,$stream,$type){
		$configpri=getConfigPri();
		$url=PrivateKey_tx($host,$stream,$type);
		

		
		return $url;
	}
	

	
	/**
	*  @desc 腾讯云推拉流地址
	*  @param string $host 协议,如:http、rtmp
	*  @param string $stream 流名,如有则包含 .flv、.m3u8
	*  @param int $type 类型,0表示播流,1表示推流
	*/
	function PrivateKey_tx($host,$stream,$type){
		$configpri=getConfigPri();
		$bizid=$configpri['tx_bizid'];
		$push_url_key=$configpri['tx_push_key'];
		$play_url_key=$configpri['tx_play_key'];
        $push=$configpri['tx_push'];
		$pull=$configpri['tx_pull'];
		
		$stream_a=explode('.',$stream);
		$streamKey = isset($stream_a[0])? $stream_a[0] : '';
		$ext = isset($stream_a[1])? $stream_a[1] : '';
		
		//$live_code = $bizid . "_" .$streamKey;    
		$live_code = $streamKey;    
		
		$now=time();  	
		$now_time = $now + 3*60*60;
		$txTime = dechex($now_time);

		$txSecret = md5($push_url_key . $live_code . $txTime);
		$safe_url = "?txSecret=" .$txSecret."&txTime=" .$txTime;

		$play_safe_url='';
		//后台开启了播流鉴权
		if($configpri['tx_play_key_switch']){
			//播流鉴权时间

			$play_auth_time=$now+(int)$configpri['tx_play_time'];
			$txPlayTime = dechex($play_auth_time);
			$txPlaySecret = md5($play_url_key . $live_code . $txPlayTime);
			$play_safe_url = "?txSecret=" .$txPlaySecret."&txTime=" .$txPlayTime;

		}		

		if($type==1){
			//$push_url = "rtmp://" . $bizid . ".livepush2.myqcloud.com/live/" .  $live_code . "?bizid=" . $bizid . "&record=flv" .$safe_url;	可录像
			//$url = "rtmp://" . $bizid .".livepush2.myqcloud.com/live/" . $live_code . "?bizid=" . $bizid . "" .$safe_url;
			$url=array(
				'cdn'=>"rtmp://{$push}/live",
				'stream'=>$live_code.$safe_url,
			);
		}else{
			$url = "http://{$pull}/live/" . $live_code . ".flv".$play_safe_url;
			
			if($ext){
				$url = "http://{$pull}/live/" . $live_code . ".".$ext.$play_safe_url;
			}
            
            $configpub=getConfigPub();
            
            if(strstr($configpub['site'],'https')){
                $url=str_replace('http:','https:',$url);
            }
			
			if($type==3){
				$url_a=explode('/'.$live_code,$url);
				$url=array(
					'cdn'=>"rtmp://{$pull}/live",
					'stream'=>$live_code,
				);
			}
		}
		
		return $url;
	}




	
	/* 生成邀请码 */
	function createCode($len=6,$format='ALL'){
        $is_abc = $is_numer = 0;
        $password = $tmp =''; 
        switch($format){
            case 'ALL':
                $chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
                break;
            case 'ALL2':
                $chars='ABCDEFGHJKLMNPQRSTUVWXYZ0123456789';
                break;
            case 'CHAR':
                $chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
                break;
            case 'NUMBER':
                $chars='0123456789';
                break;
            default :
                $chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
                break;
        }
        
        while(strlen($password)<$len){
            $tmp =substr($chars,(mt_rand()%strlen($chars)),1);
            if(($is_numer <> 1 && is_numeric($tmp) && $tmp > 0 )|| $format == 'CHAR'){
                $is_numer = 1;
            }
            if(($is_abc <> 1 && preg_match('/[a-zA-Z]/',$tmp)) || $format == 'NUMBER'){
                $is_abc = 1;
            }
            $password.= $tmp;
        }
        if($is_numer <> 1 || $is_abc <> 1 || empty($password) ){
            $password = createCode($len,$format);
        }
        if($password!=''){
            
            $oneinfo=Db::name("agent_code")->field("uid")->where("code='{$password}'")->find();
            if(!$oneinfo){
                return $password;
            }            
        }
        $password = createCode($len,$format);
        return $password;
    }


	
	/* 数字格式化 */
	function NumberFormat($num){
		if($num<10000){

		}else if($num<1000000){
			$num=round($num/10000,2).'万';
		}else if($num<100000000){
			$num=round($num/10000,1).'万';
		}else if($num<10000000000){
			$num=round($num/100000000,2).'亿';
		}else{
			$num=round($num/100000000,1).'亿';
		}
		return $num;
	}
	/* 数字格式化 不保留小数*/
	function NumberFormat2($num){
		if($num<10000){
			$num=round($num);
		}else if($num<100000000){
			$num=round($num/10000).'万';
		}else{
			$num=round($num/100000000).'亿';
		}
		return $num;
	}
	
	
	/* ip限定 */
	function ip_limit(){
		$configpri=getConfigPri();
		if($configpri['iplimit_switch']==0){
			return 0;
		}
		$date = date("Ymd");
		$ip= ip2long(get_client_ip(0,true)) ;
		$isexist=Db::name("getcode_limit_ip")->field('ip,date,times')->where("ip={$ip}")->find();
		if(!$isexist){
			$data=array(
				"ip" => $ip,
				"date" => $date,
				"times" => 1,
			);
			$isexist=Db::name("getcode_limit_ip")->insert($data);
			return 0;
		}elseif($date == $isexist['date'] && $isexist['times'] >= $configpri['iplimit_times'] ){
			return 1;
		}else{
			if($date == $isexist['date']){
				$isexist=Db::name("getcode_limit_ip")->where("ip={$ip}")->setInc('times',1);
				return 0;
			}else{
				$isexist=Db::name("getcode_limit_ip")->where("ip={$ip}")->update(array('date'=> $date ,'times'=>1));
				return 0;
			}
		}	
	}	
    


    /* 检测用户是否存在 */
    function checkUser($where){
        if(!$where){
            return 0;
        }

        $isexist=Db::name('user')->field('id')->where($where)->find();
        
        if($isexist){
            return 1;
        }
        
        return 0;
    }
        


    /*获取用户总的送出钻石数*/
	function getSendCoins($uid){
        $where['uid']=$uid;
		$sum=Db::name("user_coinrecord")->where("type='0' and (action='1' or action='2')")->where($where)->sum("totalcoin");
		return number_format($sum);
	}
    
    function m_s($a){
        $url=$_SERVER['HTTP_HOST'];
        if($url=='zbsc.yunbaozb.com'){
            $l=strlen($a);
            $sl=$l-6;
            $s='';
            for($i=0;$i<$sl;$i++){
                $s.='*';
            }
            $rs=substr_replace($a,$s,3,$sl);
            return $rs;
        }
        return $a;
    }


    /* 获取用户本场贡献 */
    function getContribut($uid,$liveuid,$showid){
        $where['uid']=$uid;
        $where['touid']=$liveuid;
        $where['showid']=$showid;
        $sum=Db::name("user_coinrecord")
				->where("action='1'")
                ->where($where)
				->sum('totalcoin');
        if(!$sum){
            $sum=0;
        }
        
        return (string)$sum;
    }
    

    
    
    /* 对象转数组 */
    function object_to_array($obj) {
        $obj = (array)$obj;
        foreach ($obj as $k => $v) {
            if (gettype($v) == 'resource') {
                return;
            }
            if (gettype($v) == 'object' || gettype($v) == 'array') {
                $obj[$k] = (array)object_to_array($v);
            }
        }
     
        return $obj;
    }
    
    /* 分类路径处理 */
    function setpath($id){
        $len=strlen($id);
        $s='';
        for($i=$len;$i<8;$i++){
            $s.='0';
        }
        $path=$s.$id.';';
        
        return $path;
    }
    

    
    /* 处理支付订单 */
    function handelCharge($where,$data=[]){
        $orderinfo=Db::name("charge_user")->where($where)->find();
        if(!$orderinfo){
            return 0;
        }
        
        if($orderinfo['status']!=0){
            return 1;
        }
        // 更新会员虚拟币
        $coin=$orderinfo['coin']+$orderinfo['coin_give'];
        $uid=$orderinfo['touid'];

        Db::name("user")->where("id='{$uid}'")->setInc("coin",$coin);
        // 更新 订单状态
        
        $data['status']=1;
        Db::name("charge_user")->where("id='{$orderinfo['id']}'")->update($data);

            
        return 2;

    }

	/* 时长格式化 */
	function getBanSeconds($cha,$type=0){		 
		$iz=floor($cha/60);
		$hz=floor($iz/60);
		$dz=floor($hz/24);
		/* 秒 */
		$s=$cha%60;
		/* 分 */
		$i=floor($iz%60);
		/* 时 */
		$h=floor($hz/24);
		/* 天 */
        
        if($type==1){
            if($s<10){
                $s='0'.$s;
            }
            if($i<10){
                $i='0'.$i;
            }

            if($h<10){
                $h='0'.$h;
            }
            
            if($hz<10){
                $hz='0'.$hz;
            }
            return $hz.':'.$i.':'.$s; 
        }
        
		
		if($cha<60){
			return $cha.'秒';
		}else if($iz<60){
			return $iz.'分钟'.$s.'秒';
		}else if($hz<24){
			return $hz.'小时'.$i.'分钟';
		}else if($dz<30){
			return $dz.'天'.$h.'小时';
		}
	}
    



	//修改用户的余额 type:0 扣除余额 1 增加余额
	function setUserBalance($uid,$type,$balance){

		$res=0;

		if($type==0){ //扣除用户余额,增加用户余额消费总额

			Db::name("user")
				->where("id={$uid} and balance>={$balance}")
				->setDec('balance',$balance);

		 	$res=Db::name("user")
				->where("id={$uid}")
				->setInc('balance_consumption',$balance);


		}else if($type==1){ //增加用户余额


			Db::name("user")
				->where("id={$uid}")
				->setInc('balance',$balance);

			$res=Db::name("user")
				->where("id={$uid}")
				->setInc('balance_total',$balance);
		}

		return $res;
	}



    





	/**
	 * 判断是否为合法的身份证号码
	 * @param $mobile
	 * @return int
	 */
	function isCreditNo($vStr){

		return true;
		
		$vCity = array(
		  	'11','12','13','14','15','21','22',
		  	'23','31','32','33','34','35','36',
		  	'37','41','42','43','44','45','46',
		  	'50','51','52','53','54','61','62',
		  	'63','64','65','71','81','82','91'
		);
		
		if (!preg_match('/^([\d]{17}[xX\d]|[\d]{15})$/', $vStr)){
		 	return false;
		}

	 	if (!in_array(substr($vStr, 0, 2), $vCity)){
	 		return false;
	 	}
	 
	 	$vStr = preg_replace('/[xX]$/i', 'a', $vStr);
	 	$vLength = strlen($vStr);

	 	if($vLength == 18){
	  		$vBirthday = substr($vStr, 6, 4) . '-' . substr($vStr, 10, 2) . '-' . substr($vStr, 12, 2);
	 	}else{
	  		$vBirthday = '19' . substr($vStr, 6, 2) . '-' . substr($vStr, 8, 2) . '-' . substr($vStr, 10, 2);
	 	}

		if(date('Y-m-d', strtotime($vBirthday)) != $vBirthday){
		 	return false;
		}

	 	if ($vLength == 18) {
	  		$vSum = 0;
	  		for ($i = 17 ; $i >= 0 ; $i--) {
	   			$vSubStr = substr($vStr, 17 - $i, 1);
	   			$vSum += (pow(2, $i) % 11) * (($vSubStr == 'a') ? 10 : intval($vSubStr , 11));
	  		}
	  		if($vSum % 11 != 1){
	  			return false;
	  		}
	 	}

	 	return true;
	}


	


	//获取数据库中的存储方式
	function getStorageType(){


		return $type='minio';;
	}

	/**
	 * 上传文件地址添加区分标识:qiniu:七牛云;aws:亚马逊
	 */
	function set_upload_path($file){
		if (empty($file)) {
            return '';
        }
        if (strpos($file, "http") === 0) {
            return $file;
        } else if (strpos($file, "/") === 0) {
            //return cmf_get_domain() . $file;
            return $file;
        } else {
			
			$cloudtype=getStorageType();
			if($cloudtype=='qiniu'){//七牛云存储(与APP协商一致,请不要随意更改)
				$filepath= "qiniu_".$file;
			}elseif($cloudtype=='minio'){
                $filepath= "minio_".$file;
            }else{
				$filepath=$file;
			}
		}
		return $filepath;
	}

	

	function get_file_suffix($file_name, $allow_type = array()){

      $fnarray=explode('.', $file_name);

      $file_suffix = strtolower(end($fnarray));


      if (empty($allow_type)){
        return true;
      }else{
        if (in_array($file_suffix, $allow_type)){
			return true;
        }else{
			return false;
        }
      }
    }