<?php

/**
 * Created by ghostsf
 * Date: 2016/4/20
 */

namespace app\admin\controller;

use app\admin\model\Config;
use app\admin\model\Personalconfig;
use think\Controller;
use think\Db;
require 'qiniu/autoload.php';
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use Qiniu\Processing\PersistentFop;
use think\Config as redis;

/**
 * 公共
 * Class Common
 * @package app\admin\controller
 */
class CommonController extends Controller {
    // 定义配置项
    private $config=array(
        'APPID'              => 'wx12fe768e213a0476', // 微信支付APPID.
        'MCHID'              => '1508786811', // 微信支付MCHID 商户收款账号
        'KEY'                => '', // 微信支付KEY
        'APPSECRET'          => '', // 公众帐号secert (公众号支付专用)
        'NOTIFY_URL'         => 'http://mms.mangmeshi.com/admin/Apiauth/huidiao', // 接收支付状态的连接

    );
    public  $redis;
    /**
     * 拦截器
     *
     * @return bool
     */
    public function _initialize() {
//session过期验证
        if (!isset($_SESSION['loginSession'])) {
            header("http/1.1", true, 389); //389 http状态码 session过期
            return false;
        }
    }
    /**
     * 七牛云存储
     */
//    public function qiniuCommon($type,$rand,$exe,$filePath)
    public function qiniuCommonVideo()
    {

        $name = $_FILES['video']['name'];
        $type = 5;
        $rand = date('YmdHis').rand(100000,999999);
        $filePath = $_FILES['video']['tmp_name'];
        $exe = explode('.',$name);
        $exe = end($exe);
        if($type == 2){
            if($exe != 'jpg' && $exe != 'gif' && $exe != 'png'){
                $return = array('status'=>0,'msg'=>'请上传图片');
                return $return;
            }
        }
        if($type == 3){
            if($exe != 'xls' && $exe != 'xlsx' && $exe != 'zip' && $exe != 'docx' && $exe != 'pdf'){
                $return = array('status'=>0,'msg'=>'请上传正确的文件格式');
                return $return;
            }
        }
        if($type == 4){
            if($exe != 'mp3' && $exe != 'm4a' && $exe != 'wav'){
                $return = array('status'=>0,'msg'=>'请上传正确的音频格式');
                return $return;
            }
        }
        if($type == 5){
            if($exe != 'mp4' && $exe != 'mov' && $exe != 'mkv' && $exe != 'flv' && $exe != '3gp' && $exe != 'wmv' && $exe != 'rmvb' && $exe != 'avi'){
                $return = array('status'=>0,'msg'=>'请上传正确的视频格式');
                return $return;
            }
        }
        $accessKey = 'nEztET3cvxjK87xXvVSOohxPd39zJTlO04jLgD74';
        $secretKey = 'ThogMprroyhdDO5q163ClfRQ_CBn8yXRsHAx1_Qk';
        $bucket = 'mangmeshi';
        $auth = new Auth($accessKey, $secretKey);
        $returnBody = '{"key":"$(key)","mimeType":"$(mimeType)","vtime":"$(avinfo.video.duration)","atime":"$(avinfo.audio.duration)","fsize":$(fsize),"width":"$(imageInfo.width)","height":"$(imageInfo.height)","height":"$(imageInfo.height)","format":"$(imageInfo.format)"}';
        $policy = array(
            'returnBody' => $returnBody
        );
        $expires = 3600;
        $token = $auth->uploadToken($bucket, null, $expires, $policy, true);
//        $filePath = $_FILES['file444']['tmp_name'];
// 上传到七牛后保存的文件名
        $key = $rand.'.'.$exe;
// 初始化 UploadManager 对象并进行文件的上传。
        $uploadMgr = new UploadManager();
//用 UploadManager 的 putFile 方法进行文件的上传
        list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
        if ($err !== null) {
            if($exe == 'mp4'){
                return json_encode(['status'=>200,'msg'=>'http://paz3uzuv1.bkt.clouddn.com/'.$key.'mp4']);
            }else{
                $res = $this->qnCommon1($key);
                if(isset($res['err'])){
                    return json_encode(['status'=>0,'msg'=>'转码失败']);
                }else{
                    return json_encode(['status'=>200,'msg'=>'http://paz3uzuv1.bkt.clouddn.com/'.$res['rand'].'mp4']);
                }
            }

//            $info = $err;
        } else {
            return json_encode(['status'=>0,'msg'=>'上传失败']);
        }
//        $info['status'] = 200;
//        var_dump($info);die;
//        return $info;
    }
    public function qnCommon1($key)
    {
//        $key = "zhouyang.avi";
        $accessKey = 'nEztET3cvxjK87xXvVSOohxPd39zJTlO04jLgD74';
        $secretKey = 'ThogMprroyhdDO5q163ClfRQ_CBn8yXRsHAx1_Qk';
        $bucket = 'mangmeshi';
//        $accessKey = '62pzsS8cWNBVDOVRxhJNejBzQCbCkAKIS5Oy0lOn';
//        $secretKey = '5HvPUZ0EzObz9z261EK5AuJntP5OT0_LV9ScDNnv';
//        $bucket = 'nanyibucketby2017year';
        $auth = new Auth($accessKey, $secretKey);

        $pipeline = 'mang_mp4';
        $force = false;
        $notifyUrl = 'http://mms.mangmeshi.com/admin/Api/index';
        $config = new \Qiniu\Config();
        $pfop = new PersistentFop($auth, $config);
        $rand = date('YmdHis').rand(100000,999999);
        $fops = "avthumb/mp4/s/640x360/vb/1.4m|saveas/" . \Qiniu\base64_urlSafeEncode($bucket .  ":".$rand.'.mp4');
        list($id, $err) = $pfop->execute($bucket, $key, $fops, $pipeline, $notifyUrl, $force);
        if ($err != null) {
            $info['err'] = $err;
            $info['rand'] = $rand;
        } else {
            $info['id'] = $id;
            $info['rand'] = $rand;
        }
//        var_dump($info);die;
        return $info;
//        list($ret, $err) = $pfop->status($id);
//        echo "\n====> pfop avthumb status: \n";
//        if ($err != null) {
//            var_dump($err);
//        } else {
//            var_dump($ret);
//        }

    }
    /**
     * @return string
     * get七牛token
     */
    public function getQiniuToken(){header("Access-Control-Allow-Origin:*");
        $accessKey = 'nEztET3cvxjK87xXvVSOohxPd39zJTlO04jLgD74';
        $secretKey = 'ThogMprroyhdDO5q163ClfRQ_CBn8yXRsHAx1_Qk';
        $auth = new Auth($accessKey, $secretKey);
        $bucket = 'mangmeshi';
// 生成上传Token
        $token = $auth->uploadToken($bucket);
        return json_encode(['status'=>200,'msg'=>$token]);
    }
    /**
     * 发送短信
     * @param $phone
     * @param $num
     * @return mixed
     */
    public function duaxin($phone,$num){
        $body_json = array(
            'sid'=>'2010a51e49df34754c876fbe910061a4',
            'token'=>'01528a612dab2ad66f70fca870a88078',
            'appid'=>'85f7e8ae0e2d4dd6a9d619ccda794047',
            'templateid'=>'296258',
            'param'=>$num,
            'mobile'=>$phone,
            'uid'=>'',
        );
        $body = json_encode($body_json);
        $header = array(
            'Accept:application/json',
            'Content-Type:application/json;charset=utf-8',
        );
        $url = 'https://open.ucpaas.com/ol/sms/sendsms';
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch,CURLOPT_POST,1);
        curl_setopt($ch,CURLOPT_POSTFIELDS,$body);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $result = curl_exec($ch);
        curl_close($ch);
        $res = json_decode($result,true);
        return $res;
    }


    /**
     * 获取融云token
     * @param $uid
     * @param $name
     * @param $imageurl
     * @return mixed
     */
    public function rongyun($uid=0,$name='',$imageurl=''){//echo 1;die;
        $appKey = 'n19jmcy5n8l09';
        $appSecret = 'P8BCshr6wkp5T';
        $body = "userId={$uid}&name={$name}&portraitUri={$imageurl}";
        $nonce = mt_rand();
        $timeStamp = time();
        $sign = sha1($appSecret.$nonce.$timeStamp);
        $header = array(
            'App-Key:'.$appKey,
            'Nonce:'.$nonce,
            'Timestamp:'.$timeStamp,
            'Signature:'.$sign,
            'Content-Type: application/x-www-form-urlencoded'
        );
        $url = 'http://api.cn.ronghub.com/user/getToken.json';
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch,CURLOPT_POST,1);
        curl_setopt($ch,CURLOPT_POSTFIELDS,$body);
