Common.php 13.7 KB
<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\exception\UploadException;
use app\common\library\Upload;
use app\common\model\Area;
use app\common\model\Version;
use fast\Random;
use think\Config;
use think\Hook;
use think\Db;
use EasyWeChat\Factory;

/**
 * 公共接口
 */
class Common extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = '*';

    /**
     * 加载初始化
     *
     * @param string $version 版本号
     * @param string $lng 经度
     * @param string $lat 纬度
     */
    public function init()
    {
        if ($version = $this->request->request('version')) {
            $lng = $this->request->request('lng');
            $lat = $this->request->request('lat');

            //配置信息
            $upload = Config::get('upload');
            //如果非服务端中转模式需要修改为中转
            if ($upload['storage'] != 'local' && isset($upload['uploadmode']) && $upload['uploadmode'] != 'server') {
                //临时修改上传模式为服务端中转
                set_addon_config($upload['storage'], ["uploadmode" => "server"], false);

                $upload = \app\common\model\Config::upload();
                // 上传信息配置后
                Hook::listen("upload_config_init", $upload);

                $upload = Config::set('upload', array_merge(Config::get('upload'), $upload));
            }

            $upload['cdnurl'] = $upload['cdnurl'] ? $upload['cdnurl'] : cdnurl('', true);
            $upload['uploadurl'] = preg_match("/^((?:[a-z]+:)?\/\/)(.*)/i", $upload['uploadurl']) ? $upload['uploadurl'] : url($upload['storage'] == 'local' ? '/api/common/upload' : $upload['uploadurl'], '', false, true);

            $content = [
                'citydata' => Area::getCityFromLngLat($lng, $lat),
                'versiondata' => Version::check($version),
                'uploaddata' => $upload,
                'coverdata' => Config::get("cover"),
            ];
            $this->success('', $content);
        } else {
            $this->error(__('Invalid parameters'));
        }
    }

    /**
     * 上传文件
     * @ApiMethod (POST)
     * @param File $file 文件流
     */
    public function upload()
    {
        Config::set('default_return_type', 'json');
        //必须设定cdnurl为空,否则cdnurl函数计算错误
        Config::set('upload.cdnurl', '');
        $chunkid = $this->request->post("chunkid");
        if ($chunkid) {
            if (!Config::get('upload.chunking')) {
                $this->error(__('Chunk file disabled'));
            }
            $action = $this->request->post("action");
            $chunkindex = $this->request->post("chunkindex/d");
            $chunkcount = $this->request->post("chunkcount/d");
            $filename = $this->request->post("filename");
            $method = $this->request->method(true);
            if ($action == 'merge') {
                $attachment = null;
                //合并分片文件
                try {
                    $upload = new Upload();
                    $attachment = $upload->merge($chunkid, $chunkcount, $filename);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                $this->success(__('Uploaded successful'), ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true)]);
            } elseif ($method == 'clean') {
                //删除冗余的分片文件
                try {
                    $upload = new Upload();
                    $upload->clean($chunkid);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                $this->success();
            } else {
                //上传分片文件
                //默认普通上传文件
                $file = $this->request->file('file');
                try {
                    $upload = new Upload($file);
                    $upload->chunk($chunkid, $chunkindex, $chunkcount);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                $this->success();
            }
        } else {
            $attachment = null;
            //默认普通上传文件
            $file = $this->request->file('file');
            try {
                $upload = new Upload($file);
                $attachment = $upload->upload();
            } catch (UploadException $e) {
                $this->error($e->getMessage());
            }

            $this->success(__('Uploaded successful'), ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true)]);
        }

    }

    public function ceshi()
    {
        $list = $this->WhereDayOk(0);
        dump($list);
    }

    public function Today()
    {
        $this->success('成功', date("Y-m-d"));
    }


    //启动页
    public function OpenPages()
    {
        $param = $this->request->param();
//        授权登录
        $ch = curl_init();
        $appid = "wx7ca302bae633e3a1";
        $secret = "80f070e671749811bdf38e6019d173a6";
        $code = $param['code'];
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$secret&js_code=$code&grant_type=authorization_code";
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        $output = curl_exec($ch);
        if ($output === FALSE) {
            echo "CURL Error:" . curl_error($ch);
        }
        curl_close($ch);
        $curl_result = json_decode($output, true);
        $openid = $curl_result['openid'];
        $UserInfo = Db::name('user')->where('openid', $openid)->find();
        if (empty($UserInfo)) {
            $IsSQL = 0;
            $TodayIsDiary = 0;
            $IsDiary = 0;
            $token = '';
            $Nickname = '';
            $Avatar = '';
        } else {
            $beginToday = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
            $endToday = mktime(0, 0, 0, date('m'), date('d') + 1, date('Y')) - 1;
            $map['createtime'] = ['between', [$beginToday, $endToday]];
            $IsUserInfoArr = Db::name('diary')->where('user_id', $UserInfo['id'])->where('isdelete', 0)->find();
            $IsTodayDiaryArr = Db::name('diary')->where('user_id', $UserInfo['id'])->where($map)->where('isdelete', 0)->find();
            //更新Token
            $token = $this->request->token();
            $UpdateToken = Db::name('user')->where('openid', $openid)->update(['token' => $token]);
            if (!$UpdateToken) {
                $this->error('token更新失败', 0);
            }
            $IsSQL = 1;
            if (empty($IsUserInfoArr)) {
                $IsDiary = 0;
            } else {
                $IsDiary = 1;
            }
            if (empty($IsTodayDiaryArr)) {
                $TodayIsDiary = 0;
            } else {
                $TodayIsDiary = 1;
            }
            $Avatar = $UserInfo['avatar'];
            $Nickname = $UserInfo['nickname'];
        }
        $data = [
            'IsSQL' => $IsSQL, //是否入库
            'IsDiary' => $IsDiary, //是否写过日记
            'TodayIsDiary' => $TodayIsDiary,  //今天是否写过日记
            'Token' => $token, //token
            'Nickname' => $Nickname,
            'Avatar' => $Avatar,
        ];
        $this->success('成功', $data);
    }

