Index.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  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. * @param bool $isApi
  124. */
  125. public function upload($isApi = false)
  126. {
  127. if ($isApi === true) {
  128. if (!$this->auth->isLogin()) {
  129. $this->error("请登录后再进行操作");
  130. }
  131. } else {
  132. $this->check();
  133. }
  134. $config = get_addon_config('cos');
  135. $oss = new Client($this->cosConfig);
  136. //检测删除文件或附件
  137. $checkDeleteFile = function ($attachment, $upload, $force = false) use ($config) {
  138. //如果设定为不备份则删除文件和记录 或 强制删除
  139. if ((isset($config['serverbackup']) && !$config['serverbackup']) || $force) {
  140. if ($attachment && !empty($attachment['id'])) {
  141. $attachment->delete();
  142. }
  143. if ($upload) {
  144. //文件绝对路径
  145. $filePath = $upload->getFile()->getRealPath() ?: $upload->getFile()->getPathname();
  146. @unlink($filePath);
  147. }
  148. }
  149. };
  150. $chunkid = $this->request->post("chunkid");
  151. if ($chunkid) {
  152. $action = $this->request->post("action");
  153. $chunkindex = $this->request->post("chunkindex/d");
  154. $chunkcount = $this->request->post("chunkcount/d");
  155. $filesize = $this->request->post("filesize");
  156. $filename = $this->request->post("filename");
  157. $method = $this->request->method(true);
  158. $key = $this->request->post("key");
  159. $uploadId = $this->request->post("uploadId");
  160. if ($action == 'merge') {
  161. $attachment = null;
  162. $upload = null;
  163. //合并分片
  164. if ($config['uploadmode'] == 'server') {
  165. //合并分片文件
  166. try {
  167. $upload = new Upload();
  168. $attachment = $upload->merge($chunkid, $chunkcount, $filename);
  169. } catch (UploadException $e) {
  170. $this->error($e->getMessage());
  171. }
  172. }
  173. $etags = $this->request->post("etags/a", []);
  174. if (count($etags) != $chunkcount) {
  175. $checkDeleteFile($attachment, $upload, true);
  176. $this->error("分片数据错误");
  177. }
  178. $listParts = [];
  179. for ($i = 0; $i < $chunkcount; $i++) {
  180. $listParts[] = array("PartNumber" => $i + 1, "ETag" => $etags[$i]);
  181. }
  182. try {
  183. $result = $oss->completeMultipartUpload(array(
  184. 'Bucket' => $config['bucket'],
  185. 'Key' => $key,
  186. 'UploadId' => $uploadId,
  187. 'Parts' => $listParts
  188. )
  189. );
  190. } catch (\Exception $e) {
  191. $checkDeleteFile($attachment, $upload, true);
  192. $this->error($e->getMessage());
  193. }
  194. if (!isset($result['Key'])) {
  195. $checkDeleteFile($attachment, $upload, true);
  196. $this->error("上传失败");
  197. } else {
  198. $checkDeleteFile($attachment, $upload);
  199. $this->success("上传成功", '', ['url' => "/" . $key, 'fullurl' => cdnurl("/" . $key, true)]);
  200. }
  201. } else {
  202. //默认普通上传文件
  203. $file = $this->request->file('file');
  204. try {
  205. $upload = new Upload($file);
  206. $file = $upload->chunk($chunkid, $chunkindex, $chunkcount);
  207. } catch (UploadException $e) {
  208. $this->error($e->getMessage());
  209. }
  210. try {
  211. $params = array(
  212. 'Bucket' => $config['bucket'],
  213. 'Key' => $key,
  214. 'UploadId' => $uploadId,
  215. 'PartNumber' => $chunkindex + 1,
  216. 'Body' => $file->fread($file->getSize())
  217. );
  218. $ret = $oss->uploadPart($params);
  219. $etag = $ret['ETag'];
  220. } catch (\Exception $e) {
  221. $this->error($e->getMessage());
  222. }
  223. $this->success("上传成功", "", [], 3, ['ETag' => $etag]);
  224. }
  225. } else {
  226. $attachment = null;
  227. //默认普通上传文件
  228. $file = $this->request->file('file');
  229. try {
  230. $upload = new Upload($file);
  231. $attachment = $upload->upload();
  232. } catch (UploadException $e) {
  233. $this->error($e->getMessage());
  234. }
  235. //文件绝对路径
  236. $filePath = $upload->getFile()->getRealPath() ?: $upload->getFile()->getPathname();
  237. $url = $attachment->url;
  238. try {
  239. $ret = $oss->upload($config['bucket'], ltrim($attachment->url, "/"), $upload->getFile());
  240. //成功不做任何操作
  241. } catch (\Exception $e) {
  242. $checkDeleteFile($attachment, $upload, true);
  243. $this->error("上传失败");
  244. }
  245. $checkDeleteFile($attachment, $upload);
  246. $this->success("上传成功", '', ['url' => $url, 'fullurl' => cdnurl($url, true)]);
  247. }
  248. return;
  249. }
  250. /**
  251. * 回调
  252. */
  253. public function notify()
  254. {
  255. $this->check();
  256. $size = $this->request->post('size/d');
  257. $name = $this->request->post('name', '');
  258. $md5 = $this->request->post('md5', '');
  259. $type = $this->request->post('type', '');
  260. $url = $this->request->post('url', '');
  261. $width = $this->request->post('width/d');
  262. $height = $this->request->post('height/d');
  263. $category = $this->request->post('category', '');
  264. $category = array_key_exists($category, config('site.attachmentcategory') ?? []) ? $category : '';
  265. $suffix = strtolower(pathinfo($name, PATHINFO_EXTENSION));
  266. $suffix = $suffix && preg_match("/^[a-zA-Z0-9]+$/", $suffix) ? $suffix : 'file';
  267. $attachment = Attachment::where('url', $url)->where('storage', 'cos')->find();
  268. if (!$attachment) {
  269. $params = array(
  270. 'category' => $category,
  271. 'admin_id' => (int)session('admin.id'),
  272. 'user_id' => (int)cookie('uid'),
  273. 'filesize' => $size,
  274. 'filename' => $name,
  275. 'imagewidth' => $width,
  276. 'imageheight' => $height,
  277. 'imagetype' => $suffix,
  278. 'imageframes' => 0,
  279. 'mimetype' => $type,
  280. 'url' => $url,
  281. 'uploadtime' => time(),
  282. 'storage' => 'cos',
  283. 'sha1' => $md5,
  284. );
  285. Attachment::create($params, true);
  286. }
  287. $this->success();
  288. return;
  289. }
  290. /**
  291. * 检查签名是否正确或过期
  292. */
  293. protected function check()
  294. {
  295. $costoken = $this->request->post('costoken', '', 'trim');
  296. if (!$costoken) {
  297. $this->error("参数不正确");
  298. }
  299. $config = get_addon_config('cos');
  300. list($appId, $sign, $data) = explode(':', $costoken);
  301. if (!$appId || !$sign || !$data) {
  302. $this->error("参数不正确");
  303. }
  304. if ($appId !== $config['appId']) {
  305. $this->error("参数不正确");
  306. }
  307. if ($sign !== base64_encode(hash_hmac('sha1', base64_decode($data), $config['secretKey'], true))) {
  308. $this->error("签名不正确");
  309. }
  310. $json = json_decode(base64_decode($data), true);
  311. if ($json['deadline'] < time()) {
  312. $this->error("请求已经超时");
  313. }
  314. }
  315. }