Upload.php 13 KB

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