//订阅消息允许
    public function IsWechatOpen()
    {
        $UserId = $this->is_token($this->request->header());
        $res = Db::name('user')->where('id', $UserId)->update(['isUp' => 1, 'updatetime' => time()]);
        $this->res($res);
    }


    public function ceshi11()
    {
        $UserInfo = Db::name('user')->where('isUp', 1)->find();
        dump($UserInfo);
        $data = [
            'thing7' => ['value' => $UserInfo['nickname']],
            'thing3' => ['value' => '今天还没有写日记哦']
        ];
        $res = $this->sendSubMessage($data, $UserInfo['openid'], $tmpl = "2XAC5381IIOZZJKbvRZtbaFjfuWf9p3GmeaWfUQB3FU");
        Db::name('user')->where('id', $UserInfo['id'])->update(['isUp' => 0]);
        dump($res);
    }

    //小程序订阅消息定时任务
    public function WechatModel()
    {
        $UserInfo = Db::name('user')->where('isUp', 1)->select();
        if (!empty($UserInfo)) {
            foreach ($UserInfo as $k => $v) {
                //当日时间戳
                $start_time = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
                $end_time = mktime(0, 0, 0, date('m'), date('d') + 1, date('Y')) - 1;
                $map['createtime'] = ['between', [$start_time, $end_time]];

                $Diary = Db::name('diary')->where('user_id', $v['id'])->where($map)->find();
                if (empty($Diary)) {
                    $data = [
                        'thing7' => ['value' => $v['nickname']],
                        'thing3' => ['value' => '今天还没有写日记哦']
                    ];
                    $this->sendSubMessage($data, $v['openid'], $tmpl = "2XAC5381IIOZZJKbvRZtbaFjfuWf9p3GmeaWfUQB3FU");
                    Db::name('user')->where('id', $v['id'])->update(['isUp' => 0]);
                }
            }
        }
    }

    public function sendSubMessage($data, $openId = "openId", $tmpl = "2XAC5381IIOZZJKbvRZtbaFjfuWf9p3GmeaWfUQB3FU")
    {
        $params['touser'] = $openId;
        $params['template_id'] = $tmpl;
        $params['page'] = "/pages/index/index";
        $params['data'] = $data;

        $appId = 'wx7ca302bae633e3a1';
        $secret = '80f070e671749811bdf38e6019d173a6';
        $config = [
            'app_id' => $appId,
            'secret' => $secret,
        ];
        $app = new \EasyWeChat\Foundation\Application($config);
        $accessToken = $app->access_token;
        $AccessToken = $accessToken->getToken();
        $url = 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=' . $AccessToken;
        return $this->curlPost1($url, $params);
    }

    public function curlPost1($url, $data)
    {
        $ch = curl_init();
        $postJosnData = json_encode($data);
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postJosnData);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        $data = curl_exec($ch);
        return $data;
    }

    //删除今天日记
    public function DeletyeTodayDidry()
    {
        $Time = strtotime('2020-11-12');
        $res = Db::name('diary')->where('user_id', 13)->where('createtime', '>', $Time)->delete();
        if ($res) {
            echo '成功';
        } else {
            echo '今天无日记';
        }
    }

    //日记方法
