Index.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. <?php
  2. namespace addons\cos\controller;
  3. use app\common\exception\UploadException;
  4. use app\common\library\Upload;
  5. use app\common\model\Attachment;
  6. use Qcloud\Cos\Client;
  7. use Qcloud\Cos\Signature;
  8. use think\addons\Controller;
  9. use think\Config;
  10. /**
  11. * COS云储存
  12. *
  13. */
  14. class Index extends Controller
  15. {
  16. protected $cosConfig = [];
  17. public function _initialize()
  18. {
  19. //跨域检测
  20. check_cors_request();
  21. parent::_initialize();
  22. Config::set('default_return_type', 'json');
  23. $config = get_addon_config('cos');
  24. $this->cosConfig = array(
  25. 'region' => $config['region'],
  26. 'schema' => 'https', //协议头部,默认为http
  27. 'credentials' => array(
  28. 'secretId' => $config['secretId'],
  29. 'secretKey' => $config['secretKey']
  30. )
  31. );
  32. }
  33. public function index()
  34. {
  35. Config::set('default_return_type', 'html');
  36. $this->error("当前插件暂无前台页面");
  37. }
  38. public function params()
  39. {
  40. $this->check();
  41. $config = get_addon_config('cos');
  42. $name = $this->request->post('name');
  43. $md5 = $this->request->post('md5');
  44. $chunk = $this->request->post('chunk');
  45. $key = (new Upload())->getSavekey($config['savekey'], $name, $md5);
  46. $key = ltrim($key, "/");
  47. $params = [
  48. 'key' => $key,
  49. 'md5' => $md5
  50. ];
  51. if ($chunk) {
  52. $fileSize = $this->request->post('size');
  53. $oss = new Client($this->cosConfig);
  54. $result = $oss->createMultipartUpload(array(
  55. 'Bucket' => $config['bucket'],
  56. 'Key' => $key,
  57. ));
  58. $uploadId = $result['UploadId'];
  59. $sig = new Signature($config['secretId'], $config['secretKey']);
  60. $partSize = $this->request->post("chunksize");
  61. $i = 0;
  62. $size_count = $fileSize;
  63. $values = array();
  64. while ($size_count > 0) {
  65. $size_count -= $partSize;
  66. $values[] = array(
  67. $partSize * $i,
  68. ($size_count > 0) ? $partSize : ($size_count + $partSize),
  69. );
  70. $i++;
  71. }
  72. $params['key'] = $key;
  73. $params['uploadId'] = $uploadId;
  74. $params['partsAuthorization'] = [];
  75. $date = gmdate('D, d M Y H:i:s \G\M\T');
  76. foreach ($values as $index => $part) {
  77. $partNumber = $index + 1;
  78. $options = array(
  79. 'Bucket' => $config['bucket'],
  80. 'Key' => $key,
  81. 'UploadId' => $uploadId,
  82. 'PartNumber' => $partNumber,
  83. 'Body' => ''
  84. );
  85. $command = $oss->getCommand('uploadPart', $options);
  86. $request = $oss->commandToRequestTransformer($command);
  87. $authorization = $sig->createAuthorization($request);
  88. $params['partsAuthorization'][$index] = $authorization;
  89. }
  90. $params['date'] = $date;
  91. } else {
  92. if ($config['uploadmode'] == 'client') {
  93. $expiretime = time() + $config['expire'];
  94. $expiration = gmdate("Y-m-d\TH:i:s.414\Z", $expiretime);
  95. $keytime = (time() - 60) . ';' . $expiretime;
  96. $policy = json_encode([
  97. 'expiration' => $expiration,
  98. 'conditions' => [
  99. ['q-sign-algorithm' => 'sha1'],
  100. ['q-ak' => $config['secretId']],
  101. ['q-sign-time' => $keytime]
  102. ]
  103. ]);
  104. $signature = hash_hmac('sha1', sha1($policy), hash_hmac('sha1', $keytime, $config['secretKey']));
  105. $params = [
  106. 'key' => $key,
  107. 'policy' => base64_encode($policy),
  108. 'q-sign-algorithm' => 'sha1',
  109. 'q-ak' => $config['secretId'],
  110. 'q-key-time' => $keytime,
  111. 'q-sign-time' => $keytime,
  112. 'q-signature' => $signature
  113. ];
  114. }
  115. }
  116. $this->success('', null, $params);
  117. return;
  118. }
  119. /**
  120. * 服务器中转上传文件
  121. * 上传分片
  122. * 合并分片
  123. */
  124. public function upload()
  125. {
  126. $this->check();
  127. $config = get_addon_config('cos');
  128. $oss = new Client($this->cosConfig);
  129. //检测删除文件或附件
  130. $checkDeleteFile = function ($attachment, $upload, $force = false) use ($config) {
  131. //如果设定为不备份则删除文件和记录 或 强制删除
  132. if ((isset($config['serverbackup']) && !$config['serverbackup']) || $force) {
  133. if ($attachment && !empty($attachment['id'])) {
  134. $attachment->delete();
  135. }
  136. if ($upload) {
  137. //文件绝对路径
  138. $filePath = $upload->getFile()->getRealPath() ?: $upload->getFile()->getPathname();
  139. @unlink($filePath);
  140. }
  141. }
  142. };
  143. $chunkid = $this->request->post("chunkid");
  144. if ($chunkid) {
  145. $action = $this->request->post("action");
  146. $chunkindex = $this->request->post("chunkindex/d");
  147. $chunkcount = $this->request->post("chunkcount/d");
  148. $filesize = $this->request->post("filesize");
  149. $filename = $this->request->post("filename");
  150. $method = $this->request->method(true);
  151. $key = $this->request->post("key");
  152. $uploadId = $this->request->post("uploadId");
  153. if ($action == 'merge') {
  154. $attachment = null;
  155. $upload = null;
  156. //合并分片
  157. if ($config['uploadmode'] == 'server') {
  158. //合并分片文件
  159. try {
  160. $upload = new Upload();
  161. $attachment = $upload->merge($chunkid, $chunkcount, $filename);
  162. } catch (UploadException $e) {
  163. $this->error($e->getMessage());
  164. }
  165. }
  166. $etags = $this->request->post("etags/a", []);
  167. if (count($etags) != $chunkcount) {
  168. $checkDeleteFile($attachment, $upload, true);
  169. $this->error("分片数据错误");
  170. }
  171. $listParts = [];
  172. for ($i = 0; $i < $chunkcount; $i++) {
  173. $listParts[] = array("PartNumber" => $i + 1, "ETag" => $etags[$i]);
  174. }
  175. try {
  176. $result = $oss->completeMultipartUpload(array(
  177. 'Bucket' => $config['bucket'],
  178. 'Key' => $key,
  179. 'UploadId' => $uploadId,
  180. 'Parts' => $listParts
  181. )
  182. );
  183. } catch (\Exception $e) {
  184. $checkDeleteFile($attachment, $upload, true);
  185. $this->error($e->getMessage());
  186. }
  187. if (!isset($result['Key'])) {
  188. $checkDeleteFile($attachment, $upload, true);
  189. $this->error("上传失败");
  190. } else {
  191. $checkDeleteFile($attachment, $upload);
  192. $this->success("上传成功", '', ['url' => "/" . $key, 'fullurl' => cdnurl("/" . $key, true)]);
  193. }
  194. } else {
  195. //默认普通上传文件
  196. $file = $this->request->file('file');
  197. try {
  198. $upload = new Upload($file);
  199. $file = $upload->chunk($chunkid, $chunkindex, $chunkcount);
  200. } catch (UploadException $e) {
  201. $this->error($e->getMessage());
  202. }
  203. try {
  204. $params = array(
  205. 'Bucket' => $config['bucket'],
  206. 'Key' => $key,
  207. 'UploadId' => $uploadId,
  208. 'PartNumber' => $chunkindex + 1,
  209. 'Body' => $file->fread($file->getSize())
  210. );
  211. $ret = $oss->uploadPart($params);
  212. $etag = $ret['ETag'];
  213. } catch (\Exception $e) {
  214. $this->error($e->getMessage());
  215. }
  216. $this->success("上传成功", "", [], 3, ['ETag' => $etag]);
  217. }
  218. } else {
  219. $attachment = null;
  220. //默认普通上传文件
  221. $file = $this->request->file('file');
  222. try {
  223. $upload = new Upload($file);
  224. $attachment = $upload->upload();
  225. } catch (UploadException $e) {
  226. $this->error($e->getMessage());
  227. }
  228. //文件绝对路径
  229. $filePath = $upload->getFile()->getRealPath() ?: $upload->getFile()->getPathname();
  230. $url = $attachment->url;
  231. try {
  232. $ret = $oss->upload($config['bucket'], ltrim($attachment->url, "/"), $upload->getFile());
  233. //成功不做任何操作
  234. } catch (\Exception $e) {
  235. $checkDeleteFile($attachment, $upload, true);
  236. $this->error("上传失败");
  237. }
  238. $checkDeleteFile($attachment, $upload);
  239. $this->success("上传成功", '', ['url' => $url, 'fullurl' => cdnurl($url, true)]);
  240. }
  241. return;
  242. }
  243. /**
  244. * 回调
  245. */
  246. public function notify()
  247. {
  248. $this->check();
  249. $size = $this->request->post('size/d');
  250. $name = $this->request->post('name', '');
  251. $md5 = $this->request->post('md5', '');
  252. $type = $this->request->post('type', '');
  253. $url = $this->request->post('url', '');
  254. $width = $this->request->post('width/d');
  255. $height = $this->request->post('height/d');
  256. $category = $this->request->post('category', '');
  257. $category = array_key_exists($category, config('site.attachmentcategory') ?? []) ? $category : '';
  258. $suffix = substr($name, stripos($name, '.') + 1);
  259. $attachment = Attachment::where('url', $url)->where('storage', 'cos')->find();
  260. if (!$attachment) {
  261. $params = array(
  262. 'category' => $category,
  263. 'admin_id' => (int)session('admin.id'),
  264. 'user_id' => (int)cookie('uid'),
  265. 'filesize' => $size,
  266. 'filename' => $name,
  267. 'imagewidth' => $width,
  268. 'imageheight' => $height,
  269. 'imagetype' => $suffix,
  270. 'imageframes' => 0,
  271. 'mimetype' => $type,
  272. 'url' => $url,
  273. 'uploadtime' => time(),
  274. 'storage' => 'cos',
  275. 'sha1' => $md5,
  276. );
  277. Attachment::create($params);
  278. }
  279. $this->success();
  280. return;
  281. }
  282. /**
  283. * 检查签名是否正确或过期
  284. */
  285. protected function check()
  286. {
  287. $costoken = $this->request->post('costoken', '', 'trim');
  288. if (!$costoken) {
  289. $this->error("参数不正确");
  290. }
  291. $config = get_addon_config('cos');
  292. list($appId, $sign, $data) = explode(':', $costoken);
  293. if (!$appId || !$sign || !$data) {
  294. $this->error("参数不正确");
  295. }
  296. if ($appId !== $config['appId']) {
  297. $this->error("参数不正确");
  298. }
  299. if ($sign !== base64_encode(hash_hmac('sha1', base64_decode($data), $config['secretKey'], true))) {
  300. $this->error("签名不正确");
  301. }
  302. $json = json_decode(base64_decode($data), true);
  303. if ($json['deadline'] < time()) {
  304. $this->error("请求已经超时");
  305. }
  306. }
  307. }