Index.php 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  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. * @param bool $isApi
  68. */
  69. public function upload($isApi = false)
  70. {
  71. if ($isApi === true) {
  72. } else {
  73. $this->check();
  74. }
  75. $config = get_addon_config('alioss');
  76. $oss = new OssClient($config['accessKeyId'], $config['accessKeySecret'], $config['endpoint']);
  77. //检测删除文件或附件
  78. $checkDeleteFile = function ($attachment, $upload, $force = false) use ($config) {
  79. //如果设定为不备份则删除文件和记录 或 强制删除
  80. if ((isset($config['serverbackup']) && !$config['serverbackup']) || $force) {
  81. if ($attachment && !empty($attachment['id'])) {
  82. $attachment->delete();
  83. }
  84. if ($upload) {
  85. //文件绝对路径
  86. $filePath = $upload->getFile()->getRealPath() ?: $upload->getFile()->getPathname();
  87. @unlink($filePath);
  88. }
  89. }
  90. };
  91. $chunkid = $this->request->post("chunkid");
  92. if ($chunkid) {
  93. $action = $this->request->post("action");
  94. $chunkindex = $this->request->post("chunkindex/d");
  95. $chunkcount = $this->request->post("chunkcount/d");
  96. $filesize = $this->request->post("filesize");
  97. $filename = $this->request->post("filename");
  98. $method = $this->request->method(true);
  99. $key = $this->request->post("key");
  100. $uploadId = $this->request->post("uploadId");
  101. if ($action == 'merge') {
  102. $attachment = null;
  103. $upload = null;
  104. //合并分片
  105. if ($config['uploadmode'] == 'server') {
  106. //合并分片文件
  107. try {
  108. $upload = new Upload();
  109. $attachment = $upload->merge($chunkid, $chunkcount, $filename);
  110. } catch (UploadException $e) {
  111. $this->error($e->getMessage());
  112. }
  113. }
  114. $etags = $this->request->post("etags/a", []);
  115. if (count($etags) != $chunkcount) {
  116. $checkDeleteFile($attachment, $upload, true);
  117. $this->error("分片数据错误");
  118. }
  119. $listParts = [];
  120. for ($i = 0; $i < $chunkcount; $i++) {
  121. $listParts[] = array("PartNumber" => $i + 1, "ETag" => $etags[$i]);
  122. }
  123. try {
  124. $ret = $oss->completeMultipartUpload($config['bucket'], $key, $uploadId, $listParts);
  125. } catch (\Exception $e) {
  126. $checkDeleteFile($attachment, $upload, true);
  127. $this->error($e->getMessage());
  128. }
  129. $result = json_decode(json_encode(simplexml_load_string($ret['body'], "SimpleXMLElement", LIBXML_NOCDATA)), true);
  130. if (!isset($result['Key'])) {
  131. $checkDeleteFile($attachment, $upload, true);
  132. $this->error("上传失败");
  133. } else {
  134. $checkDeleteFile($attachment, $upload);
  135. $this->success("上传成功", '', ['url' => "/" . $key, 'fullurl' => cdnurl("/" . $key, true)]);
  136. }
  137. } else {
  138. //默认普通上传文件
  139. $file = $this->request->file('file');
  140. try {
  141. $upload = new Upload($file);
  142. $file = $upload->chunk($chunkid, $chunkindex, $chunkcount);
  143. } catch (UploadException $e) {
  144. $this->error($e->getMessage());
  145. }
  146. try {
  147. //上传分片到OSS
  148. $ret = $oss->uploadPart($config['bucket'], $key, $uploadId, ['fileUpload' => $file->getRealPath(), 'partNumber' => $chunkindex + 1]);
  149. } catch (\Exception $e) {
  150. $this->error($e->getMessage());
  151. }
  152. $this->success("上传成功", "", [], 3, ['ETag' => $ret]);
  153. }
  154. } else {
  155. $attachment = null;
  156. //默认普通上传文件
  157. $file = $this->request->file('file');
  158. try {
  159. $upload = new Upload($file);
  160. $attachment = $upload->upload();
  161. } catch (UploadException $e) {
  162. $this->error($e->getMessage());
  163. }
  164. //文件绝对路径
  165. $filePath = $upload->getFile()->getRealPath() ?: $upload->getFile()->getPathname();
  166. $url = $attachment->url;
  167. try {
  168. $ret = $oss->uploadFile($config['bucket'], ltrim($attachment->url, "/"), $filePath);
  169. //成功不做任何操作
  170. } catch (\Exception $e) {
  171. $checkDeleteFile($attachment, $upload, true);
  172. $this->error("上传失败");
  173. }
  174. $checkDeleteFile($attachment, $upload);
  175. $this->success("上传成功", '', ['url' => $url, 'fullurl' => cdnurl($url, true)]);
  176. }
  177. return;
  178. }
  179. /**
  180. * 回调
  181. */
  182. public function notify()
  183. {
  184. $this->check();
  185. $size = $this->request->post('size/d');
  186. $name = $this->request->post('name', '');
  187. $md5 = $this->request->post('md5', '');
  188. $type = $this->request->post('type', '');
  189. $url = $this->request->post('url', '');
  190. $width = $this->request->post('width/d');
  191. $height = $this->request->post('height/d');
  192. $category = $this->request->post('category', '');
  193. $category = array_key_exists($category, config('site.attachmentcategory') ?? []) ? $category : '';
  194. $suffix = strtolower(pathinfo($name, PATHINFO_EXTENSION));
  195. $suffix = $suffix && preg_match("/^[a-zA-Z0-9]+$/", $suffix) ? $suffix : 'file';
  196. $attachment = Attachment::where('url', $url)->where('storage', 'alioss')->find();
  197. if (!$attachment) {
  198. $params = array(
  199. 'category' => $category,
  200. 'admin_id' => (int)session('admin.id'),
  201. 'user_id' => (int)cookie('uid'),
  202. 'filesize' => $size,
  203. 'filename' => $name,
  204. 'imagewidth' => $width,
  205. 'imageheight' => $height,
  206. 'imagetype' => $suffix,
  207. 'imageframes' => 0,
  208. 'mimetype' => $type,
  209. 'url' => $url,
  210. 'uploadtime' => time(),
  211. 'storage' => 'alioss',
  212. 'sha1' => $md5,
  213. );
  214. Attachment::create($params, true);
  215. }
  216. $this->success();
  217. return;
  218. }
  219. /**
  220. * 检查签名是否正确或过期
  221. */
  222. protected function check()
  223. {
  224. $aliosstoken = $this->request->post('aliosstoken', '', 'trim');
  225. if (!$aliosstoken) {
  226. $this->error("参数不正确");
  227. }
  228. $config = get_addon_config('alioss');
  229. list($accessKeyId, $sign, $data) = explode(':', $aliosstoken);
  230. if (!$accessKeyId || !$sign || !$data) {
  231. $this->error("参数不能为空");
  232. }
  233. if ($accessKeyId !== $config['accessKeyId']) {
  234. $this->error("参数不正确");
  235. }
  236. if ($sign !== base64_encode(hash_hmac('sha1', base64_decode($data), $config['accessKeySecret'], true))) {
  237. $this->error("签名不正确");
  238. }
  239. $json = json_decode(base64_decode($data), true);
  240. if ($json['deadline'] < time()) {
  241. $this->error("请求已经超时");
  242. }
  243. }
  244. }