Upload.php 14 KB

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