审查视图

application/api/controller/Common.php 6.8 KB
wangzhi authored
1 2 3 4 5 6 7 8 9
<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\Area;
use app\common\model\Version;
use fast\Random;
use think\Config;
wangzhi authored
10 11
use app\common\model\Attachment;
use addons\qiniu\library\Auth;
wangzhi authored
12
use think\Db;
wangzhi authored
13
wangzhi authored
14 15 16 17 18
/**
 * 公共接口
 */
class Common extends Api
{
wangzhi authored
19
    protected $noNeedLogin = ['*'];
wangzhi authored
20 21 22 23 24 25
    protected $noNeedRight = '*';

    /**
     * 加载初始化
     *
     * @param string $version 版本号
wangzhi authored
26 27
     * @param string $lng 经度
     * @param string $lat 纬度
wangzhi authored
28 29 30 31 32 33 34
     */
    public function init()
    {
        if ($version = $this->request->request('version')) {
            $lng = $this->request->request('lng');
            $lat = $this->request->request('lat');
            $content = [
wangzhi authored
35
                'citydata' => Area::getCityFromLngLat($lng, $lat),
wangzhi authored
36
                'versiondata' => Version::check($version),
wangzhi authored
37 38
                'uploaddata' => Config::get('upload'),
                'coverdata' => Config::get("cover"),
wangzhi authored
39 40 41 42 43 44 45 46
            ];
            $this->success('', $content);
        } else {
            $this->error(__('Invalid parameters'));
        }
    }