//    curl_setopt($ch, CURLOPT_SSL_VERI/FYPEER, false);
//    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $result = curl_exec($ch);
        curl_close($ch);
        $res = json_decode($result,true);
        return $res;
//    var_dump($res) ;
    }

    public function uploadFile($tmp,$name,$size)
    {
        if($size > 2048*1024){
            return array('status'=>0,'msg'=>"图片不得超过2M!");
        }
        $imgarray = array('jpg','jpeg','png');
        $dir = $_SERVER['DOCUMENT_ROOT'];
        $url =  "http://".$_SERVER['HTTP_HOST'];
        if($tmp){
            //=======重命名=====
            $rand = date('YmdHis').rand(100000,999999);
            $exe = explode('.',$name);
            $exe = end($exe);
            if(!in_array($exe,$imgarray)){
                return array('status'=>0,'msg'=>'图片格式不支持');
            }
            $newName = $rand . '.' .$exe;
            //=======================
            if(move_uploaded_file($tmp,"{$dir}/mang/image/{$newName}")){
                $imgUrl = "{$url}/mang/image/{$newName}";
                return array('status'=>200,'msg'=>$imgUrl);
            }else{
                return array('status'=>0,'msg'=>'图片保存失败');
            }
        }else{
            return array('status'=>0,'msg'=>"上传一张图!");
        }
    }
    function diffBetweenTwoDays ($day2)
    {
        $day1 = date('Y-m-d');
        $second1 = strtotime($day1);
        $second2 = strtotime($day2);
        if ($second1 < $second2) {
            $tmp = $second2;
            $second2 = $second1;
            $second1 = $tmp;
        }
        return ($second1 - $second2) / 86400;
    }
    /**
     * 验证唯一性:异地登陆
     * @param $uid
     * @param $time
     * @param $value
     * @param $reqKey
     * @return bool
     */
    public  function checkAll($uid,$time,$value,$reqKey){//$uid,$time,$value
        header("Access-Control-Allow-Origin:*");
        if($uid == 0){
            return true;
        }else{
            $user = Db::table('ew_u_user')->where('user_id',$uid)
                ->field('user_id,user_auth,user_auth_date,user_status,user_token')->find();
            if($user['user_status'] != 1){//禁用
                return false;
            }
            //------------------------------------------------------
            if($user['user_auth'] > 0){
                $today = date('Y-m-d');
                if($user['user_auth_date'] < $today){
                    Db::table('ew_u_user')->where('user_id',$uid)->update(['user_auth'=>0]);
                }
            }
            //------------------------------------------------------
            $token = $user['user_token'];
            $appId = "A6060432236270";
            $appkey = "F591B37E-1C61-01C7-57C6-8B2F6D59DCD9";
            $myreqKey = md5($appId . 'XW' . $appkey . 'XW' . $time);
            $myvalue = md5($uid . 'XW' . $token . 'XW' . $time);
            if($myvalue != $value || $myreqKey != $reqKey){
                return false;
            }else{
                return true;
            }
        }
    }
    public function uuid($prefix = '')
    {
        $chars = md5(uniqid(mt_rand(), true));
        $uuid  = substr($chars,0,8);
        $uuid .= substr($chars,8,4);
        $uuid .= substr($chars,12,4);
        $uuid .= substr($chars,16,4);
        $uuid .= substr($chars,20,12);
        return $prefix . $uuid;
    }
    /**
     * @return string
     */
    public function getJobData($type,$where,$page,$self=1){
        $orderNum = 1;
        if(isset($where['order'])){
            $orderNum = $where['order'];
            unset($where['order']);
        }
        if($orderNum == 1){
            $order = "job_createtime DESC";
        }elseif ($orderNum == 2){
            $order = "job_createtime ASC";
        }elseif ($orderNum == 3){
            $order = "distance DESC";
        }elseif ($orderNum == 4){
            $order = "distance ASC";
        }elseif ($orderNum == 5){
            $order = "job_zhouqi_order DESC";
        }elseif ($orderNum == 6){
            $order = "job_zhouqi_order ASC";
        }else{
            $order = "job_createtime DESC";
        }
        $field = 'job_id,user_id,job_user_id,job_name,job_status,job_type,u.district sheng,ua.district shi,uaa.district qu,job_money_min,job_money_max,job_createtime,job_zhouqi_order';
        $field .= ',job_year,job_phone,job_weixin,job_qq,job_school,job_age_min,job_age_max,job_sex,user_username,user_image';
        $field .= ',job_peple,job_com_find_zhouqi,job_zhouqi_year,job_zhi,job_whatfor,job_views';
        if(isset($where['lat']) && isset($where['lon']) && $where['lat'] && $where['lon']){
            $lat = $where['lat'];
            $lon = $where['lon'];
            unset($where['lat']);
            unset($where['lon']);
        }else{
            $lat = 0.1;
            $lon = 0.1;
        }
        $field .= ',ROUND(6378.138 * 2 * ASIN(SQRT(POW(SIN(('.$lat.'* PI() / 180 - job_lat * PI() / 180) / 2),2) + COS('.$lat.' * PI() / 180) * COS(job_lat * PI() / 180) * POW(SIN(('.$lon.' * PI() / 180 - job_lon * PI() / 180) / 2),2))) * 1000) AS distance';
        if($type == 1){
            $field .= ',user_one_star';
        }elseif($type == 2){
            $field .= ',user_company,user_company_logo,job_com_name,user_two_star';
        }elseif($type == 3){
            $field .= ',user_thr_star';
        }

        if(isset($where['job_name'])){
            $search = $where['job_name'];
            unset($where['job_name']);
            $data = Db::table('ew_job')->alias('j')
                ->join('ew_u_user uu','j.job_user_id=uu.user_id','LEFT')
                ->join('ew_area u','j.job_sheng=u.district_id','LEFT')
                ->join('ew_area ua','j.job_shi=ua.district_id','LEFT')
                ->join('ew_area uaa','j.job_qu=uaa.district_id','LEFT')
                ->where($where)
                ->where(function ($query) use($search){
                    $query->where('job_name','like',"%$search%")
                        ->whereOr('job_address','like',"%$search%")
                        ->whereOr('job_com_name','like',"%$search%");
                })
                ->field($field)
                ->order($order)
                ->limit(($page-1)*10,10)
                ->select();
        }else{
            $data = Db::table('ew_job')->alias('j')
                ->join('ew_u_user uu','j.job_user_id=uu.user_id','LEFT')
                ->join('ew_area u','j.job_sheng=u.district_id','LEFT')
                ->join('ew_area ua','j.job_shi=ua.district_id','LEFT')
                ->join('ew_area uaa','j.job_qu=uaa.district_id','LEFT')
                ->where($where)
                ->field($field)
                ->order($order)
                ->limit(($page-1)*10,10)
                ->select();
            if(!$data && $self==1){
                $morenids = Db::table('ew_u_user')->where('user_moren',2)->column('user_id');
                if($morenids){
                    $data = Db::table('ew_job')->alias('j')
                        ->join('ew_u_user uu','j.job_user_id=uu.user_id','LEFT')
                        ->join('ew_area u','j.job_sheng=u.district_id','LEFT')
                        ->join('ew_area ua','j.job_shi=ua.district_id','LEFT')
                        ->join('ew_area uaa','j.job_qu=uaa.district_id','LEFT')
                        ->where('job_type',$type)
                        ->where('job_user_id','in',$morenids)
                        ->field($field)
                        ->order($order)
                        ->limit(($page-1)*10,10)
                        ->select();
                }

            }
        }
        return $data;
    }
    /**
     * 获取我的资讯
     *
     */
    public function getLifeData($type,$where,$page){
        if(isset($where['index_user_id'])){
            $user_id = $where['index_user_id'];
            unset($where['index_user_id']);
        }else{
            $user_id = $where['life_user_id'];
        }
        if($type == 4){
            $data = Db::table('ew_life')
                ->alias ('el')
                ->join('ew_life_type elt','el.life_type=elt.lt_id','left')
                ->where($where)
                ->field('el.life_id,life_message,life_new_type,life_zan,el.life_number,el.life_title,el.life_image,el.life_time,elt.lt_id,elt.lt_name')
                ->page($page,10)
                ->order("el.life_time desc")
                ->select();
        }else{
            $field = "user_id,user_image,user_username,life_new_type,el.life_id,el.life_price,life_message,life_zan,el.life_number,el.life_title,el.life_image,el.life_time";
//            if(isset($where['lat']) && isset($where['lon']) && $where['lat'] && $where['lon']){
//                $lat = $where['lat'];
//                $lon = $where['lon'];
//                unset($where['lat']);
//                unset($where['lon']);
//                $field .= ',ROUND(6378.138 * 2 * ASIN(SQRT(POW(SIN(('.$lat.'* PI() / 180 - life_lat * PI() / 180) / 2),2) + COS('.$lat.' * PI() / 180) * COS(life_lat * PI() / 180) * POW(SIN(('.$lon.' * PI() / 180 - life_lon * PI() / 180) / 2),2))) * 1000) AS distance';
//            }
            $field .= ',life_url,life_content,life_thing,life_address,u.district sheng,ua.district shi,uaa.district qu';
            $data = Db::table('ew_life')->alias ('el')
                ->join('ew_u_user uu','el.life_user_id=uu.user_id','left')
                ->join('ew_area u','el.life_sheng=u.district_id','LEFT')
                ->join('ew_area ua','el.life_shi=ua.district_id','LEFT')
                ->join('ew_area uaa','el.life_qu=uaa.district_id','LEFT')
                ->where($where)
                ->field($field)
                ->page($page,10)
                ->order("el.life_time desc")
                ->select();
        }

        $zandata = Db::table('ew_life_zan')->where('lz_user_id',$user_id)->column('lz_life_id');
        if($data){
            foreach ($data as $k=>$v){
                $data[$k]['zan'] = 1;//没有点赞
                if($v['life_image']){
                    $v['life_image'] = trim($v['life_image'],',');
                    $data[$k]['life_image'] = explode(',',$v['life_image']);
                }
                if($zandata){
                    if(in_array($v['life_id'],$zandata)){
                        $data[$k]['zan'] = 2;//已经点赞
                    }
                }
            }
        }
        return $data;
    }





    
    /** redis连接
     * @return bool
     */

    public function redis()
    {
        $options=redis::get('database');
        $redisHost=array_key_exists("redisHost",$options)?$options['redisHost']:"127.0.0.1";
        $redisPort=array_key_exists("redisPort",$options)?$options['redisPort']:6379;
        $redisAuth=array_key_exists("redisAuth",$options)?$options['redisAuth']:'';
        $redisHost=$redisHost==null?"127.0.0.1":$redisHost;
        $redisPort=$redisPort==null? 6379:$redisPort;
        if(extension_loaded("redis")){
            $redis= new \redis();
            if($redis->connect($redisHost,$redisPort)){
                if($redisAuth!=null){
                    $redis->auth($redisAuth);
                    if(false==$redis->set('ce',1)){
                        return false;
                    }
                }
               $this->redis=$redis;
                return true;
            }else{
                  return false;
                die;
                $tishi="redis连接失败原因IP地址连接有误";
                die($tishi);
            }

        }else{
            return false;
        }
    }

    /**
     * 全局设置
     * @param array $arr
     */
    public function setGlobalSettings($arr = []) {
        foreach ($arr as $name) {
            $config = Config::get(array("name" => $name));
            $this->assign($name, $config->value);
        }
    }

    /**
     * 个性设置
     * @param array $arr
     */
    public function setPersonalSettings($arr = []) {
        $loginSession = session('loginSession');
        $userid = $loginSession['id'];
        foreach ($arr as $name) {
            $personalConfig = Personalconfig::get(array("name" => $name, "userid" => $userid));
            if ($personalConfig) {
                $this->assign($name, $personalConfig->value);
            } else {
                $this->setGlobalSettings([$name]);
            }
        }
    }

    /**
     * 根据校区id区分数据显示
     */
    public function getDataByCampusid($arr = []) {
//为空是用来判断添加数据时要不要传参
//$str是专门用于获取数据(其他是campusid 校区管理是id) 针对校区管理 除了校区管理  其他功能不用传
        foreach ($arr as $key => $value) {
            if ($key == 'page') {
                unset($arr[$key]);
            } else if ($key == 'rows') {
                unset($arr[$key]);
            } else if ($value == '') {
                unset($arr[$key]);
            }  else if ($value == 'job_shi') {
               $arr[$key] = $value;
            } else {
                $arr[$key] = Array('like', '%' . $value . '%');
            }
        }

        return $arr;
    }

    /**
     * @param $type
     * @param $msg
     * @param $msg_encode
     * @param $data
     * @return mixed
     * 极光推送
     */
