Upload.php 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkAdmin
  4. // +----------------------------------------------------------------------
  5. // | 版权所有 2014~2022 广州楚才信息科技有限公司 [ http://www.cuci.cc ]
  6. // +----------------------------------------------------------------------
  7. // | 官方网站: https://thinkadmin.top
  8. // +----------------------------------------------------------------------
  9. // | 开源协议 ( https://mit-license.org )
  10. // | 免费声明 ( https://thinkadmin.top/disclaimer )
  11. // +----------------------------------------------------------------------
  12. // | gitee 代码仓库:https://gitee.com/zoujingli/ThinkAdmin
  13. // | github 代码仓库:https://github.com/zoujingli/ThinkAdmin
  14. // +----------------------------------------------------------------------
  15. namespace app\admin\controller\api;
  16. use think\admin\Controller;
  17. use think\admin\Storage;
  18. use think\admin\storage\AliossStorage;
  19. use think\admin\storage\LocalStorage;
  20. use think\admin\storage\QiniuStorage;
  21. use think\admin\storage\TxcosStorage;
  22. use think\admin\storage\UpyunStorage;
  23. use think\exception\HttpResponseException;
  24. use think\file\UploadedFile;
  25. use think\Response;
  26. /**
  27. * 文件上传接口
  28. * Class Upload
  29. * @package app\admin\controller\api
  30. */
  31. class Upload extends Controller
  32. {
  33. /**
  34. * 文件上传脚本
  35. * @return Response
  36. * @throws \think\db\exception\DataNotFoundException
  37. * @throws \think\db\exception\DbException
  38. * @throws \think\db\exception\ModelNotFoundException
  39. */
  40. public function index(): Response
  41. {
  42. $data = ['exts' => []];
  43. foreach (str2arr(sysconf('storage.allow_exts')) as $ext) {
  44. $data['exts'][$ext] = Storage::mime($ext);
  45. }
  46. $template = realpath(__DIR__ . '/../../view/api/upload.js');
  47. $data['exts'] = json_encode($data['exts'], JSON_UNESCAPED_UNICODE);
  48. $data['nameType'] = sysconf('storage.name_type') ?: 'xmd5';
  49. return view($template, $data)->contentType('application/x-javascript');
  50. }
  51. /**
  52. * 文件上传检查
  53. * @login true
  54. * @throws \think\admin\Exception
  55. * @throws \think\db\exception\DataNotFoundException
  56. * @throws \think\db\exception\DbException
  57. * @throws \think\db\exception\ModelNotFoundException
  58. */
  59. public function state()
  60. {
  61. [$name, $safe] = [input('name'), $this->getSafe()];
  62. $data = ['uptype' => $this->getType(), 'safe' => intval($safe), 'key' => input('key')];
  63. if ($info = Storage::instance($data['uptype'])->info($data['key'], $safe, $name)) {
  64. $data['url'] = $info['url'];
  65. $data['key'] = $info['key'];
  66. $this->success('文件已经上传', $data, 200);
  67. } elseif ('local' === $data['uptype']) {
  68. $data['url'] = LocalStorage::instance()->url($data['key'], $safe, $name);
  69. $data['server'] = LocalStorage::instance()->upload();
  70. } elseif ('qiniu' === $data['uptype']) {
  71. $data['url'] = QiniuStorage::instance()->url($data['key'], $safe, $name);
  72. $data['token'] = QiniuStorage::instance()->buildUploadToken($data['key'], 3600, $name);
  73. $data['server'] = QiniuStorage::instance()->upload();
  74. } elseif ('alioss' === $data['uptype']) {
  75. $token = AliossStorage::instance()->buildUploadToken($data['key'], 3600, $name);
  76. $data['url'] = $token['siteurl'];
  77. $data['policy'] = $token['policy'];
  78. $data['signature'] = $token['signature'];
  79. $data['OSSAccessKeyId'] = $token['keyid'];
  80. $data['server'] = AliossStorage::instance()->upload();
  81. } elseif ('txcos' === $data['uptype']) {
  82. $token = TxcosStorage::instance()->buildUploadToken($data['key'], 3600, $name);
  83. $data['url'] = $token['siteurl'];
  84. $data['q-ak'] = $token['q-ak'];
  85. $data['policy'] = $token['policy'];
  86. $data['q-key-time'] = $token['q-key-time'];
  87. $data['q-signature'] = $token['q-signature'];
  88. $data['q-sign-algorithm'] = $token['q-sign-algorithm'];
  89. $data['server'] = TxcosStorage::instance()->upload();
  90. } elseif ('upyun' === $data['uptype']) {
  91. $token = UpyunStorage::instance()->buildUploadToken($data['key'], 3600, $name, input('size'), input('hash'));
  92. $data['url'] = $token['siteurl'];
  93. $data['policy'] = $token['policy'];
  94. $data['authorization'] = $token['authorization'];
  95. $data['server'] = UpyunStorage::instance()->upload();
  96. }
  97. $this->success('获取上传授权参数', $data, 404);
  98. }
  99. /**
  100. * 文件上传入口
  101. * @login true
  102. * @throws \think\db\exception\DataNotFoundException
  103. * @throws \think\db\exception\DbException
  104. * @throws \think\db\exception\ModelNotFoundException
  105. */
  106. public function file()
  107. {
  108. if (!($file = $this->getFile())->isValid()) {
  109. $this->error('文件上传异常,文件过大或未上传!');
  110. }
  111. $safeMode = $this->getSafe();
  112. $extension = strtolower($file->getOriginalExtension());
  113. $saveName = input('key') ?: Storage::name($file->getPathname(), $extension, '', 'md5_file');
  114. // 检查文件名称是否合法
  115. if (strpos($saveName, '../') !== false) {
  116. $this->error('文件路径不能出现跳级操作!');
  117. }
  118. // 检查文件后缀是否被恶意修改
  119. if (strtolower(pathinfo(parse_url($saveName, PHP_URL_PATH), PATHINFO_EXTENSION)) !== $extension) {
  120. $this->error('文件后缀异常,请重新上传文件!');
  121. }
  122. // 屏蔽禁止上传指定后缀的文件
  123. if (!in_array($extension, str2arr(sysconf('storage.allow_exts')))) {
  124. $this->error('文件类型受限,请在后台配置规则!');
  125. }
  126. if (in_array($extension, ['sh', 'asp', 'bat', 'cmd', 'exe', 'php'])) {
  127. $this->error('文件安全保护,禁止上传可执行文件!');
  128. }
  129. try {
  130. if ($this->getType() === 'local') {
  131. $local = LocalStorage::instance();
  132. $distName = $local->path($saveName, $safeMode);
  133. $file->move(dirname($distName), basename($distName));
  134. $info = $local->info($saveName, $safeMode, $file->getOriginalName());
  135. if (in_array($extension, ['jpg', 'gif', 'png', 'bmp', 'jpeg', 'wbmp'])) {
  136. if ($this->imgNotSafe($distName) && $local->del($saveName)) {
  137. $this->error('图片未通过安全检查!');
  138. }
  139. [$width, $height] = getimagesize($distName);
  140. if (($width < 1 || $height < 1) && $local->del($saveName)) {
  141. $this->error('读取图片的尺寸失败!');
  142. }
  143. }
  144. } else {
  145. $bina = file_get_contents($file->getPathname());
  146. $info = Storage::instance($this->getType())->set($saveName, $bina, $safeMode, $file->getOriginalName());
  147. }
  148. if (isset($info['url'])) {
  149. $this->success('文件上传成功!', ['url' => $safeMode ? $saveName : $info['url']]);
  150. } else {
  151. $this->error('文件处理失败,请稍候再试!');
  152. }
  153. } catch (HttpResponseException $exception) {
  154. throw $exception;
  155. } catch (\Exception $exception) {
  156. $this->error($exception->getMessage());
  157. }
  158. }
  159. /**
  160. * 获取文件上传类型
  161. * @return boolean
  162. */
  163. private function getSafe(): bool
  164. {
  165. return boolval(input('safe', '0'));
  166. }
  167. /**
  168. * 获取文件上传方式
  169. * @return string
  170. * @throws \think\db\exception\DataNotFoundException
  171. * @throws \think\db\exception\DbException
  172. * @throws \think\db\exception\ModelNotFoundException
  173. */
  174. private function getType(): string
  175. {
  176. $type = strtolower(input('uptype', ''));
  177. if (in_array($type, ['local', 'qiniu', 'alioss', 'txcos', 'uptype'])) {
  178. return $type;
  179. } else {
  180. return strtolower(sysconf('storage.type'));
  181. }
  182. }
  183. /**
  184. * 获取本地文件对象
  185. * @return UploadedFile|void
  186. */
  187. private function getFile(): UploadedFile
  188. {
  189. try {
  190. $file = $this->request->file('file');
  191. if ($file instanceof UploadedFile) {
  192. return $file;
  193. } else {
  194. $this->error('未获取到上传的文件对象!');
  195. }
  196. } catch (HttpResponseException $exception) {
  197. throw $exception;
  198. } catch (\Exception $exception) {
  199. $this->error(lang($exception->getMessage()));
  200. }
  201. }
  202. /**
  203. * 检查图片是否安全
  204. * @param string $filename
  205. * @return boolean
  206. */
  207. private function imgNotSafe(string $filename): bool
  208. {
  209. $source = fopen($filename, 'rb');
  210. if (($size = filesize($filename)) > 512) {
  211. $hexs = bin2hex(fread($source, 512));
  212. fseek($source, $size - 512);
  213. $hexs .= bin2hex(fread($source, 512));
  214. } else {
  215. $hexs = bin2hex(fread($source, $size));
  216. }
  217. if (is_resource($source)) fclose($source);
  218. $bins = hex2bin($hexs);
  219. /* 匹配十六进制中的 <% ( ) %> 或 <? ( ) ?> 或 <script | /script> */
  220. foreach (['<?php ', '<% ', '<script '] as $key) if (stripos($bins, $key) !== false) return true;
  221. return preg_match("/(3c25.*?28.*?29.*?253e)|(3c3f.*?28.*?29.*?3f3e)|(3C534352495054)|(2F5343524950543E)|(3C736372697074)|(2F7363726970743E)/is", $hexs);
  222. }
  223. }