Index.php 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. <?php
  2. namespace addons\alioss\controller;
  3. use app\common\exception\UploadException;
  4. use app\common\library\Upload;
  5. use app\common\model\Attachment;
  6. use OSS\Core\OssException;
  7. use OSS\OssClient;
  8. use think\addons\Controller;
  9. use think\Config;
  10. /**
  11. * 阿里OSS云储存
  12. *
  13. */
  14. class Index extends Controller
  15. {
  16. public function _initialize()
  17. {
  18. //跨域检测
  19. check_cors_request();
  20. parent::_initialize();
  21. Config::set('default_return_type', 'json');
  22. }
  23. public function index()
  24. {
  25. Config::set('default_return_type', 'html');
  26. $this->error("当前插件暂无前台页面");
  27. }
  28. /**
  29. * 获取签名
  30. */
  31. public function params()
  32. {
  33. $this->check();
  34. $name = $this->request->post('name');
  35. $md5 = $this->request->post('md5');
  36. $chunk = $this->request->post('chunk');
  37. $auth = new \addons\alioss\library\Auth();
  38. $params = $auth->params($name, $md5);
  39. $params['OSSAccessKeyId'] = $params['id'];
  40. $params['success_action_status'] = 200;
  41. $config = get_addon_config('alioss');
  42. if ($chunk) {
  43. $oss = new OssClient($config['accessKeyId'], $config['accessKeySecret'], $config['endpoint']);
  44. // 初始化
  45. $fileSize = $this->request->post('size');
  46. $chunkSize = $this->request->post('chunksize');
  47. $uploadId = $oss->initiateMultipartUpload($config['bucket'], $params['key']);
  48. $params['uploadId'] = $uploadId;
  49. $params['parts'] = $oss->generateMultiuploadParts($fileSize, $chunkSize);
  50. $params['partsAuthorization'] = [];
  51. $date = gmdate('D, d M Y H:i:s \G\M\T');
  52. foreach ($params['parts'] as $index => $part) {
  53. $partNumber = $index + 1;
  54. $signstr = "PUT\n\n\n{$date}\nx-oss-date:{$date}\n/{$config['bucket']}/{$params['key']}?partNumber={$partNumber}&uploadId={$uploadId}";
  55. $authorization = base64_encode(hash_hmac('sha1', $signstr, $config['accessKeySecret'], true));
  56. $params['partsAuthorization'][$index] = $authorization;
  57. }
  58. $params['date'] = $date;
  59. }
  60. $this->success('', null, $params);
  61. return;
  62. }
  63. /**
  64. * 服务器中转上传文件
  65. * 上传分片
  66. * 合并分片
  67. */
  68. public function upload()
  69. {
  70. $this->check();
  71. $config = get_addon_config('alioss');
  72. $oss = new OssClient($config['accessKeyId'], $config['accessKeySecret'], $config['endpoint']);
  73. //检测删除文件或附件
  74. $checkDeleteFile = function ($attachment, $upload, $force = false) use ($config) {
  75. //如果设定为不备份则删除文件和记录 或 强制删除
  76. if ((isset($config['serverbackup']) && !$config['serverbackup']) || $force) {
  77. if ($attachment && !empty($attachment['id'])) {
  78. $attachment->delete();
  79. }
  80. if ($upload) {
  81. //文件绝对路径
  82. $filePath = $upload->getFile()->getRealPath() ?: $upload->getFile()->getPathname();
  83. @unlink($filePath);
  84. }
  85. }
  86. };
  87. $chunkid = $this->request->post("chunkid");
  88. if ($chunkid) {
  89. $action = $this->request->post("action");
  90. $chunkindex = $this->request->post("chunkindex/d");
  91. $chunkcount = $this->request->post("chunkcount/d");
  92. $filesize = $this->request->post("filesize");
  93. $filename = $this->request->post("filename");
  94. $method = $this->request->method(true);
  95. $key = $this->request->post("key");
  96. $uploadId = $this->request->post("uploadId");
  97. if ($action == 'merge') {
  98. $attachment = null;
  99. $upload = null;
  100. //合并分片
  101. if ($config['uploadmode'] == 'server') {
  102. //合并分片文件
  103. try {
  104. $upload = new Upload();
  105. $attachment = $upload->merge($chunkid, $chunkcount, $filename);
  106. } catch (UploadException $e) {
  107. $this->error($e->getMessage());
  108. }
  109. }
  110. $etags = $this->request->post("etags/a", []);
  111. if (count($etags) != $chunkcount) {
  112. $checkDeleteFile($attachment, $upload, true);
  113. $this->error("分片数据错误");
  114. }
  115. $listParts = [];
  116. for ($i = 0; $i < $chunkcount; $i++) {
  117. $listParts[] = array("PartNumber" => $i + 1, "ETag" => $etags[$i]);
  118. }
  119. try {
  120. $ret = $oss->completeMultipartUpload($config['bucket'], $key, $uploadId, $listParts);
  121. } catch (\Exception $e) {
  122. $checkDeleteFile($attachment, $upload, true);
  123. $this->error($e->getMessage());
  124. }
  125. $result = json_decode(json_encode(simplexml_load_string($ret['body'], "SimpleXMLElement", LIBXML_NOCDATA)), true);
  126. if (!isset($result['Key'])) {
  127. $checkDeleteFile($attachment, $upload, true);
  128. $this->error("上传失败");
  129. } else {
  130. $checkDeleteFile($attachment, $upload);
  131. $this->success("上传成功", '', ['url' => "/" . $key, 'fullurl' => cdnurl("/" . $key, true)]);
  132. }
  133. } else {
  134. //默认普通上传文件
  135. $file = $this->request->file('file');
  136. try {
  137. $upload = new Upload($file);
  138. $file = $upload->chunk($chunkid, $chunkindex, $chunkcount);
  139. } catch (UploadException $e) {
  140. $this->error($e->getMessage());
  141. }
  142. try {
  143. //上传分片到OSS
  144. $ret = $oss->uploadPart($config['bucket'], $key, $uploadId, ['fileUpload' => $file->getRealPath(), 'partNumber' => $chunkindex + 1]);
  145. } catch (\Exception $e) {
  146. $this->error($e->getMessage());
  147. }
  148. $this->success("上传成功", "", [], 3, ['ETag' => $ret]);
  149. }
  150. } else {
  151. $attachment = null;
  152. //默认普通上传文件
  153. $file = $this->request->file('file');
  154. try {
  155. $upload = new Upload($file);
  156. $attachment = $upload->upload();
  157. } catch (UploadException $e) {
  158. $this->error($e->getMessage());
  159. }
  160. //文件绝对路径
  161. $filePath = $upload->getFile()->getRealPath() ?: $upload->getFile()->getPathname();
  162. $url = $attachment->url;
  163. try {
  164. $ret = $oss->uploadFile($config['bucket'], ltrim($attachment->url, "/"), $filePath);
  165. //成功不做任何操作
  166. } catch (\Exception $e) {
  167. $checkDeleteFile($attachment, $upload, true);
  168. $this->error("上传失败");
  169. }
  170. $checkDeleteFile($attachment, $upload);
  171. $this->success("上传成功", '', ['url' => $url, 'fullurl' => cdnurl($url, true)]);
  172. }
  173. return;
  174. }
  175. /**
  176. * 回调
  177. */
  178. public function notify()
  179. {
  180. $this->check();
  181. $size = $this->request->post('size/d');
  182. $name = $this->request->post('name', '');
  183. $md5 = $this->request->post('md5', '');
  184. $type = $this->request->post('type', '');
  185. $url = $this->request->post('url', '');
  186. $width = $this->request->post('width/d');
  187. $height = $this->request->post('height/d');
  188. $category = $this->request->post('category', '');
  189. $category = array_key_exists($category, config('site.attachmentcategory') ?? []) ? $category : '';
  190. $suffix = substr($name, stripos($name, '.') + 1);
  191. $attachment = Attachment::where('url', $url)->where('storage', 'alioss')->find();
  192. if (!$attachment) {
  193. $params = array(
  194. // 'category' => $category,
  195. 'admin_id' => (int)session('admin.id'),
  196. 'user_id' => (int)cookie('uid'),
  197. 'filesize' => $size,
  198. 'filename' => $name,
  199. 'imagewidth' => $width,
  200. 'imageheight' => $height,
  201. 'imagetype' => $suffix,
  202. 'imageframes' => 0,
  203. 'mimetype' => $type,
  204. 'url' => $url,
  205. 'uploadtime' => time(),
  206. 'storage' => 'alioss',
  207. 'sha1' => $md5,
  208. );
  209. Attachment::create($params);
  210. }
  211. $this->success();
  212. return;
  213. }
  214. /**
  215. * 检查签名是否正确或过期
  216. */
  217. protected function check()
  218. {
  219. $aliosstoken = $this->request->post('aliosstoken', '', 'trim');
  220. if (!$aliosstoken) {
  221. $this->error("参数不正确");
  222. }
  223. $config = get_addon_config('alioss');
  224. list($accessKeyId, $sign, $data) = explode(':', $aliosstoken);
  225. if (!$accessKeyId || !$sign || !$data) {
  226. $this->error("参数不正确");
  227. }
  228. if ($accessKeyId !== $config['accessKeyId']) {
  229. $this->error("参数不正确");
  230. }
  231. if ($sign !== base64_encode(hash_hmac('sha1', base64_decode($data), $config['accessKeySecret'], true))) {
  232. $this->error("签名不正确");
  233. }
  234. $json = json_decode(base64_decode($data), true);
  235. if ($json['deadline'] < time()) {
  236. $this->error("请求已经超时");
  237. }
  238. }
  239. }