Upload.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // |
  4. // +----------------------------------------------------------------------
  5. // |
  6. // +----------------------------------------------------------------------
  7. // |
  8. // +----------------------------------------------------------------------
  9. // |
  10. // +----------------------------------------------------------------------
  11. // | Original reference: https://gitee.com/karson/fastadmin
  12. // +----------------------------------------------------------------------
  13. // +----------------------------------------------------------------------
  14. // | 上传基础类
  15. // +----------------------------------------------------------------------
  16. namespace app\common\library;
  17. use app\common\exception\UploadException;
  18. use app\common\model\Attachment;
  19. use FilesystemIterator;
  20. use think\facade\Config;
  21. use think\facade\Event;
  22. use think\File;
  23. use think\file\UploadedFile;
  24. class Upload
  25. {
  26. protected $config = [];
  27. protected $file = null;
  28. protected $fileInfo = null;
  29. protected $merging = false;
  30. protected $chunkDir = null;
  31. public function __construct($file = null)
  32. {
  33. $this->config = Config::get('upload');
  34. $this->chunkDir = runtime_path() . 'chunks';
  35. if ($file) {
  36. $this->setFile($file);
  37. }
  38. }
  39. public function setFile($file)
  40. {
  41. if (empty($file)) {
  42. throw new UploadException('未上传文件或超出服务器上传限制');
  43. }
  44. $fileInfo['type'] = $file->getOriginalMime();
  45. $fileInfo['size'] = $file->getSize();
  46. $fileInfo['name'] = $file->getOriginalName();
  47. $fileInfo['tmp_name'] = $file->getPathname();
  48. $suffix = strtolower(pathinfo($fileInfo['name'], PATHINFO_EXTENSION));
  49. $suffix = $suffix && preg_match("/^[a-zA-Z0-9]+$/", $suffix) ? $suffix : 'file';
  50. $fileInfo['suffix'] = $suffix;
  51. $fileInfo['imagewidth'] = 0;
  52. $fileInfo['imageheight'] = 0;
  53. $this->file = $file;
  54. $this->fileInfo = $fileInfo;
  55. $this->checkExecutable();
  56. }
  57. protected function checkExecutable()
  58. {
  59. //禁止上传以.开头的文件
  60. if (substr($this->fileInfo['name'], 0, 1) === '.') {
  61. throw new UploadException('上传文件格式受限制');
  62. }
  63. //禁止上传PHP和HTML文件
  64. if (in_array($this->fileInfo['type'], ['text/x-php', 'text/html']) || in_array($this->fileInfo['suffix'], ['php', 'asp', 'exe', 'cmd', 'sh', 'bat', 'html', 'htm', 'phtml', 'phar']) || preg_match("/^php(.*)/i", $this->fileInfo['suffix'])) {
  65. throw new UploadException('上传文件格式受限制');
  66. }
  67. return true;
  68. }
  69. /**
  70. * 检测是否图片
  71. * @param bool $force
  72. * @return bool
  73. * @throws UploadException
  74. */
  75. protected function checkImage($force = false)
  76. {
  77. //验证是否为图片文件
  78. if (in_array($this->fileInfo['type'], ['image/gif', 'image/jpg', 'image/jpeg', 'image/bmp', 'image/png', 'image/webp']) || in_array($this->fileInfo['suffix'], ['gif', 'jpg', 'jpeg', 'bmp', 'png', 'webp', 'wbmp'])) {
  79. $imgInfo = getimagesize($this->fileInfo['tmp_name']);
  80. if (!$imgInfo || !isset($imgInfo[0]) || !isset($imgInfo[1])) {
  81. throw new UploadException('上传文件不是有效的图片文件');
  82. }
  83. $this->fileInfo['imagewidth'] = $imgInfo[0] ?? 0;
  84. $this->fileInfo['imageheight'] = $imgInfo[1] ?? 0;
  85. return true;
  86. } else {
  87. return !$force;
  88. }
  89. }
  90. protected function checkSize()
  91. {
  92. preg_match('/([0-9\.]+)(\w+)/', $this->config['maxsize'], $matches);
  93. $size = $matches ? $matches[1] : $this->config['maxsize'];
  94. $type = $matches ? strtolower($matches[2]) : 'b';
  95. $typeDict = ['b' => 0, 'k' => 1, 'kb' => 1, 'm' => 2, 'mb' => 2, 'gb' => 3, 'g' => 3];
  96. $size = $size * pow(1024, $typeDict[$type] ?? 0);
  97. if ($this->fileInfo['size'] > $size) {
  98. throw new UploadException(
  99. '当前上传 (' . round($this->fileInfo['size'] / pow(1024, 2), 2) . 'MiB),最大允许上传文件大小:' . round($size / pow(1024, 2), 2) . 'MiB。'
  100. );
  101. }
  102. }
  103. protected function checkMimetype()
  104. {
  105. $mimetypeArr = explode(',', strtolower($this->config['mimetype']));
  106. $typeArr = explode('/', $this->fileInfo['type']);
  107. //Mimetype值不正确
  108. if (stripos($this->fileInfo['type'], '/') === false) {
  109. throw new UploadException('上传文件格式受限制');
  110. }
  111. //验证Mimetype类型
  112. if (!preg_match('/^[a-zA-Z0-9\-\+\.]+\/[a-zA-Z0-9\-\+\.]+$/', $this->fileInfo['type'])) {
  113. throw new UploadException('无效的MIME类型格式');
  114. }
  115. //验证文件后缀
  116. if (in_array($this->fileInfo['suffix'], $mimetypeArr) || in_array('.' . $this->fileInfo['suffix'], $mimetypeArr)
  117. || in_array($typeArr[0] . "/*", $mimetypeArr) || (in_array($this->fileInfo['type'], $mimetypeArr) && stripos($this->fileInfo['type'], '/') !== false)) {
  118. return true;
  119. }
  120. throw new UploadException('上传文件格式受限制');
  121. }
  122. /**
  123. * 保存附件
  124. * @param string $dir 附件存放的目录
  125. * @param string $from 来源
  126. * @return string|\think\response\Json
  127. */
  128. public function upload($dir = '', $from = '', $savekey = null)
  129. {
  130. if (empty($this->file)) {
  131. throw new UploadException('未上传文件或超出服务器上传限制');
  132. }
  133. $this->checkSize();
  134. $this->checkMimetype();
  135. $this->checkExecutable();
  136. $this->checkImage();
  137. // 附件上传钩子,用于第三方文件上传扩展
  138. if (config::get('site.upload_driver') != 'local') {
  139. $hook_result = Event::trigger('upload_cloud', ['dir' => $dir, 'file' => $this->file, 'from' => $from], true);
  140. if (false !== $hook_result) {
  141. return $hook_result;
  142. }
  143. }
  144. $savekey = $savekey ?: $this->getSavekey($dir);
  145. $savekey = '/' . ltrim($savekey, '/');
  146. $uploadDir = substr($savekey, 0, strripos($savekey, '/') + 1);
  147. $saveName = substr($savekey, strripos($savekey, '/') + 1);
  148. $destDir = public_path() . str_replace('/', DS, $uploadDir);
  149. $sha1 = $this->file->hash();
  150. $md5 = $this->file->md5();
  151. $mimetype = mb_substr($this->fileInfo['type'], 0, 100);
  152. //如果是合并文件
  153. if ($this->merging) {
  154. $destFile = $destDir . $saveName;
  155. $sourceFile = $this->file->getRealPath() ?: $this->file->getPathname();
  156. $this->file = null;
  157. if (!is_dir($destDir)) {
  158. @mkdir($destDir, 0755, true);
  159. }
  160. rename($sourceFile, $destFile);
  161. $file = new UploadedFile($destFile, $saveName);
  162. } else {
  163. // 移动到框架应用根目录指定目录下
  164. $file = $this->file->move($destDir, $saveName);
  165. if (!$file) {
  166. // 上传失败获取错误信息
  167. throw new UploadException($this->file->getError());
  168. }
  169. }
  170. $this->file = $file;
  171. $category = request()->post('category', '');
  172. $category = array_key_exists($category, config('site.attachmentcategory') ?? []) ? $category : '';
  173. // 获取附件信息
  174. $auth = Auth::instance();
  175. $file_info = [
  176. 'admin_id' => (int) session('admin.id'),
  177. 'user_id' => (int) $auth->id,
  178. 'name' => mb_substr(htmlspecialchars(strip_tags($this->fileInfo['name'])), 0, 100),
  179. 'mime' => $mimetype,
  180. 'category' => $category,
  181. 'path' => cdnurl($uploadDir . $saveName),
  182. 'ext' => $this->fileInfo['suffix'],
  183. 'size' => (int) $this->fileInfo['size'],
  184. 'imagewidth' => (int) $this->fileInfo['imagewidth'],
  185. 'imageheight' => (int) $this->fileInfo['imageheight'],
  186. 'md5' => $md5,
  187. 'sha1' => $sha1,
  188. 'driver' => 'local',
  189. ];
  190. $attachment = new Attachment();
  191. $attachment->data(array_filter($file_info));
  192. $attachment->save();
  193. Event::trigger("upload_after", $attachment);
  194. return $attachment;
  195. }
  196. /**
  197. * 合并分片文件
  198. * @param string $chunkid
  199. * @param int $chunkcount
  200. * @param string $filename
  201. * @return attachment|\think\Model
  202. * @throws UploadException
  203. */
  204. public function merge($chunkid, $chunkcount, $filename, $dir, $from)
  205. {
  206. if (!preg_match('/^[a-z0-9\-]{36}$/', $chunkid)) {
  207. throw new UploadException('未知参数');
  208. }
  209. $filePath = $this->chunkDir . DS . $chunkid;
  210. $completed = true;
  211. //检查所有分片是否都存在
  212. for ($i = 0; $i < $chunkcount; $i++) {
  213. if (!file_exists("{$filePath}-{$i}.part")) {
  214. $completed = false;
  215. break;
  216. }
  217. }
  218. if (!$completed) {
  219. $this->clean($chunkid);
  220. throw new UploadException('分片文件错误');
  221. }
  222. //如果所有文件分片都上传完毕,开始合并
  223. $uploadPath = $filePath;
  224. if (!$destFile = @fopen($uploadPath, "wb")) {
  225. $this->clean($chunkid);
  226. throw new UploadException('分片合并错误');
  227. }
  228. if (flock($destFile, LOCK_EX)) {
  229. // 进行排他型锁定
  230. for ($i = 0; $i < $chunkcount; $i++) {
  231. $partFile = "{$filePath}-{$i}.part";
  232. if (!$handle = @fopen($partFile, "rb")) {
  233. break;
  234. }
  235. while ($buff = fread($handle, filesize($partFile))) {
  236. fwrite($destFile, $buff);
  237. }
  238. @fclose($handle);
  239. @unlink($partFile); //删除分片
  240. }
  241. flock($destFile, LOCK_UN);
  242. }
  243. @fclose($destFile);
  244. $attachment = null;
  245. try {
  246. $file = new UploadedFile($uploadPath, $filename, (new File($uploadPath))->getMime(), null, true);
  247. //重新设置文件
  248. $this->setFile($file);
  249. unset($file);
  250. $this->merging = true;
  251. //允许大文件
  252. $this->config['maxsize'] = "1024G";
  253. $attachment = $this->upload($dir, $from);
  254. } catch (\Exception $e) {
  255. @unlink($destFile);
  256. throw new UploadException($e->getMessage());
  257. }
  258. return $attachment;
  259. }
  260. /**
  261. * 清理分片文件
  262. * @param $chunkid
  263. */
  264. public function clean($chunkid)
  265. {
  266. if (!preg_match('/^[a-z0-9\-]{36}$/', $chunkid)) {
  267. throw new UploadException('未知参数');
  268. }
  269. $iterator = new \GlobIterator($this->chunkDir . DS . $chunkid . '-*', FilesystemIterator::KEY_AS_FILENAME);
  270. $array = iterator_to_array($iterator);
  271. foreach ($array as &$item) {
  272. $sourceFile = $item->getRealPath() ?: $item->getPathname();
  273. $item = null;
  274. @unlink($sourceFile);
  275. }
  276. }
  277. /**
  278. * 分片上传
  279. */
  280. public function chunk($chunkid, $chunkindex, $chunkcount, $chunkfilesize = null, $chunkfilename = null, $direct = false)
  281. {
  282. if ($this->fileInfo['type'] != 'application/octet-stream') {
  283. throw new UploadException('上传文件格式受限制');
  284. }
  285. if (!preg_match('/^[a-z0-9\-]{36}$/', $chunkid)) {
  286. throw new UploadException('未知参数');
  287. }
  288. $fileName = $chunkid . "-" . $chunkindex . '.part';
  289. $destFile = $this->chunkDir . DS . $fileName;
  290. if (!is_dir($this->chunkDir)) {
  291. @mkdir($this->chunkDir, 0755, true);
  292. }
  293. if (!move_uploaded_file($this->file->getPathname(), $destFile)) {
  294. throw new UploadException('分片写入失败');
  295. }
  296. $file = new UploadedFile($destFile, $fileName, (new File($destFile))->getMime());
  297. $this->setFile($file);
  298. return $file;
  299. }
  300. protected function getSavekey($dir, $savekey = null, $filename = null, $md5 = null, $category = null)
  301. {
  302. if ($filename) {
  303. $suffix = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
  304. } else {
  305. $suffix = $this->fileInfo['suffix'] ?? '';
  306. }
  307. $suffix = $suffix && preg_match("/^[a-zA-Z0-9]+$/", $suffix) ? $suffix : 'file';
  308. $filename = $filename ?: ($this->fileInfo['name'] ?? 'unknown');
  309. $filename = xss_clean(strip_tags(htmlspecialchars($filename)));
  310. $fileprefix = mb_substr($filename, 0, mb_strrpos($filename, '.'), 'UTF-8');
  311. //文件名长度
  312. $maxFilenameLength = $this->config['maxfilenamelength'] ?? 100;
  313. if (mb_strlen($filename, 'UTF-8') > $maxFilenameLength) {
  314. $maxPrefixLength = $maxFilenameLength - mb_strlen($suffix, 'UTF-8') - 1;
  315. $fileprefix = mb_substr($filename, 0, $maxPrefixLength, 'UTF-8');
  316. $filename = $fileprefix . '.' . $suffix;
  317. }
  318. $md5 = $md5 ?: (isset($this->fileInfo['tmp_name']) ? md5_file($this->fileInfo['tmp_name']) : '');
  319. $category = $category ?: request()->post('category');
  320. $category = array_key_exists($category, config('site.attachmentcategory') ?? []) ? $category : '';
  321. $replaceArr = [
  322. '{dir}' => $dir,
  323. '{year}' => date("Y"),
  324. '{mon}' => date("m"),
  325. '{day}' => date("d"),
  326. '{hour}' => date("H"),
  327. '{min}' => date("i"),
  328. '{sec}' => date("s"),
  329. '{random}' => \util\Random::alnum(16),
  330. '{random32}' => \util\Random::alnum(32),
  331. '{category}' => $category,
  332. '{filename}' => $filename,
  333. '{fileprefix}' => $fileprefix,
  334. '{suffix}' => $suffix,
  335. '{.suffix}' => '.' . $suffix,
  336. '{filemd5}' => $md5,
  337. ];
  338. $savekey = $savekey ?: $this->config['savekey'];
  339. $savekey = str_replace(array_keys($replaceArr), array_values($replaceArr), $savekey);
  340. return $savekey;
  341. }
  342. }