Upload.php 14 KB

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