Upload.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  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 \think\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. public function setChunkDir($dir)
  33. {
  34. $this->chunkDir = $dir;
  35. }
  36. public function getFile()
  37. {
  38. return $this->file;
  39. }
  40. public function setFile($file)
  41. {
  42. if (empty($file)) {
  43. throw new UploadException(__('No file upload or server upload limit exceeded'));
  44. }
  45. $fileInfo = $file->getInfo();
  46. $suffix = strtolower(pathinfo($fileInfo['name'], PATHINFO_EXTENSION));
  47. $suffix = $suffix && preg_match("/^[a-zA-Z0-9]+$/", $suffix) ? $suffix : 'file';
  48. $fileInfo['suffix'] = $suffix;
  49. $fileInfo['imagewidth'] = 0;
  50. $fileInfo['imageheight'] = 0;
  51. $this->file = $file;
  52. $this->fileInfo = $fileInfo;
  53. $this->checkExecutable();
  54. }
  55. protected function checkExecutable()
  56. {
  57. //禁止上传PHP和HTML文件
  58. if (in_array($this->fileInfo['type'], ['text/x-php', 'text/html']) || in_array($this->fileInfo['suffix'], ['php', 'html', 'htm'])) {
  59. throw new UploadException(__('Uploaded file format is limited'));
  60. }
  61. return true;
  62. }
  63. protected function checkMimetype()
  64. {
  65. $mimetypeArr = explode(',', strtolower($this->config['mimetype']));
  66. $typeArr = explode('/', $this->fileInfo['type']);
  67. //验证文件后缀
  68. if ($this->config['mimetype'] === '*'
  69. || in_array($this->fileInfo['suffix'], $mimetypeArr) || in_array('.' . $this->fileInfo['suffix'], $mimetypeArr)
  70. || in_array($this->fileInfo['type'], $mimetypeArr) || in_array($typeArr[0] . "/*", $mimetypeArr)) {
  71. return true;
  72. }
  73. throw new UploadException(__('Uploaded file format is limited'));
  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'])) {
  79. $imgInfo = getimagesize($this->fileInfo['tmp_name']);
  80. if (!$imgInfo || !isset($imgInfo[0]) || !isset($imgInfo[1])) {
  81. throw new UploadException(__('Uploaded file is not a valid image'));
  82. }
  83. $this->fileInfo['imagewidth'] = isset($imgInfo[0]) ? $imgInfo[0] : 0;
  84. $this->fileInfo['imageheight'] = isset($imgInfo[1]) ? $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 = (int)($size * pow(1024, isset($typeDict[$type]) ? $typeDict[$type] : 0));
  97. if ($this->fileInfo['size'] > $size) {
  98. throw new UploadException(__('File is too big (%sMiB). Max filesize: %sMiB.',
  99. round($this->fileInfo['size'] / pow(1024, 2), 2),
  100. round($size / pow(1024, 2), 2)));
  101. }
  102. }
  103. public function getSuffix()
  104. {
  105. return $this->fileInfo['suffix'] ?: 'file';
  106. }
  107. public function getSavekey($savekey = null, $filename = null, $md5 = null)
  108. {
  109. if ($filename) {
  110. $suffix = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
  111. $suffix = $suffix && preg_match("/^[a-zA-Z0-9]+$/", $suffix) ? $suffix : 'file';
  112. } else {
  113. $suffix = $this->fileInfo['suffix'];
  114. }
  115. $filename = $filename ? $filename : ($suffix ? substr($this->fileInfo['name'], 0, strripos($this->fileInfo['name'], '.')) : $this->fileInfo['name']);
  116. $md5 = $md5 ? $md5 : md5_file($this->fileInfo['tmp_name']);
  117. $replaceArr = [
  118. '{year}' => date("Y"),
  119. '{mon}' => date("m"),
  120. '{day}' => date("d"),
  121. '{hour}' => date("H"),
  122. '{min}' => date("i"),
  123. '{sec}' => date("s"),
  124. '{random}' => Random::alnum(16),
  125. '{random32}' => Random::alnum(32),
  126. '{filename}' => substr($filename, 0, 100),
  127. '{suffix}' => $suffix,
  128. '{.suffix}' => $suffix ? '.' . $suffix : '',
  129. '{filemd5}' => $md5,
  130. ];
  131. $savekey = $savekey ? $savekey : $this->config['savekey'];
  132. $savekey = str_replace(array_keys($replaceArr), array_values($replaceArr), $savekey);
  133. return $savekey;
  134. }
  135. /**
  136. * 清理分片文件
  137. * @param $chunkid
  138. */
  139. public function clean($chunkid)
  140. {
  141. if (!preg_match('/^[a-z0-9\-]{36}$/', $chunkid)) {
  142. throw new UploadException(__('Invalid parameters'));
  143. }
  144. $iterator = new \GlobIterator($this->chunkDir . DS . $chunkid . '-*', FilesystemIterator::KEY_AS_FILENAME);
  145. $array = iterator_to_array($iterator);
  146. foreach ($array as $index => &$item) {
  147. $sourceFile = $item->getRealPath() ?: $item->getPathname();
  148. $item = null;
  149. @unlink($sourceFile);
  150. }
  151. }
  152. /**
  153. * 合并分片文件
  154. * @param string $chunkid
  155. * @param int $chunkcount
  156. * @param string $filename
  157. * @return attachment|\think\Model
  158. * @throws UploadException
  159. */
  160. public function merge($chunkid, $chunkcount, $filename)
  161. {
  162. if (!preg_match('/^[a-z0-9\-]{36}$/', $chunkid)) {
  163. throw new UploadException(__('Invalid parameters'));
  164. }
  165. $filePath = $this->chunkDir . DS . $chunkid;
  166. $completed = true;
  167. //检查所有分片是否都存在
  168. for ($i = 0; $i < $chunkcount; $i++) {
  169. if (!file_exists("{$filePath}-{$i}.part")) {
  170. $completed = false;
  171. break;
  172. }
  173. }
  174. if (!$completed) {
  175. $this->clean($chunkid);
  176. throw new UploadException(__('Chunk file info error'));
  177. }
  178. //如果所有文件分片都上传完毕,开始合并
  179. $uploadPath = $filePath;
  180. if (!$destFile = @fopen($uploadPath, "wb")) {
  181. $this->clean($chunkid);
  182. throw new UploadException(__('Chunk file merge error'));
  183. }
  184. if (flock($destFile, LOCK_EX)) { // 进行排他型锁定
  185. for ($i = 0; $i < $chunkcount; $i++) {
  186. $partFile = "{$filePath}-{$i}.part";
  187. if (!$handle = @fopen($partFile, "rb")) {
  188. break;
  189. }
  190. while ($buff = fread($handle, filesize($partFile))) {
  191. fwrite($destFile, $buff);
  192. }
  193. @fclose($handle);
  194. @unlink($partFile); //删除分片
  195. }
  196. flock($destFile, LOCK_UN);
  197. }
  198. @fclose($destFile);
  199. $attachment = null;
  200. try {
  201. $file = new File($uploadPath);
  202. $info = [
  203. 'name' => $filename,
  204. 'type' => $file->getMime(),
  205. 'tmp_name' => $uploadPath,
  206. 'error' => 0,
  207. 'size' => $file->getSize()
  208. ];
  209. $file->setSaveName($filename)->setUploadInfo($info);
  210. $file->isTest(true);
  211. //重新设置文件
  212. $this->setFile($file);
  213. unset($file);
  214. $this->merging = true;
  215. //允许大文件
  216. $this->config['maxsize'] = "1024G";
  217. $attachment = $this->upload();
  218. } catch (\Exception $e) {
  219. @unlink($destFile);
  220. throw new UploadException($e->getMessage());
  221. }
  222. return $attachment;
  223. }
  224. /**
  225. * 分片上传
  226. * @throws UploadException
  227. */
  228. public function chunk($chunkid, $chunkindex, $chunkcount, $chunkfilesize = null, $chunkfilename = null, $direct = false)
  229. {
  230. if ($this->fileInfo['type'] != 'application/octet-stream') {
  231. throw new UploadException(__('Uploaded file format is limited'));
  232. }
  233. if (!preg_match('/^[a-z0-9\-]{36}$/', $chunkid)) {
  234. throw new UploadException(__('Invalid parameters'));
  235. }
  236. $destDir = RUNTIME_PATH . 'chunks';
  237. $fileName = $chunkid . "-" . $chunkindex . '.part';
  238. $destFile = $destDir . DS . $fileName;
  239. if (!is_dir($destDir)) {
  240. @mkdir($destDir, 0755, true);
  241. }
  242. if (!move_uploaded_file($this->file->getPathname(), $destFile)) {
  243. throw new UploadException(__('Chunk file write error'));
  244. }
  245. $file = new File($destFile);
  246. $info = [
  247. 'name' => $fileName,
  248. 'type' => $file->getMime(),
  249. 'tmp_name' => $destFile,
  250. 'error' => 0,
  251. 'size' => $file->getSize()
  252. ];
  253. $file->setSaveName($fileName)->setUploadInfo($info);
  254. $this->setFile($file);
  255. return $file;
  256. }
  257. /**
  258. * 普通上传
  259. * @return \app\common\model\attachment|\think\Model
  260. * @throws UploadException
  261. */
  262. public function upload($savekey = null)
  263. {
  264. if (empty($this->file)) {
  265. throw new UploadException(__('No file upload or server upload limit exceeded'));
  266. }
  267. $this->checkSize();
  268. $this->checkExecutable();
  269. $this->checkMimetype();
  270. $this->checkImage();
  271. $savekey = $savekey ? $savekey : $this->getSavekey();
  272. $savekey = '/' . ltrim($savekey, '/');
  273. $uploadDir = substr($savekey, 0, strripos($savekey, '/') + 1);
  274. $fileName = substr($savekey, strripos($savekey, '/') + 1);
  275. $destDir = ROOT_PATH . 'public' . str_replace('/', DS, $uploadDir);
  276. $sha1 = $this->file->hash();
  277. //如果是合并文件
  278. if ($this->merging) {
  279. if (!$this->file->check()) {
  280. throw new UploadException($this->file->getError());
  281. }
  282. $destFile = $destDir . $fileName;
  283. $sourceFile = $this->file->getRealPath() ?: $this->file->getPathname();
  284. $info = $this->file->getInfo();
  285. $this->file = null;
  286. if (!is_dir($destDir)) {
  287. @mkdir($destDir, 0755, true);
  288. }
  289. rename($sourceFile, $destFile);
  290. $file = new File($destFile);
  291. $file->setSaveName($fileName)->setUploadInfo($info);
  292. } else {
  293. $file = $this->file->move($destDir, $fileName);
  294. if (!$file) {
  295. // 上传失败获取错误信息
  296. throw new UploadException($this->file->getError());
  297. }
  298. }
  299. $this->file = $file;
  300. $category = request()->post('category');
  301. $category = array_key_exists($category, config('site.attachmentcategory') ?? []) ? $category : '';
  302. $auth = Auth::instance();
  303. $params = array(
  304. 'admin_id' => (int)session('admin.id'),
  305. 'user_id' => (int)$auth->id,
  306. 'filename' => mb_substr(htmlspecialchars(strip_tags($this->fileInfo['name'])), 0, 100),
  307. 'category' => $category,
  308. 'filesize' => $this->fileInfo['size'],
  309. 'imagewidth' => $this->fileInfo['imagewidth'],
  310. 'imageheight' => $this->fileInfo['imageheight'],
  311. 'imagetype' => $this->fileInfo['suffix'],
  312. 'imageframes' => 0,
  313. 'mimetype' => $this->fileInfo['type'],
  314. 'url' => $uploadDir . $file->getSaveName(),
  315. 'uploadtime' => time(),
  316. 'storage' => 'local',
  317. 'sha1' => $sha1,
  318. 'extparam' => '',
  319. );
  320. $attachment = new Attachment();
  321. $attachment->data(array_filter($params));
  322. $attachment->save();
  323. \think\Hook::listen("upload_after", $attachment);
  324. return $attachment;
  325. }
  326. public function setError($msg)
  327. {
  328. $this->error = $msg;
  329. }
  330. public function getError()
  331. {
  332. return $this->error;
  333. }
  334. }