Upload.php 12 KB

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