Upload.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  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\model\SystemFile;
  18. use think\admin\service\AdminService;
  19. use think\admin\Storage;
  20. use think\admin\storage\AliossStorage;
  21. use think\admin\storage\LocalStorage;
  22. use think\admin\storage\QiniuStorage;
  23. use think\admin\storage\TxcosStorage;
  24. use think\admin\storage\UpyunStorage;
  25. use think\exception\HttpResponseException;
  26. use think\file\UploadedFile;
  27. use think\Response;
  28. /**
  29. * 文件上传接口
  30. * Class Upload
  31. * @package app\admin\controller\api
  32. */
  33. class Upload extends Controller
  34. {
  35. /**
  36. * 文件上传脚本
  37. * @return Response
  38. * @throws \think\db\exception\DataNotFoundException
  39. * @throws \think\db\exception\DbException
  40. * @throws \think\db\exception\ModelNotFoundException
  41. */
  42. public function index(): Response
  43. {
  44. $data = ['exts' => []];
  45. foreach (str2arr(sysconf('storage.allow_exts')) as $ext) {
  46. $data['exts'][$ext] = Storage::mime($ext);
  47. }
  48. $template = realpath(__DIR__ . '/../../view/api/upload.js');
  49. $data['exts'] = json_encode($data['exts'], JSON_UNESCAPED_UNICODE);
  50. $data['nameType'] = sysconf('storage.name_type') ?: 'xmd5';
  51. return view($template, $data)->contentType('application/x-javascript');
  52. }
  53. /**
  54. * 文件上传检查
  55. * @login true
  56. * @throws \think\admin\Exception
  57. * @throws \think\db\exception\DataNotFoundException
  58. * @throws \think\db\exception\DbException
  59. * @throws \think\db\exception\ModelNotFoundException
  60. */
  61. public function state()
  62. {
  63. [$name, $safe] = [input('name'), $this->getSafe()];
  64. $data = ['uptype' => $this->getType(), 'safe' => intval($safe), 'key' => input('key')];
  65. $file = SystemFile::mk()->data($this->_vali([
  66. 'path.value' => $data['key'],
  67. 'type.value' => $this->getType(),
  68. 'uuid.value' => AdminService::instance()->getUserId(),
  69. 'name.require' => '名称不能为空!',
  70. 'hash.require' => '哈希不能为空!',
  71. 'xext.require' => '后缀不能为空!',
  72. 'size.require' => '大小不能为空!',
  73. 'mime.require' => "类型不能为空!",
  74. 'status.value' => 1
  75. ]));
  76. if ($info = Storage::instance($data['uptype'])->info($data['key'], $safe, $name)) {
  77. $file->save(['xurl' => $info['url'], 'is_fast' => 1, 'is_safe' => $data['safe']]);
  78. $extr = ['id' => $file->id ?? 0, 'url' => $info['url'], 'key' => $info['key']];
  79. $this->success('文件已经上传', array_merge($data, $extr), 200);
  80. } elseif ('local' === $data['uptype']) {
  81. $data['url'] = LocalStorage::instance()->url($data['key'], $safe, $name);
  82. $data['server'] = LocalStorage::instance()->upload();
  83. } elseif ('qiniu' === $data['uptype']) {
  84. $data['url'] = QiniuStorage::instance()->url($data['key'], $safe, $name);
  85. $data['token'] = QiniuStorage::instance()->buildUploadToken($data['key'], 3600, $name);
  86. $data['server'] = QiniuStorage::instance()->upload();
  87. } elseif ('alioss' === $data['uptype']) {
  88. $token = AliossStorage::instance()->buildUploadToken($data['key'], 3600, $name);
  89. $data['url'] = $token['siteurl'];
  90. $data['policy'] = $token['policy'];
  91. $data['signature'] = $token['signature'];
  92. $data['OSSAccessKeyId'] = $token['keyid'];
  93. $data['server'] = AliossStorage::instance()->upload();
  94. } elseif ('txcos' === $data['uptype']) {
  95. $token = TxcosStorage::instance()->buildUploadToken($data['key'], 3600, $name);
  96. $data['url'] = $token['siteurl'];
  97. $data['q-ak'] = $token['q-ak'];
  98. $data['policy'] = $token['policy'];
  99. $data['q-key-time'] = $token['q-key-time'];
  100. $data['q-signature'] = $token['q-signature'];
  101. $data['q-sign-algorithm'] = $token['q-sign-algorithm'];
  102. $data['server'] = TxcosStorage::instance()->upload();
  103. } elseif ('upyun' === $data['uptype']) {
  104. $token = UpyunStorage::instance()->buildUploadToken($data['key'], 3600, $name, input('size'), input('hash'));
  105. $data['url'] = $token['siteurl'];
  106. $data['policy'] = $token['policy'];
  107. $data['authorization'] = $token['authorization'];
  108. $data['server'] = UpyunStorage::instance()->upload();
  109. }
  110. $file->save(['xurl' => $data['url'], 'is_fast' => 0, 'is_safe' => $data['safe']]);
  111. $this->success('获取上传授权参数', array_merge($data, ['id' => $file->id ?? 0]), 404);
  112. }
  113. /**
  114. * 更新文件状态
  115. * @login true
  116. * @return void
  117. */
  118. public function done()
  119. {
  120. $data = $this->_vali([
  121. 'id.require' => '编号不能为空!',
  122. 'hash.require' => '哈希不能为空!',
  123. ]);
  124. $data['uuid'] = AdminService::instance()->getUserId();
  125. $file = SystemFile::mk()->where($data)->findOrEmpty();
  126. if ($file->isEmpty()) $this->error('文件不存在!');
  127. if ($file->save(['status' => 2])) {
  128. $this->success('更新成功!');
  129. } else {
  130. $this->error('更新失败!');
  131. }
  132. }
  133. /**
  134. * 文件上传入口
  135. * @login true
  136. * @throws \think\db\exception\DataNotFoundException
  137. * @throws \think\db\exception\DbException
  138. * @throws \think\db\exception\ModelNotFoundException
  139. */
  140. public function file()
  141. {
  142. if (!($file = $this->getFile())->isValid()) {
  143. $this->error('文件上传异常,文件过大或未上传!');
  144. }
  145. $safeMode = $this->getSafe();
  146. $extension = strtolower($file->getOriginalExtension());
  147. $saveName = input('key') ?: Storage::name($file->getPathname(), $extension, '', 'md5_file');
  148. // 检查文件名称是否合法
  149. if (strpos($saveName, '../') !== false) {
  150. $this->error('文件路径不能出现跳级操作!');
  151. }
  152. // 检查文件后缀是否被恶意修改
  153. if (strtolower(pathinfo(parse_url($saveName, PHP_URL_PATH), PATHINFO_EXTENSION)) !== $extension) {
  154. $this->error('文件后缀异常,请重新上传文件!');
  155. }
  156. // 屏蔽禁止上传指定后缀的文件
  157. if (!in_array($extension, str2arr(sysconf('storage.allow_exts')))) {
  158. $this->error('文件类型受限,请在后台配置规则!');
  159. }
  160. if (in_array($extension, ['sh', 'asp', 'bat', 'cmd', 'exe', 'php'])) {
  161. $this->error('文件安全保护,禁止上传可执行文件!');
  162. }
  163. try {
  164. if ($this->getType() === 'local') {
  165. $local = LocalStorage::instance();
  166. $distName = $local->path($saveName, $safeMode);
  167. $file->move(dirname($distName), basename($distName));
  168. $info = $local->info($saveName, $safeMode, $file->getOriginalName());
  169. if (in_array($extension, ['jpg', 'gif', 'png', 'bmp', 'jpeg', 'wbmp'])) {
  170. if ($this->imgNotSafe($distName) && $local->del($saveName)) {
  171. $this->error('图片未通过安全检查!');
  172. }
  173. [$width, $height] = getimagesize($distName);
  174. if (($width < 1 || $height < 1) && $local->del($saveName)) {
  175. $this->error('读取图片的尺寸失败!');
  176. }
  177. }
  178. } else {
  179. $bina = file_get_contents($file->getPathname());
  180. $info = Storage::instance($this->getType())->set($saveName, $bina, $safeMode, $file->getOriginalName());
  181. }
  182. if (isset($info['url'])) {
  183. $this->success('文件上传成功!', ['url' => $safeMode ? $saveName : $info['url']]);
  184. } else {
  185. $this->error('文件处理失败,请稍候再试!');
  186. }
  187. } catch (HttpResponseException $exception) {
  188. throw $exception;
  189. } catch (\Exception $exception) {
  190. $this->error($exception->getMessage());
  191. }
  192. }
  193. /**
  194. * 获取文件上传类型
  195. * @return boolean
  196. */
  197. private function getSafe(): bool
  198. {
  199. return boolval(input('safe', '0'));
  200. }
  201. /**
  202. * 获取文件上传方式
  203. * @return string
  204. * @throws \think\db\exception\DataNotFoundException
  205. * @throws \think\db\exception\DbException
  206. * @throws \think\db\exception\ModelNotFoundException
  207. */
  208. private function getType(): string
  209. {
  210. $type = strtolower(input('uptype', ''));
  211. if (in_array($type, ['local', 'qiniu', 'alioss', 'txcos', 'uptype'])) {
  212. return $type;
  213. } else {
  214. return strtolower(sysconf('storage.type'));
  215. }
  216. }
  217. /**
  218. * 获取本地文件对象
  219. * @return UploadedFile|void
  220. */
  221. private function getFile(): UploadedFile
  222. {
  223. try {
  224. $file = $this->request->file('file');
  225. if ($file instanceof UploadedFile) {
  226. return $file;
  227. } else {
  228. $this->error('未获取到上传的文件对象!');
  229. }
  230. } catch (HttpResponseException $exception) {
  231. throw $exception;
  232. } catch (\Exception $exception) {
  233. $this->error(lang($exception->getMessage()));
  234. }
  235. }
  236. /**
  237. * 检查图片是否安全
  238. * @param string $filename
  239. * @return boolean
  240. */
  241. private function imgNotSafe(string $filename): bool
  242. {
  243. $source = fopen($filename, 'rb');
  244. if (($size = filesize($filename)) > 512) {
  245. $hexs = bin2hex(fread($source, 512));
  246. fseek($source, $size - 512);
  247. $hexs .= bin2hex(fread($source, 512));
  248. } else {
  249. $hexs = bin2hex(fread($source, $size));
  250. }
  251. if (is_resource($source)) fclose($source);
  252. $bins = hex2bin($hexs);
  253. /* 匹配十六进制中的 <% ( ) %> 或 <? ( ) ?> 或 <script | /script> */
  254. foreach (['<?php ', '<% ', '<script '] as $key) if (stripos($bins, $key) !== false) return true;
  255. return preg_match("/(3c25.*?28.*?29.*?253e)|(3c3f.*?28.*?29.*?3f3e)|(3C534352495054)|(2F5343524950543E)|(3C736372697074)|(2F7363726970743E)/is", $hexs);
  256. }
  257. }