Upload.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  1. <?php
  2. namespace app\common\library;
  3. use app\common\exception\UploadException;
  4. use app\common\model\Attachment;
  5. use fast\Random;
  6. use FilesystemIterator;
  7. use think\Config;
  8. use think\File;
  9. use think\Hook;
  10. /**
  11. * 文件上传类
  12. */
  13. class Upload
  14. {
  15. protected $merging = false;
  16. protected $chunkDir = null;
  17. protected $config = [];
  18. protected $error = '';
  19. /**
  20. * @var File
  21. */
  22. protected $file = null;
  23. protected $fileInfo = null;
  24. public function __construct($file = null)
  25. {
  26. $this->config = Config::get('upload');
  27. $this->chunkDir = RUNTIME_PATH . 'chunks';
  28. if ($file) {
  29. $this->setFile($file);
  30. }
  31. }
  32. /**
  33. * 设置分片目录
  34. * @param $dir
  35. */
  36. public function setChunkDir($dir)
  37. {
  38. $this->chunkDir = $dir;
  39. }
  40. /**
  41. * 获取文件
  42. * @return File
  43. */
  44. public function getFile()
  45. {
  46. return $this->file;
  47. }
  48. /**
  49. * 设置文件
  50. * @param $file
  51. * @throws UploadException
  52. */
  53. public function setFile($file)
  54. {
  55. if (empty($file)) {
  56. throw new UploadException(__('No file upload or server upload limit exceeded'));
  57. }
  58. $fileInfo = $file->getInfo();
  59. $suffix = strtolower(pathinfo($fileInfo['name'], PATHINFO_EXTENSION));
  60. $suffix = $suffix && preg_match("/^[a-zA-Z0-9]+$/", $suffix) ? $suffix : 'file';
  61. $fileInfo['suffix'] = $suffix;
  62. $fileInfo['imagewidth'] = 0;
  63. $fileInfo['imageheight'] = 0;
  64. $this->file = $file;
  65. $this->fileInfo = $fileInfo;
  66. $this->checkExecutable();
  67. }
  68. /**
  69. * 检测是否为可执行脚本
  70. * @return bool
  71. * @throws UploadException
  72. */
  73. protected function checkExecutable()
  74. {
  75. //禁止上传PHP和HTML文件
  76. if (in_array($this->fileInfo['type'], ['text/x-php', 'text/html']) || in_array($this->fileInfo['suffix'], ['php', 'html', 'htm', 'phar', 'phtml']) || preg_match("/^php(.*)/i", $this->fileInfo['suffix'])) {
  77. throw new UploadException(__('Uploaded file format is limited'));
  78. }
  79. return true;
  80. }
  81. /**
  82. * 检测文件类型
  83. * @return bool
  84. * @throws UploadException
  85. */
  86. protected function checkMimetype()
  87. {
  88. $mimetypeArr = explode(',', strtolower($this->config['mimetype']));
  89. $typeArr = explode('/', $this->fileInfo['type']);
  90. //Mimetype值不正确
  91. if (stripos($this->fileInfo['type'], '/') === false) {
  92. throw new UploadException(__('Uploaded file format is limited'));
  93. }
  94. //验证文件后缀
  95. if ($this->config['mimetype'] === '*'
  96. || in_array($this->fileInfo['suffix'], $mimetypeArr) || in_array('.' . $this->fileInfo['suffix'], $mimetypeArr)
  97. || in_array($typeArr[0] . "/*", $mimetypeArr) || (in_array($this->fileInfo['type'], $mimetypeArr) && stripos($this->fileInfo['type'], '/') !== false)) {
  98. return true;
  99. }
  100. throw new UploadException(__('Uploaded file format is limited'));
  101. }
  102. /**
  103. * 检测是否图片
  104. * @param bool $force
  105. * @return bool
  106. * @throws UploadException
  107. */
  108. protected function checkImage($force = false)
  109. {
  110. //验证是否为图片文件
  111. 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'])) {
  112. $imgInfo = getimagesize($this->fileInfo['tmp_name']);
  113. if (!$imgInfo || !isset($imgInfo[0]) || !isset($imgInfo[1])) {
  114. throw new UploadException(__('Uploaded file is not a valid image'));
  115. }
  116. $this->fileInfo['imagewidth'] = $imgInfo[0] ?? 0;
  117. $this->fileInfo['imageheight'] = $imgInfo[1] ?? 0;
  118. return true;
  119. } else {
  120. return !$force;
  121. }
  122. }
  123. /**
  124. * 检测文件大小
  125. * @throws UploadException
  126. */
  127. protected function checkSize()
  128. {
  129. preg_match('/([0-9\.]+)(\w+)/', $this->config['maxsize'], $matches);
  130. $size = $matches ? $matches[1] : $this->config['maxsize'];
  131. $type = $matches ? strtolower($matches[2]) : 'b';
  132. $typeDict = ['b' => 0, 'k' => 1, 'kb' => 1, 'm' => 2, 'mb' => 2, 'gb' => 3, 'g' => 3];
  133. $size = $size * pow(1024, $typeDict[$type] ?? 0);
  134. if ($this->fileInfo['size'] > $size) {
  135. throw new UploadException(__(
  136. 'File is too big (%sMiB), Max filesize: %sMiB.',
  137. round($this->fileInfo['size'] / pow(1024, 2), 2),
  138. round($size / pow(1024, 2), 2)
  139. ));
  140. }
  141. }
  142. /**
  143. * 获取后缀
  144. * @return string
  145. */
  146. public function getSuffix()
  147. {
  148. return $this->fileInfo['suffix'] ?: 'file';
  149. }
  150. /**
  151. * 获取存储的文件名
  152. * @param string $savekey 保存路径
  153. * @param string $filename 文件名
  154. * @param string $md5 文件MD5
  155. * @param string $category 分类
  156. * @return mixed|null
  157. */
  158. public function getSavekey($savekey = null, $filename = null, $md5 = null, $category = null)
  159. {
  160. if ($filename) {
  161. $suffix = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
  162. } else {
  163. $suffix = $this->fileInfo['suffix'] ?? '';
  164. }
  165. $suffix = $suffix && preg_match("/^[a-zA-Z0-9]+$/", $suffix) ? $suffix : 'file';
  166. $filename = $filename ? $filename : ($this->fileInfo['name'] ?? 'unknown');
  167. $filename = xss_clean(strip_tags(htmlspecialchars($filename)));
  168. $fileprefix = substr($filename, 0, strripos($filename, '.'));
  169. $md5 = $md5 ? $md5 : (isset($this->fileInfo['tmp_name']) ? md5_file($this->fileInfo['tmp_name']) : '');
  170. $category = $category ? $category : request()->post('category');
  171. $category = $category ? xss_clean($category) : 'all';
  172. $replaceArr = [
  173. '{year}' => date("Y"),
  174. '{mon}' => date("m"),
  175. '{day}' => date("d"),
  176. '{hour}' => date("H"),
  177. '{min}' => date("i"),
  178. '{sec}' => date("s"),
  179. '{random}' => Random::alnum(16),
  180. '{random32}' => Random::alnum(32),
  181. '{category}' => $category ? $category : '',
  182. '{filename}' => substr($filename, 0, 100),
  183. '{fileprefix}' => substr($fileprefix, 0, 100),
  184. '{suffix}' => $suffix,
  185. '{.suffix}' => $suffix ? '.' . $suffix : '',
  186. '{filemd5}' => $md5,
  187. ];
  188. $savekey = $savekey ? $savekey : $this->config['savekey'];
  189. $savekey = str_replace(array_keys($replaceArr), array_values($replaceArr), $savekey);
  190. return $savekey;
  191. }
  192. /**
  193. * 清理分片文件
  194. * @param $chunkid
  195. */
  196. public function clean($chunkid)
  197. {
  198. if (!preg_match('/^[a-z0-9\-]{36}$/', $chunkid)) {
  199. throw new UploadException(__('Invalid parameters'));
  200. }
  201. $iterator = new \GlobIterator($this->chunkDir . DS . $chunkid . '-*', FilesystemIterator::KEY_AS_FILENAME);
  202. $array = iterator_to_array($iterator);
  203. foreach ($array as $index => &$item) {
  204. $sourceFile = $item->getRealPath() ?: $item->getPathname();
  205. $item = null;
  206. @unlink($sourceFile);
  207. }
  208. }
  209. /**
  210. * 合并分片文件
  211. * @param string $chunkid
  212. * @param int $chunkcount
  213. * @param string $filename
  214. * @return attachment|\think\Model
  215. * @throws UploadException
  216. */
  217. public function merge($chunkid, $chunkcount, $filename)
  218. {
  219. if (!preg_match('/^[a-z0-9\-]{36}$/', $chunkid)) {
  220. throw new UploadException(__('Invalid parameters'));
  221. }
  222. $filePath = $this->chunkDir . DS . $chunkid;
  223. $completed = true;
  224. //检查所有分片是否都存在
  225. for ($i = 0; $i < $chunkcount; $i++) {
  226. if (!file_exists("{$filePath}-{$i}.part")) {
  227. $completed = false;
  228. break;
  229. }
  230. }
  231. if (!$completed) {
  232. $this->clean($chunkid);
  233. throw new UploadException(__('Chunk file info error'));
  234. }
  235. //如果所有文件分片都上传完毕,开始合并
  236. $uploadPath = $filePath;
  237. if (!$destFile = @fopen($uploadPath, "wb")) {
  238. $this->clean($chunkid);
  239. throw new UploadException(__('Chunk file merge error'));
  240. }
  241. if (flock($destFile, LOCK_EX)) { // 进行排他型锁定
  242. for ($i = 0; $i < $chunkcount; $i++) {
  243. $partFile = "{$filePath}-{$i}.part";
  244. if (!$handle = @fopen($partFile, "rb")) {
  245. break;
  246. }
  247. while ($buff = fread($handle, filesize($partFile))) {
  248. fwrite($destFile, $buff);
  249. }
  250. @fclose($handle);
  251. @unlink($partFile); //删除分片
  252. }
  253. flock($destFile, LOCK_UN);
  254. }
  255. @fclose($destFile);
  256. $attachment = null;
  257. try {
  258. $file = new File($uploadPath);
  259. $info = [
  260. 'name' => $filename,
  261. 'type' => $file->getMime(),
  262. 'tmp_name' => $uploadPath,
  263. 'error' => 0,
  264. 'size' => $file->getSize()
  265. ];
  266. $file->setSaveName($filename)->setUploadInfo($info);
  267. $file->isTest(true);
  268. //重新设置文件
  269. $this->setFile($file);
  270. unset($file);
  271. $this->merging = true;
  272. //允许大文件
  273. $this->config['maxsize'] = "1024G";
  274. $attachment = $this->upload();
  275. } catch (\Exception $e) {
  276. @unlink($destFile);
  277. throw new UploadException($e->getMessage());
  278. }
  279. return $attachment;
  280. }
  281. /**
  282. * 分片上传
  283. * @throws UploadException
  284. */
  285. public function chunk($chunkid, $chunkindex, $chunkcount, $chunkfilesize = null, $chunkfilename = null, $direct = false)
  286. {
  287. if ($this->fileInfo['type'] != 'application/octet-stream') {
  288. throw new UploadException(__('Uploaded file format is limited'));
  289. }
  290. if (!preg_match('/^[a-z0-9\-]{36}$/', $chunkid)) {
  291. throw new UploadException(__('Invalid parameters'));
  292. }
  293. $destDir = RUNTIME_PATH . 'chunks';
  294. $fileName = $chunkid . "-" . $chunkindex . '.part';
  295. $destFile = $destDir . DS . $fileName;
  296. if (!is_dir($destDir)) {
  297. @mkdir($destDir, 0755, true);
  298. }
  299. if (!move_uploaded_file($this->file->getPathname(), $destFile)) {
  300. throw new UploadException(__('Chunk file write error'));
  301. }
  302. $file = new File($destFile);
  303. $info = [
  304. 'name' => $fileName,
  305. 'type' => $file->getMime(),
  306. 'tmp_name' => $destFile,
  307. 'error' => 0,
  308. 'size' => $file->getSize()
  309. ];
  310. $file->setSaveName($fileName)->setUploadInfo($info);
  311. $this->setFile($file);
  312. return $file;
  313. }
  314. /**
  315. * 普通上传
  316. * @return \app\common\model\attachment|\think\Model
  317. * @throws UploadException
  318. */
  319. public function upload($savekey = null)
  320. {
  321. if (empty($this->file)) {
  322. throw new UploadException(__('No file upload or server upload limit exceeded'));
  323. }
  324. $this->checkSize();
  325. $this->checkExecutable();
  326. $this->checkMimetype();
  327. $this->checkImage();
  328. $savekey = $savekey ? $savekey : $this->getSavekey();
  329. $savekey = '/' . ltrim($savekey, '/');
  330. $uploadDir = substr($savekey, 0, strripos($savekey, '/') + 1);
  331. $fileName = substr($savekey, strripos($savekey, '/') + 1);
  332. $destDir = ROOT_PATH . 'public' . str_replace('/', DS, $uploadDir);
  333. $sha1 = $this->file->hash();
  334. //如果是合并文件
  335. if ($this->merging) {
  336. if (!$this->file->check()) {
  337. throw new UploadException($this->file->getError());
  338. }
  339. $destFile = $destDir . $fileName;
  340. $sourceFile = $this->file->getRealPath() ?: $this->file->getPathname();
  341. $info = $this->file->getInfo();
  342. $this->file = null;
  343. if (!is_dir($destDir)) {
  344. @mkdir($destDir, 0755, true);
  345. }
  346. rename($sourceFile, $destFile);
  347. $file = new File($destFile);
  348. $file->setSaveName($fileName)->setUploadInfo($info);
  349. } else {
  350. $file = $this->file->move($destDir, $fileName);
  351. if (!$file) {
  352. // 上传失败获取错误信息
  353. throw new UploadException($this->file->getError());
  354. }
  355. }
  356. $this->file = $file;
  357. $category = request()->post('category');
  358. $category = array_key_exists($category, config('site.attachmentcategory') ?? []) ? $category : '';
  359. $auth = Auth::instance();
  360. $params = array(
  361. 'admin_id' => (int)session('admin.id'),
  362. 'user_id' => (int)$auth->id,
  363. 'filename' => mb_substr(htmlspecialchars(strip_tags($this->fileInfo['name'])), 0, 100),
  364. 'category' => $category,
  365. 'filesize' => $this->fileInfo['size'],
  366. 'imagewidth' => $this->fileInfo['imagewidth'],
  367. 'imageheight' => $this->fileInfo['imageheight'],
  368. 'imagetype' => $this->fileInfo['suffix'],
  369. 'imageframes' => 0,
  370. 'mimetype' => $this->fileInfo['type'],
  371. 'url' => $uploadDir . $file->getSaveName(),
  372. 'uploadtime' => time(),
  373. 'storage' => 'local',
  374. 'sha1' => $sha1,
  375. 'extparam' => '',
  376. );
  377. $attachment = new Attachment();
  378. $attachment->data(array_filter($params));
  379. $attachment->save();
  380. \think\Hook::listen("upload_after", $attachment);
  381. return $attachment;
  382. }
  383. /**
  384. * 设置错误信息
  385. * @param $msg
  386. */
  387. public function setError($msg)
  388. {
  389. $this->error = $msg;
  390. }
  391. /**
  392. * 获取错误信息
  393. * @return string
  394. */
  395. public function getError()
  396. {
  397. return $this->error;
  398. }
  399. }