Upload.php 12 KB

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