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'] = isset($imgInfo[0]) ? $imgInfo[0] : 0;
  117. $this->fileInfo['imageheight'] = isset($imgInfo[1]) ? $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 = (int)($size * pow(1024, isset($typeDict[$type]) ? $typeDict[$type] : 0));
  134. if ($this->fileInfo['size'] > $size) {
  135. throw new UploadException(__('File is too big (%sMiB), Max filesize: %sMiB.',
  136. round($this->fileInfo['size'] / pow(1024, 2), 2),
  137. round($size / pow(1024, 2), 2)));
  138. }
  139. }
  140. /**
  141. * 获取后缀
  142. * @return string
  143. */
  144. public function getSuffix()
  145. {
  146. return $this->fileInfo['suffix'] ?: 'file';
  147. }
  148. /**
  149. * 获取存储的文件名
  150. * @param string $savekey 保存路径
  151. * @param string $filename 文件名
  152. * @param string $md5 文件MD5
  153. * @param string $category 分类
  154. * @return mixed|null
  155. */
  156. public function getSavekey($savekey = null, $filename = null, $md5 = null, $category = null)
  157. {
  158. if ($filename) {
  159. $suffix = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
  160. } else {
  161. $suffix = $this->fileInfo['suffix'] ?? '';
  162. }
  163. $suffix = $suffix && preg_match("/^[a-zA-Z0-9]+$/", $suffix) ? $suffix : 'file';
  164. $filename = $filename ? $filename : ($this->fileInfo['name'] ?? 'unknown');
  165. $filename = xss_clean(strip_tags(htmlspecialchars($filename)));
  166. $fileprefix = substr($filename, 0, strripos($filename, '.'));
  167. $md5 = $md5 ? $md5 : (isset($this->fileInfo['tmp_name']) ? md5_file($this->fileInfo['tmp_name']) : '');
  168. $category = $category ? $category : request()->post('category');
  169. $category = $category ? xss_clean($category) : 'all';
  170. $replaceArr = [
  171. '{year}' => date("Y"),
  172. '{mon}' => date("m"),
  173. '{day}' => date("d"),
  174. '{hour}' => date("H"),
  175. '{min}' => date("i"),
  176. '{sec}' => date("s"),
  177. '{random}' => Random::alnum(16),
  178. '{random32}' => Random::alnum(32),
  179. '{category}' => $category ? $category : '',
  180. '{filename}' => substr($filename, 0, 100),
  181. '{fileprefix}' => substr($fileprefix, 0, 100),
  182. '{suffix}' => $suffix,
  183. '{.suffix}' => $suffix ? '.' . $suffix : '',
  184. '{filemd5}' => $md5,
  185. ];
  186. $savekey = $savekey ? $savekey : $this->config['savekey'];
  187. $savekey = str_replace(array_keys($replaceArr), array_values($replaceArr), $savekey);
  188. return $savekey;
  189. }
  190. /**
  191. * 清理分片文件
  192. * @param $chunkid
  193. */
  194. public function clean($chunkid)
  195. {
  196. if (!preg_match('/^[a-z0-9\-]{36}$/', $chunkid)) {
  197. throw new UploadException(__('Invalid parameters'));
  198. }
  199. $iterator = new \GlobIterator($this->chunkDir . DS . $chunkid . '-*', FilesystemIterator::KEY_AS_FILENAME);
  200. $array = iterator_to_array($iterator);
  201. foreach ($array as $index => &$item) {
  202. $sourceFile = $item->getRealPath() ?: $item->getPathname();
  203. $item = null;
  204. @unlink($sourceFile);
  205. }
  206. }
  207. /**
  208. * 合并分片文件
  209. * @param string $chunkid
  210. * @param int $chunkcount
  211. * @param string $filename
  212. * @return attachment|\think\Model
  213. * @throws UploadException
  214. */
  215. public function merge($chunkid, $chunkcount, $filename)
  216. {
  217. if (!preg_match('/^[a-z0-9\-]{36}$/', $chunkid)) {
  218. throw new UploadException(__('Invalid parameters'));
  219. }
  220. $filePath = $this->chunkDir . DS . $chunkid;
  221. $completed = true;
  222. //检查所有分片是否都存在
  223. for ($i = 0; $i < $chunkcount; $i++) {
  224. if (!file_exists("{$filePath}-{$i}.part")) {
  225. $completed = false;
  226. break;
  227. }
  228. }
  229. if (!$completed) {
  230. $this->clean($chunkid);
  231. throw new UploadException(__('Chunk file info error'));
  232. }
  233. //如果所有文件分片都上传完毕,开始合并
  234. $uploadPath = $filePath;
  235. if (!$destFile = @fopen($uploadPath, "wb")) {
  236. $this->clean($chunkid);
  237. throw new UploadException(__('Chunk file merge error'));
  238. }
  239. if (flock($destFile, LOCK_EX)) { // 进行排他型锁定
  240. for ($i = 0; $i < $chunkcount; $i++) {
  241. $partFile = "{$filePath}-{$i}.part";
  242. if (!$handle = @fopen($partFile, "rb")) {
  243. break;
  244. }
  245. while ($buff = fread($handle, filesize($partFile))) {
  246. fwrite($destFile, $buff);
  247. }
  248. @fclose($handle);
  249. @unlink($partFile); //删除分片
  250. }
  251. flock($destFile, LOCK_UN);
  252. }
  253. @fclose($destFile);
  254. $attachment = null;
  255. try {
  256. $file = new File($uploadPath);
  257. $info = [
  258. 'name' => $filename,
  259. 'type' => $file->getMime(),
  260. 'tmp_name' => $uploadPath,
  261. 'error' => 0,
  262. 'size' => $file->getSize()
  263. ];
  264. $file->setSaveName($filename)->setUploadInfo($info);
  265. $file->isTest(true);
  266. //重新设置文件
  267. $this->setFile($file);
  268. unset($file);
  269. $this->merging = true;
  270. //允许大文件
  271. $this->config['maxsize'] = "1024G";
  272. $attachment = $this->upload();
  273. } catch (\Exception $e) {
  274. @unlink($destFile);
  275. throw new UploadException($e->getMessage());
  276. }
  277. return $attachment;
  278. }
  279. /**
  280. * 分片上传
  281. * @throws UploadException
  282. */
  283. public function chunk($chunkid, $chunkindex, $chunkcount, $chunkfilesize = null, $chunkfilename = null, $direct = false)
  284. {
  285. if ($this->fileInfo['type'] != 'application/octet-stream') {
  286. throw new UploadException(__('Uploaded file format is limited'));
  287. }
  288. if (!preg_match('/^[a-z0-9\-]{36}$/', $chunkid)) {
  289. throw new UploadException(__('Invalid parameters'));
  290. }
  291. $destDir = RUNTIME_PATH . 'chunks';
  292. $fileName = $chunkid . "-" . $chunkindex . '.part';
  293. $destFile = $destDir . DS . $fileName;
  294. if (!is_dir($destDir)) {
  295. @mkdir($destDir, 0755, true);
  296. }
  297. if (!move_uploaded_file($this->file->getPathname(), $destFile)) {
  298. throw new UploadException(__('Chunk file write error'));
  299. }
  300. $file = new File($destFile);
  301. $info = [
  302. 'name' => $fileName,
  303. 'type' => $file->getMime(),
  304. 'tmp_name' => $destFile,
  305. 'error' => 0,
  306. 'size' => $file->getSize()
  307. ];
  308. $file->setSaveName($fileName)->setUploadInfo($info);
  309. $this->setFile($file);
  310. return $file;
  311. }
  312. /**
  313. * 普通上传
  314. * @return \app\common\model\attachment|\think\Model
  315. * @throws UploadException
  316. */
  317. public function upload($savekey = null)
  318. {
  319. if (empty($this->file)) {
  320. throw new UploadException(__('No file upload or server upload limit exceeded'));
  321. }
  322. $this->checkSize();
  323. $this->checkExecutable();
  324. $this->checkMimetype();
  325. $this->checkImage();
  326. $savekey = $savekey ? $savekey : $this->getSavekey();
  327. $savekey = '/' . ltrim($savekey, '/');
  328. $uploadDir = substr($savekey, 0, strripos($savekey, '/') + 1);
  329. $fileName = substr($savekey, strripos($savekey, '/') + 1);
  330. $destDir = ROOT_PATH . 'public' . str_replace('/', DS, $uploadDir);
  331. $sha1 = $this->file->hash();
  332. //如果是合并文件
  333. if ($this->merging) {
  334. if (!$this->file->check()) {
  335. throw new UploadException($this->file->getError());
  336. }
  337. $destFile = $destDir . $fileName;
  338. $sourceFile = $this->file->getRealPath() ?: $this->file->getPathname();
  339. $info = $this->file->getInfo();
  340. $this->file = null;
  341. if (!is_dir($destDir)) {
  342. @mkdir($destDir, 0755, true);
  343. }
  344. rename($sourceFile, $destFile);
  345. $file = new File($destFile);
  346. $file->setSaveName($fileName)->setUploadInfo($info);
  347. } else {
  348. $file = $this->file->move($destDir, $fileName);
  349. if (!$file) {
  350. // 上传失败获取错误信息
  351. throw new UploadException($this->file->getError());
  352. }
  353. }
  354. $this->file = $file;
  355. $category = request()->post('category');
  356. $category = array_key_exists($category, config('site.attachmentcategory') ?? []) ? $category : '';
  357. $auth = Auth::instance();
  358. $params = array(
  359. 'admin_id' => (int)session('admin.id'),
  360. 'user_id' => (int)$auth->id,
  361. 'filename' => mb_substr(htmlspecialchars(strip_tags($this->fileInfo['name'])), 0, 100),
  362. 'category' => $category,
  363. 'filesize' => $this->fileInfo['size'],
  364. 'imagewidth' => $this->fileInfo['imagewidth'],
  365. 'imageheight' => $this->fileInfo['imageheight'],
  366. 'imagetype' => $this->fileInfo['suffix'],
  367. 'imageframes' => 0,
  368. 'mimetype' => $this->fileInfo['type'],
  369. 'url' => $uploadDir . $file->getSaveName(),
  370. 'uploadtime' => time(),
  371. 'storage' => 'local',
  372. 'sha1' => $sha1,
  373. 'extparam' => '',
  374. );
  375. $attachment = new Attachment();
  376. $attachment->data(array_filter($params));
  377. $attachment->save();
  378. \think\Hook::listen("upload_after", $attachment);
  379. return $attachment;
  380. }
  381. /**
  382. * 设置错误信息
  383. * @param $msg
  384. */
  385. public function setError($msg)
  386. {
  387. $this->error = $msg;
  388. }
  389. /**
  390. * 获取错误信息
  391. * @return string
  392. */
  393. public function getError()
  394. {
  395. return $this->error;
  396. }
  397. }