Upload.php 12 KB

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