Upload.php 13 KB

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