//    public function sendJpush($type,$msg,$msg_encode,$msg1,$data,$code1){
    public function sendJpush($token,$msg,$msg_data,$type,$tc=1){
        require_once 'jpush/autoload.php';
        $ji=array(
            'appKey'=>'a76796e479c786ee49c9c94e',
            'masterSecret'=>'a432ce71926d1125eda4fbe6',
        );
        $client = new \JPush\Client($ji['appKey'],$ji['masterSecret']);
        $push = $client->push();
        $push->setPlatform('all');
        //==================
        if($type==1){
            $push->addAlias($token);
        }else{
            $push->addAllAudience();
        }
        //==================
//        $push->addAlias($token);

        $push->iosNotification($msg, array(
                'alert'=>$msg,
                'badge' => '1',
                'extras' => $msg_data,
                'sound'=>'default'
            )
        );
        $push->androidNotification($msg, array(
            'badge' => '1',
            'extras' => $msg_data
        ));
        //6新农村,7大学生,8二手货,9涨知识
        $msg1 = "{tcid:$tc}";//1是职位的和忙友圈的,2是申请好友,6789是资讯的四个
        $push->message($msg1, [//透传
//            'title' => 'Hello',
            'content_type' => 'text',
//            'extras' => [
//                'key' => $code1
//            ]
        ]);
        return $push->send();
    }

    /**
     * 知道俩人的状态,是不是好友或其他状态
     * uid,user_id
     */
    function getFriendStatus($uid,$user_id){
        $who = 0;//不是你的好友
        $friend_id = 0;//申请的id
        if($uid == $user_id){
            $who = 6;//我自己
        }else{
            $mygood1 = Db::table('ew_friend')
                ->where('friend_user_id',$user_id)
                ->where('friend_good_user_id',$uid)
                ->find();
            $mygood2 = Db::table('ew_friend')
                ->where('friend_user_id',$uid)
                ->where('friend_good_user_id',$user_id)
                ->find();

            if($mygood1){
                $who = $mygood1['friend_status'];//对应相应的123
                $friend_id = $mygood1['friend_id'];//
            }
            if($mygood2){
                if($mygood2['friend_status'] == 1){$who = 1;}//已经同意是好友
                if($mygood2['friend_status'] == 2){$who = 4;}//你选择同意还是拒接
                if($mygood2['friend_status'] == 3){$who = 5;}//你已经拒绝了
                $friend_id = $mygood2['friend_id'];//只有同意或者拒绝的时候才有
            }
        }
        $data = array();
        $data['who'] = $who;
        $data['friend_id'] = $friend_id;
        return $data;
    }
    function fiveWho($i){
        $data = array('ok','已经是好友了','您已申请过','对方已拒绝','对方已申请加你','您已拒绝对方的好友申请','不能添加自己为好友');
        return $data[$i];
    }
    /**
     * 压缩图片
     * @param $imgsrc:原图片地址(完整的图片路径)
     * @param $imgdst:压缩后的图片地址,也是完整的
     */
    function image_png_size_add($imgsrc,$imgdst){
        list($width,$height,$type)=getimagesize($imgsrc);
        switch($type){
            case 1:
                break;
            case 2:
                header('Content-Type:image/jpeg');
                $image = imagecreatefromjpeg($imgsrc);
                imagejpeg($image, $imgdst,20);
                imagedestroy($image);
                break;
            case 3:
                header('Content-Type:image/png');
                $image = imagecreatefrompng($imgsrc);
                imagejpeg($image, $imgdst,20);
                imagedestroy($image);
                break;
        }
    }

    /**
     * 根据经纬度算出两地的距离
     * @param $lat1
     * @param $lng1
     * @param $lat2
     * @param $lng2
     * @return int
     */
    function getDistance($lat1, $lng1, $lat2, $lng2){
        //将角度转为狐度

        $radLat1=deg2rad($lat1);//deg2rad()函数将角度转换为弧度

        $radLat2=deg2rad($lat2);

        $radLng1=deg2rad($lng1);

        $radLng2=deg2rad($lng2);

        $a=$radLat1-$radLat2;

        $b=$radLng1-$radLng2;

        $s=2*asin(sqrt(pow(sin($a/2),2)+cos($radLat1)*cos($radLat2)*pow(sin($b/2),2)))*6378.137;

        $res = round($s*1000);
        if($res < 1000){
            return $res . 'm';
        }else{
            return round($res/1000,2) . 'km';
        }

    }


    /**
     * 筛选搜索条件不是like是=
     */
    public function searchNotLike($searchPath=[],$postArr=[],$one='',$two='',$three='') {
        if (isset($searchPath[$one]) && $one != '') {
            unset($searchPath[$one]);
            $searchPath[$one] = $postArr[$one];
        }
        if (isset($searchPath[$two]) && $two != '') {
            unset($searchPath[$two]);
            $searchPath[$two] = $postArr[$two];
        }
        if (isset($searchPath[$three]) && $three != '') {
            unset($searchPath[$three]);
            $searchPath[$three] = $postArr[$three];
        }
        return $searchPath;
    }

    /**
     * +----------------------------------------------------------
     * Export Excel | 2016.09.14
     * Author:ghostsf <ghostsf@163.com>
     * +----------------------------------------------------------
     * @param $expTitle     string File name
     * +----------------------------------------------------------
     * @param $expCellName  array  Column name
     * +----------------------------------------------------------
     * @param $expTableData array  Table data
     * +----------------------------------------------------------
     */
    public function exportExcel($expTitle, $expCellName, $expTableData) {
        $xlsTitle = iconv('utf-8', 'gb2312', $expTitle); //文件表名称
        $fileName = $xlsTitle . date('_YmdHis'); //文件名称
        $cellNum = count($expCellName);
        $dataNum = count($expTableData);
        vendor("phpoffice.phpexcel.Classes.PHPExcel");
        $objPHPExcel = new \PHPExcel();
        $cellName = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ');
//$objPHPExcel->getActiveSheet()->mergeCells('A1:' . $cellName[$cellNum - 1] . '1');//合并单元格
//$objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', $expTitle . '  Export time:' . date('Y-m-d H:i:s'));
        $objPHPExcel->getDefaultStyle()->getFont()->setName('微软雅黑');
        $objPHPExcel->getDefaultStyle()->getFont()->setSize(12);
        $objPHPExcel->getActiveSheet()->getStyle('1')->applyFromArray(
                array(
                    'font' => array(
                        'bold' => true
                    )
                )
        );
        for ($i = 0; $i < $cellNum; $i++) {
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($cellName[$i] . '1', $expCellName[$i][1]);
            $objPHPExcel->getActiveSheet()->getColumnDimension($cellName[$i])->setAutoSize(true);
        }
// Miscellaneous glyphs, UTF-8
        for ($i = 0; $i < $dataNum; $i++) {
            for ($j = 0; $j < $cellNum; $j++) {
                $objPHPExcel->getActiveSheet()->setCellValue($cellName[$j] . ($i + 2), $expTableData[$i][$expCellName[$j][0]]);
            }
        }
        header('pragma:public');
        header('Content-type:application/vnd.ms-excel;charset=utf-8;name="' . $xlsTitle . '.xls"');
        header("Content-Disposition:attachment;filename=$fileName.xls"); //attachment新窗口打印inline本窗口打印
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        exit;
    }

    /**
     * +----------------------------------------------------------
     * Import Excel | 2016.0914
     * Author:ghostsf <ghostsf@163.com>
     * +----------------------------------------------------------
     * @param  $file   upload file $_FILES
     * +----------------------------------------------------------
     * @return array   array("error","message")
     * +----------------------------------------------------------
     */
    public function read($filename,$encode='utf-8')
   {
          vendor("phpoffice.phpexcel.Classes.PHPExcel.IOFactory");
          $objReader = \PHPExcel_IOFactory::createReader('Excel5');

          $objReader->setReadDataOnly(true);

          $objPHPExcel = $objReader->load($filename);

          $objWorksheet = $objPHPExcel->getActiveSheet();

         $highestRow = $objWorksheet->getHighestRow();
         $highestColumn = $objWorksheet->getHighestColumn();
         $highestColumnIndex = \PHPExcel_Cell::columnIndexFromString($highestColumn);
         $excelData = array();
             for ($row = 1; $row <= $highestRow; $row++) {
             for ($col = 0; $col < $highestColumnIndex; $col++) {
                 $excelData[$row][] =(string)$objWorksheet->getCellByColumnAndRow($col, $row)->getValue();
           }
         }
      
        return $excelData;

    }
    //--------------------------------------------------融云群聊的操作------------------------------------------------
    //建群
    public function create($uids,$groupid,$name){
        $appKey = 'n19jmcy5n8l09';
        $appSecret = 'P8BCshr6wkp5T';
        $body = "{$uids}groupId=$groupid&groupName=$name";
        $nonce = mt_rand();
        $timeStamp = time();
        $sign = sha1($appSecret . $nonce . $timeStamp);
        $header = array(
            'App-Key:' . $appKey,
            'Nonce:' . $nonce,
            'Timestamp:' . $timeStamp,
            'Signature:' . $sign,
            'Content-Type: application/x-www-form-urlencoded'
        );
        $url = 'http://api.cn.ronghub.com/group/create.json';
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
//    curl_setopt($ch, CURLOPT_SSL_VERI/FYPEER, false);
//    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $result = curl_exec($ch);
        curl_close($ch);
        $res = json_decode($result, true);
        return $res;
    }

    //加入
    /**
     * @return mixed
     */
    public function joinin($uidstr,$groupid,$name)
    {
        $appKey = 'n19jmcy5n8l09';
        $appSecret = 'P8BCshr6wkp5T';
        $body = "{$uidstr}groupId=$groupid&groupName=$name";
        $nonce = mt_rand();
        $timeStamp = time();
        $sign = sha1($appSecret . $nonce . $timeStamp);
        $header = array(
            'App-Key:' . $appKey,
            'Nonce:' . $nonce,
            'Timestamp:' . $timeStamp,
            'Signature:' . $sign,
            'Content-Type: application/x-www-form-urlencoded'
        );
        $url = 'http://api.cn.ronghub.com/group/join.json';
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
//    curl_setopt($ch, CURLOPT_SSL_VERI/FYPEER, false);
//    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $result = curl_exec($ch);
        curl_close($ch);
        $res = json_decode($result, true);
        return $res;
    }

    //退出
    public function getout($uidstr,$groupid)
    {
        $appKey = 'n19jmcy5n8l09';
        $appSecret = 'P8BCshr6wkp5T';
        $body = "{$uidstr}groupId=$groupid";
        $nonce = mt_rand();
        $timeStamp = time();
        $sign = sha1($appSecret . $nonce . $timeStamp);
        $header = array(
            'App-Key:' . $appKey,
            'Nonce:' . $nonce,
            'Timestamp:' . $timeStamp,
            'Signature:' . $sign,
            'Content-Type: application/x-www-form-urlencoded'
        );
        $url = 'http://api.cn.ronghub.com/group/quit.json';
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
//    curl_setopt($ch, CURLOPT_SSL_VERI/FYPEER, false);
//    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $result = curl_exec($ch);
        curl_close($ch);
        $res = json_decode($result, true);
        return $res;
    }
    //退出
    public function kill($uid,$groupid)
    {
        $appKey = 'n19jmcy5n8l09';
        $appSecret = 'P8BCshr6wkp5T';
        $body = "userId=$uid&groupId=$groupid";
        $nonce = mt_rand();
        $timeStamp = time();
        $sign = sha1($appSecret . $nonce . $timeStamp);
        $header = array(
            'App-Key:' . $appKey,
            'Nonce:' . $nonce,
            'Timestamp:' . $timeStamp,
            'Signature:' . $sign,
            'Content-Type: application/x-www-form-urlencoded'
        );
        $url = 'http://api.cn.ronghub.com/group/dismiss.json';
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
//    curl_setopt($ch, CURLOPT_SSL_VERI/FYPEER, false);
//    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $result = curl_exec($ch);
        curl_close($ch);
        $res = json_decode($result, true);
        return $res;
    }

    //--------------------*************以下是微信支付相关************-----------------------------------
    public function WeChatPayReady($order){
        // 获取配置项
        $weixinpay_config=$this->config;
        $config=array(
            'appid'=>$weixinpay_config['APPID'],
            'mch_id'=>$weixinpay_config['MCHID'],
            'nonce_str'=>'test',
            'spbill_create_ip'=>$_SERVER['REMOTE_ADDR'],
            'notify_url'=>$weixinpay_config['NOTIFY_URL']
        );
        $type = 1;
        if(!empty($type)){
            $config['notify_url']='http://mms.mangmeshi.com/admin/Apiauth/huidiao';
        }
        // 合并配置数据和订单数据
        $data=array_merge($order,$config);

        // 生成签名
        $sign=$this->makeSign($data);
        $data['sign']=$sign;
        $xml=$this->toXml($data);
        $url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';//接收xml数据的文件
        $header[] = "Content-type: text/xml";//定义content-type为xml,注意是数组
        $ch = curl_init ($url);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);//严格校验
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
        $response = curl_exec($ch);
        if(curl_errno($ch)){
            print curl_error($ch);
        }
        curl_close($ch);
        $result=$this->toArray($response);
        $result['sign']=$sign;
        $result['nonce_str']='test';
        $result2 = $this->getOrder($result['prepay_id']);
        $res222['status'] = 200;
        $res222['msg'] = $result2;
        return $res222;
    }
    /**
     * 输出xml字符
     * @throws WxPayException
     **/
    public function toXml($data){
        //var_dump($data);
        if(!is_array($data) || count($data) <= 0){
            //throw new WxPayException("数组数据异常!");
        }
        $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;
    }

    /**
     * 生成签名
     * @return 签名,本函数不覆盖sign成员变量,如要设置签名需要调用SetSign方法赋值
     */
    public function makeSign($data){
        // 去空
        $data=array_filter($data);
        //签名步骤一:按字典序排序参数
        ksort($data);
        $string_a=http_build_query($data);
        $string_a=urldecode($string_a);
        //签名步骤二:在string后加入KEY
        $config=$this->config;
        $string_sign_temp=$string_a."&key=".$config['KEY'];
        //签名步骤三:MD5加密
        $sign = md5($string_sign_temp);
        // 签名步骤四:所有字符转为大写
        $result=strtoupper($sign);
        return $result;
    }

    /**
     * 将xml转为array
     * @param  string $xml xml字符串
     * @return array       转换得到的数组
     */
    public function toArray($xml){
        //禁止引用外部xml实体
        libxml_disable_entity_loader(true);
        $result= json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $result;
    }
    //执行第二次签名,才能返回给客户端使用
    public function getOrder($prepayId){
        $data["appid"] = $this->config["APPID"];
        $data["noncestr"] = $this->getRandChar(32);
        $data["package"] = "Sign=WXPay";
        $data["partnerid"] = $this->config['MCHID'];
        $data["prepayid"] = $prepayId;
        $data["timestamp"] = time();
        $s = $this->makeSign($data);
        $data["sign"] = $s;

        return $data;
    }
    //获取指定长度的随机字符串
    function getRandChar($length){
        $str = null;
        $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
        $max = strlen($strPol)-1;

        for($i=0;$i<$length;$i++){
            $str.=$strPol[rand(0,$max)];//rand($min,$max)生成介于min和max两个数之间的一个随机整数
        }

        return $str;
    }
    //-----------退款---------
    /**
     * 提现
     * 提现的这个如果是201也把状态改了
     * 查询的那个如果是200说明已经提现过了,拒绝的时候也要查询一下,200就把状态改了,防止数据出错
     */
    public function userTiXian($refundNo,$openid,$money){

//            $openid = 'ojZJn05cmFfzFmZl35-wU9_xXFow';
        $url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers";
        $data["mch_appid"] = $this->config['APPID'];//微信开放平台审核通过的应用APPID
        $data["mchid"] = $this->config['MCHID'];//商户号
        $data["nonce_str"] = $this->getRandChar(32);//随机字符串
        $data["partner_trade_no"] = $refundNo;
        $data["openid"] = $openid;
        $data["check_name"] = 'NO_CHECK';
        $data["amount"] = $money*100;
        $data["desc"] = '提现到账通知';
        $data["spbill_create_ip"] = $_SERVER['REMOTE_ADDR'];
        $sign = $this->makeSign($data);
        $data['sign'] = $sign;
        $xml = $this->toXml($data);
        $response = $this->postXmlCurl($xml, $url, '', true, '/appcert/apiclient_cert.pem', '/appcert/apiclient_key.pem');
        $responseArr = $this->toArray($response);
        if (!is_array($responseArr) || count($responseArr) <= 0) {
            $return['msg'] = '网络请求繁忙';
            $return['status'] = 0;
        } else if ($responseArr['return_code'] == 'FAIL') {
            $return['msg'] = $responseArr['return_msg'];
            $return['status'] = 0;
        } else {
            if ($responseArr['result_code'] == 'FAIL') {
                $return['msg'] = $responseArr['err_code_des'];
                $return['status'] = 0;
            } else {
                $return['text'] = $responseArr;
                $return['status'] = 200;
            }
        }
        return $return;
    }
    /**
     * 提现查询
     */
    public function tiXianChaXun($refundNo){
        $url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/gettransferinfo";
        $data["appid"] = $this->config['APPID'];//微信开放平台审核通过的应用APPID
        $data["mch_id"]       = $this->config['MCHID'];//商户号
        $data["nonce_str"]       = $this->getRandChar(32);//随机字符串
        $data["partner_trade_no"]   = $refundNo;
        $sign=$this->makeSign($data);
        $data['sign']=$sign;
        $xml=$this->toXml($data);
        $response     = $this->postXmlCurl($xml, $url,'',true,'/appcert/apiclient_cert.pem','/appcert/apiclient_key.pem');
        $responseArr=$this->toArray($response);
        if(!is_array($responseArr) || count($responseArr)<=0){
            $return['msg'] = '网络请求繁忙';
            $return['status'] = 0;
        }else if($responseArr['return_code'] == 'FAIL'){
            $return['msg'] = $responseArr['return_msg'];
            $return['status'] = 0;
        }else{
            if($responseArr['result_code'] == 'FAIL'){
                $return['msg'] = $responseArr['err_code_des'];
                $return['status'] = 0;
            }else{
                $return['text'] = $responseArr;
                $return['status'] = 200;
            }
        }
        return $return;
    }
    function postXmlCurl($xml, $url, $second=30, $useCert=false, $sslcert_path, $sslkey_path)
    {
        $ch = curl_init();
        //设置超时
        curl_setopt($ch, CURLOPT_TIMEOUT, $second);
        curl_setopt($ch,CURLOPT_URL, $url);

        //设置header
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        //要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);

        if($useCert == true){
            curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
            curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);
//            curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,TRUE);
//            curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,1);//严格校验
            //设置证书
            $path = $_SERVER['DOCUMENT_ROOT'];
            curl_setopt($ch,CURLOPT_SSLCERTTYPE,'PEM');
            curl_setopt($ch,CURLOPT_SSLCERT, $path.$sslcert_path);
            curl_setopt($ch,CURLOPT_SSLKEYTYPE,'PEM');
            curl_setopt($ch,CURLOPT_SSLKEY, $path.$sslkey_path);
//            curl_setopt($ch,CURLOPT_CAINFO, __DIR__.'/cert/rootca.pem');
        }
        //post提交方式
        curl_setopt($ch, CURLOPT_POST, TRUE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
        //运行curl
        $data = curl_exec($ch);
        //返回结果
        if($data){
            curl_close($ch);
            return $data;
        } else {
            $error = curl_errno($ch);
            curl_close($ch);
            return false;
        }
    }
}

标签: none

添加新评论