Upload.php 13 KB

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