Index.php 10.0 KB

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