Upload.php 13 KB

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