    /**
wangzhi authored
47 48 49 50 51 52
     * 上传文件-七牛
     *
     * @ApiTitle    (上传文件-七牛)
     * @ApiSummary  (测试描述信息)
     * @ApiMethod   (POST)
     * @ApiParams   (name="file", type="file", required=true, description="用户名")
wangzhi authored
53
     */
wangzhi authored
54
    public function uploadQiniu()
wangzhi authored
55
    {
wangzhi authored
56
//        Config::set('default_return_type', 'json');
wangzhi authored
57 58 59 60 61 62 63 64 65 66 67
//        $token = $this->request->header();
//        if (empty($token['token'])) {
//            $this->error('请登陆后再操作!', '', '9');
//        }
//        $token_model = new UserToken();
//        $user_id = $token_model::get(['token' => $token['token']]);
//        if (!$user_id) {
//            $this->error('Token不存在', '', '8');
//        }
        $config = get_addon_config('qiniu');
wangzhi authored
68
        $file = $this->request->file('file');
wangzhi authored
69 70
        if (!$file || !$file->isValid()) {
            $this->error("请上传有效的文件");
wangzhi authored
71
        }
wangzhi authored
72
        $fileInfo = $file->getInfo();
wangzhi authored
73
wangzhi authored
74 75
        $filePath = $file->getRealPath() ?: $file->getPathname();
        preg_match('/(\d+)(\w+)/', $config['maxsize'], $matches);
wangzhi authored
76 77
        $type = strtolower($matches[2]);
        $typeDict = ['b' => 0, 'k' => 1, 'kb' => 1, 'm' => 2, 'mb' => 2, 'gb' => 3, 'g' => 3];
wangzhi authored
78 79
        $size = (int)$config['maxsize'] * pow(1024, isset($typeDict[$type]) ? $typeDict[$type] : 0);
wangzhi authored
80
        $suffix = strtolower(pathinfo($fileInfo['name'], PATHINFO_EXTENSION));
wangzhi authored
81
        $suffix = $suffix ? $suffix : 'file';
wangzhi authored
82
wangzhi authored
83 84 85 86 87 88
        $md5 = md5_file($filePath);
        $search = ['$(year)', '$(mon)', '$(day)', '$(etag)', '$(ext)'];
        $replace = [date("Y"), date("m"), date("d"), $md5, '.' . $suffix];
        $object = ltrim(str_replace($search, $replace, $config['savekey']), '/');

        $mimetypeArr = explode(',', strtolower($config['mimetype']));
wangzhi authored
89 90
        $typeArr = explode('/', $fileInfo['type']);
wangzhi authored
91 92 93
        //检查文件大小
        if (!$file->checkSize($size)) {
            $this->error("起过最大可上传文件限制");
wangzhi authored
94
        }
wangzhi authored
95
wangzhi authored
96
        //验证文件后缀
wangzhi authored
97
        if ($config['mimetype'] !== '*' &&
wangzhi authored
98 99
            (
                !in_array($suffix, $mimetypeArr)
wangzhi authored
100
                || (stripos($typeArr[0] . '/', $config['mimetype']) !== false && (!in_array($fileInfo['type'], $mimetypeArr) && !in_array($typeArr[0] . '/*', $mimetypeArr)))
wangzhi authored
101 102
            )
        ) {
wangzhi authored
103
            $this->error(__('上传格式限制'));
wangzhi authored
104
        }
wangzhi authored
105 106

        $savekey = '/' . $object;
wangzhi authored
107 108 109

        $uploadDir = substr($savekey, 0, strripos($savekey, '/') + 1);
        $fileName = substr($savekey, strripos($savekey, '/') + 1);
wangzhi authored
110 111
        //先上传到本地
        $splInfo = $file->move(ROOT_PATH . '/public' . $uploadDir, $fileName);
wangzhi authored
112
        if ($splInfo) {
wangzhi authored
113 114 115 116 117
            $extparam = $this->request->post();
            $filePath = $splInfo->getRealPath() ?: $splInfo->getPathname();

            $sha1 = sha1_file($filePath);
            $imagewidth = $imageheight = 0;
wangzhi authored
118
            if (in_array($suffix, ['gif', 'jpg', 'jpeg', 'bmp', 'png', 'swf', 'pdf'])) {
wangzhi authored
119 120 121 122
                $imgInfo = getimagesize($splInfo->getPathname());
                $imagewidth = isset($imgInfo[0]) ? $imgInfo[0] : $imagewidth;
                $imageheight = isset($imgInfo[1]) ? $imgInfo[1] : $imageheight;
            }
wangzhi authored
123
            $params = array(
wangzhi authored
124 125 126 127
                'admin_id' => session('admin.id'),
                'user_id' => $this->auth->id,
                'filesize' => $fileInfo['size'],
                'imagewidth' => $imagewidth,
wangzhi authored
128
                'imageheight' => $imageheight,
wangzhi authored
129
                'imagetype' => $suffix,
wangzhi authored
130
                'imageframes' => 0,
wangzhi authored
131 132 133 134 135 136
                'mimetype' => $fileInfo['type'],
                'url' => $uploadDir . $splInfo->getSaveName(),
                'uploadtime' => time(),
                'storage' => 'local',
                'sha1' => $sha1,
                'extparam' => json_encode($extparam),
wangzhi authored
137
            );
wangzhi authored
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
            $attachment = Attachment::create(array_filter($params), true);
            $policy = array(
                'saveKey' => ltrim($savekey, '/'),
            );
            $auth = new Auth($config['app_key'], $config['secret_key']);
            $token = $auth->uploadToken($config['bucket'], null, $config['expire'], $policy);
            $multipart = [
                ['name' => 'token', 'contents' => $token],
                [
                    'name' => 'file',
                    'contents' => fopen($filePath, 'r'),
                    'filename' => $fileName,
                ]
            ];
            try {
                $client = new \GuzzleHttp\Client();
                $res = $client->request('POST', $config['uploadurl'], [
                    'multipart' => $multipart
                ]);
                $code = $res->getStatusCode();
                //成功不做任何操作
            } catch (\GuzzleHttp\Exception\ClientException $e) {
                $attachment->delete();
                unlink($filePath);
                $this->error("上传失败");
            }

            $url = '/' . $object;

            //上传成功后将存储变更为qiniu
            $attachment->storage = 'qiniu';
wangzhi authored
169
            $attachment->save();
wangzhi authored
170
            $this->success("上传成功", $url);
wangzhi authored
171
        } else {
wangzhi authored
172
            $this->error('上传失败');
wangzhi authored
173
        }
wangzhi authored
174
        return;
wangzhi authored
175
    }
wangzhi authored
176 177 178 179 180


    //每天清空日搜索
    public function delete_day_so()
    {
wangzhi authored
181 182
        $map = [];
        $beginToday = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
wangzhi authored
183
        $map['createtime'] = array('LT', $beginToday);
wangzhi authored
184
        Db::name('so_level_day')->where($map)->delete();
wangzhi authored
185 186 187 188 189

    }
    //每周清空周搜索
    public function delete_month_so()
    {
wangzhi authored
190 191 192 193
        $map2 = [];
        $beginWeek = mktime(0, 0, 0, date("m"), date("d") - date("w") + 1, date("Y"));
        $map2['createtime'] = array('LT', $beginWeek);
        Db::name('so_level_month')->where($map2)->delete();
wangzhi authored
194
    }
wangzhi authored
195
}