//    public function SqlInserEncode()
//    {
//        $aRR = Db::name('diary')->select();
//        foreach ($aRR as $k => $v) {
//            $res = Db::name('diary')->where('id', $v['id'])->update(
//                [
//                    'content' => base64_encode($v['content']),
//                    'con' => base64_encode($v['con']),
//                ]
//            );
//            if (!$res) {
//                $this->error('失败', $v['id']);
//            }
//        }
//    }


//用户是否订阅
    public function UserWechatMiniAppMessage()
    {
        $UserId = $this->is_token($this->request->header());
        $IsUp = Db::name('user')->where('id', $UserId)->value('isUp');
        $this->success('成功', $IsUp);
    }


    //delete
    public function echo()
    {
        $start_time = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
        $end_time = mktime(0, 0, 0, date('m'), date('d') + 1, date('Y')) - 1;
        echo $start_time;
        echo $end_time;
    }

    public function sport($person)
    {
        $newArr = array();
        foreach ($person as $key => $v) {
            $newArr[$key]['num'] = $v['num'];
        }
        array_multisort($newArr, SORT_DESC, $person);//SORT_DESC为降序,SORT_ASC为升序
        return $person;
    }

    /*排序定时任务A 根据篇数排序*/
    public function SportA()
    {
        //清空表数据
        Db::name('sport_a')->where('id', '>', 0)->delete();
        $Array = Db::name('user')->select();
        foreach ($Array as $k => $v) {
            $DiaryCount = Db::name('diary')->where('user_id', $v['id'])->select();
            $List[$k]['user_id'] = $v['id'];
            $List[$k]['num'] = count($DiaryCount);
        }
        $Sport_List = $this->sport($List);
        foreach ($Sport_List as $k => $v) {
            $data = [
                'user_id' => $v['user_id'],
                'num' => $v['num'],
                'createtime' => time()
            ];
            Db::name('sport_a')->insert($data);
        }
    }

    /*排序定时任务B 根据天数排序*/
    public function SportB()
    {
        //清空表数据
        Db::name('sport_b')->where('id', '>', 0)->delete();
        $Array = Db::name('user')->select();
        foreach ($Array as $k => $v) {
            $DiaryCount = Db::name('diary')->where('user_id', $v['id'])->select();
            $List[$k]['user_id'] = $v['id'];
            $List[$k]['num'] = count($this->second_array_unique_bykey($DiaryCount, 'createtime'));
        }
        $Sport_List = $this->sport($List);
        foreach ($Sport_List as $k => $v) {
            $data = [
                'user_id' => $v['user_id'],
                'num' => $v['num'],
                'createtime' => time()
            ];
            Db::name('sport_b')->insert($data);
        }
    }
}