Index.php 11 KB

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