审查视图

addons/qiniu/controller/Index.php 8.4 KB
李忠强 authored
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 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 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231
<?php

namespace addons\qiniu\controller;

use app\common\exception\UploadException;
use app\common\library\Upload;
use app\common\model\Attachment;
use Qiniu\Auth;
use Qiniu\Storage\ResumeUploader;
use Qiniu\Storage\UploadManager;
use think\addons\Controller;
use think\Config;

/**
 * 七牛管理
 *
 */
class Index extends Controller
{

    public function _initialize()
    {
        //跨域检测
        check_cors_request();

        parent::_initialize();
        Config::set('default_return_type', 'json');
    }

    public function index()
    {
        Config::set('default_return_type', 'html');
        $this->error("当前插件暂无前台页面");
    }

    /**
     * 中转上传文件
     * 上传分片
     * 合并分片
     */
    public function upload()
    {
        Config::set('default_return_type', 'json');

        $this->check();
        $config = get_addon_config('qiniu');
        $config['savekey'] = str_replace(['{year}', '{mon}', '{day}', '{filemd5}', '{.suffix}'], ['$(year)', '$(mon)', '$(day)', '$(etag)', '$(ext)'], $config['savekey']);

        // 构建鉴权对象
        $auth = new Auth($config['accessKey'], $config['secretKey']);
        // 生成上传 Token
        $token = $auth->uploadToken($config['bucket'], null, 3600, ['saveKey' => ltrim($config['savekey'], '/')]);
        // 初始化 UploadManager 对象并进行文件的上传。
        $uploadMgr = new UploadManager();

        //检测删除文件或附件
        $checkDeleteFile = function ($attachment, $upload, $force = false) use ($config) {
            //如果设定为不备份则删除文件和记录 或 强制删除
            if ((isset($config['serverbackup']) && !$config['serverbackup']) || $force) {
                if ($attachment && !empty($attachment['id'])) {
                    $attachment->delete();
                }
                if ($upload) {
                    //文件绝对路径
                    $filePath = $upload->getFile()->getRealPath() ?: $upload->getFile()->getPathname();
                    @unlink($filePath);
                }
            }
        };

        $chunkid = $this->request->post("chunkid");
        if ($chunkid) {
            $action = $this->request->post("action");
            $chunkindex = $this->request->post("chunkindex/d");
            $chunkcount = $this->request->post("chunkcount/d");
            $filesize = $this->request->post("filesize");
            $filename = $this->request->post("filename");
            if ($action == 'merge') {
                $attachment = null;
                $upload = null;
                if ($config['uploadmode'] == 'server') {
                    //合并分片文件
                    try {
                        $upload = new Upload();
                        $attachment = $upload->merge($chunkid, $chunkcount, $filename);
                    } catch (UploadException $e) {
                        $this->error($e->getMessage());
                    }
                }

                $contexts = $this->request->post("contexts/a", []);
                $uploader = new ResumeUploader($token, null, null, $filesize);
                list($ret, $err) = $uploader->setContexts($contexts)->makeFile($filename);
                if ($err !== null) {
                    $checkDeleteFile($attachment, $upload, true);
                    $this->error("上传失败");
                } else {
                    $checkDeleteFile($attachment, $upload);
                    $this->success("上传成功", '', ['url' => '/' . $ret['key'], 'fullurl' => cdnurl('/' . $ret['key'], true), 'hash' => $ret['hash']]);
                }
            } else {
                //默认普通上传文件
                $file = $this->request->file('file');
                try {
                    $upload = new Upload($file);
                    $file = $upload->chunk($chunkid, $chunkindex, $chunkcount);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }

                //上传分片文件
                //$file = $this->request->file('file');
                $filesize = $file->getSize();
                //合并分片文件
                $uploader = new ResumeUploader($token, null, fopen($file->getRealPath(), 'rb'), $filesize);
                $ret = $uploader->uploadChunk($chunkindex, $file, $filesize);
                $this->success("上传成功", "", $ret);
            }
        } else {
            $attachment = null;
            //默认普通上传文件
            $file = $this->request->file('file');
            try {
                $upload = new Upload($file);

                $suffix = $upload->getSuffix();
                $md5 = md5_file($file->getRealPath());
                $search = ['$(year)', '$(mon)', '$(day)', '$(etag)', '$(ext)'];
                $replace = [date("Y"), date("m"), date("d"), $md5, '.' . $suffix];
                $savekey = ltrim(str_replace($search, $replace, $config['savekey']), '/');

                $attachment = $upload->upload($savekey);
            } catch (UploadException $e) {
                $this->error($e->getMessage());
            }

            //文件绝对路径
            $filePath = $upload->getFile()->getRealPath() ?: $upload->getFile()->getPathname();

            //上传到七牛后保存的文件名
            $saveKey = ltrim($attachment->url, '/');

            $url = $attachment->url;

            try {
                // 调用 UploadManager 的 putFile 方法进行文件的上传。
                list($ret, $err) = $uploadMgr->putFile($token, $saveKey, $filePath);

                if ($err !== null) {
                    throw new \Exception("上传失败");
                }
                //成功不做任何操作
            } catch (\Exception $e) {
                $checkDeleteFile($attachment, $upload, true);
                $this->error("上传失败");
            }
            $hash = md5_file($filePath);
            $checkDeleteFile($attachment, $upload);

            $this->success("上传成功", '', ['url' => $url, 'fullurl' => cdnurl($url, true), 'hash' => $hash]);
        }
    }

    /**
     * 通知回调
     */
    public function notify()
    {
        Config::set('default_return_type', 'json');

        $this->check();

        $size = $this->request->post('size/d');
        $name = $this->request->post('name', '');
        $hash = $this->request->post('hash', '');
        $type = $this->request->post('type', '');
        $url = $this->request->post('url', '');
        $width = $this->request->post('width/d');
        $height = $this->request->post('height/d');
        $category = $this->request->post('category', '');
        $suffix = substr($name, stripos($name, '.') + 1);
        $attachment = Attachment::where('url', $url)->where('storage', 'qiniu')->find();
        if (!$attachment) {
            $params = array(
                'category'    => $category,
                'admin_id'    => (int)session('admin.id'),
                'user_id'     => (int)cookie('uid'),
                'filename'    => $name,
                'filesize'    => $size,
                'imagewidth'  => $width,
                'imageheight' => $height,
                'imagetype'   => $suffix,
                'imageframes' => 0,
                'mimetype'    => $type,
                'url'         => $url,
                'uploadtime'  => time(),
                'storage'     => 'qiniu',
                'sha1'        => $hash,
            );
            Attachment::create($params);
        }
        $this->success();
    }

    /**
     * 检查签名是否正确或过期
     */
    protected function check()
    {
        $qiniutoken = $this->request->post('qiniutoken', $this->request->server('AUTHORIZATION'), 'trim');
        if (!$qiniutoken) {
            $this->error("参数不正确");
        }
        $config = get_addon_config('qiniu');
        $auth = new Auth($config['accessKey'], $config['secretKey']);
        list($accessKey, $sign, $data) = explode(':', $qiniutoken);
        if (!$accessKey || !$sign || !$data) {
            $this->error("参数不正确");
        }
        if ($accessKey !== $config['accessKey']) {
            $this->error("参数不正确");
        }
        if ($accessKey . ':' . $sign !== $auth->sign($data)) {
            $this->error("签名不正确");
        }
        $json = json_decode(\Qiniu\base64_urlSafeDecode($data), true);
        if ($json['deadline'] < time()) {
            $this->error("请求已经超时");
        }
    }
}