Upload.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  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 $chunkDir = null;
  26. protected $config = [];
  27. protected $error = '';
  28. /**
  29. * @var \think\File
  30. */
  31. protected $file = null;
  32. protected $fileInfo = null;
  33. public function __construct($file = null)
  34. {
  35. $this->config = Config::get('upload');
  36. $this->chunkDir = RUNTIME_PATH . 'chunks';
  37. if ($file) {
  38. $this->setFile($file);
  39. }
  40. }
  41. public function setChunkDir($dir)
  42. {
  43. $this->chunkDir = $dir;
  44. }
  45. public function getFile()
  46. {
  47. return $this->file;
  48. }
  49. public function setFile($file)
  50. {
  51. if (empty($file)) {
  52. throw new UploadException(__('No file upload or server upload limit exceeded'));
  53. }
  54. $fileInfo = $file->getInfo();
  55. $suffix = strtolower(pathinfo($fileInfo['name'], PATHINFO_EXTENSION));
  56. $suffix = $suffix && preg_match("/^[a-zA-Z0-9]+$/", $suffix) ? $suffix : 'file';
  57. $fileInfo['suffix'] = $suffix;
  58. $fileInfo['imagewidth'] = 0;
  59. $fileInfo['imageheight'] = 0;
  60. $this->file = $file;
  61. $this->fileInfo = $fileInfo;
  62. }
  63. protected function checkExecutable()
  64. {
  65. //禁止上传PHP和HTML文件
  66. if (in_array($this->fileInfo['type'], ['text/x-php', 'text/html']) || in_array($this->fileInfo['suffix'], ['php', 'html', 'htm'])) {
  67. throw new UploadException(__('Uploaded file format is limited'));
  68. }
  69. return true;
  70. }
  71. protected function checkMimetype()
  72. {
  73. $mimetypeArr = explode(',', strtolower($this->config['mimetype']));
  74. $typeArr = explode('/', $this->fileInfo['type']);
  75. //验证文件后缀
  76. if ($this->config['mimetype'] !== '*' &&
  77. (!in_array($this->fileInfo['suffix'], $mimetypeArr) || (stripos($typeArr[0] . '/', $this->config['mimetype']) !== false && (!in_array($this->fileInfo['type'], $mimetypeArr) && !in_array($typeArr[0] . '/*', $mimetypeArr))))
  78. ) {
  79. throw new UploadException(__('Uploaded file format is limited'));
  80. return false;
  81. }
  82. return true;
  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}' => $filename,
  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. var_dump($array);
  153. }
  154. public function merge($chunkid, $chunkcount, $filename)
  155. {
  156. $filePath = $this->chunkDir . DS . $chunkid;
  157. $completed = true;
  158. //检查所有分片是否都存在
  159. for ($i = 0; $i < $chunkcount; $i++) {
  160. if (!file_exists("{$filePath}-{$i}.part")) {
  161. $completed = false;
  162. break;
  163. }
  164. }
  165. if (!$completed) {
  166. throw new UploadException(__('Chunk file info error'));
  167. }
  168. //如果所有文件分片都上传完毕,开始合并
  169. $uploadPath = $filePath;
  170. if (!$destFile = @fopen($uploadPath, "wb")) {
  171. throw new UploadException(__('Chunk file merge error'));
  172. }
  173. if (flock($destFile, LOCK_EX)) { // 进行排他型锁定
  174. for ($i = 0; $i < $chunkcount; $i++) {
  175. $partFile = "{$filePath}-{$i}.part";
  176. if (!$handle = @fopen($partFile, "rb")) {
  177. break;
  178. }
  179. while ($buff = fread($handle, filesize($partFile))) {
  180. fwrite($destFile, $buff);
  181. }
  182. @fclose($handle);
  183. @unlink($partFile); //删除分片
  184. }
  185. flock($destFile, LOCK_UN);
  186. }
  187. @fclose($destFile);
  188. $file = new File($uploadPath);
  189. $info = [
  190. 'name' => $filename,
  191. 'type' => $file->getMime(),
  192. 'tmp_name' => $uploadPath,
  193. 'error' => 0,
  194. 'size' => $file->getSize()
  195. ];
  196. $file->setUploadInfo($info);
  197. $file->isTest(true);
  198. //重新设置文件
  199. $this->setFile($file);
  200. //允许大文件
  201. $this->config['maxsize'] = "1024G";
  202. return $this->upload();
  203. }
  204. /**
  205. * 分片上传
  206. * @throws UploadException
  207. */
  208. public function chunk($chunkid, $chunkindex, $chunkcount, $chunkfilesize = null, $chunkfilename = null, $direct = false)
  209. {
  210. if ($this->fileInfo['type'] != 'application/octet-stream') {
  211. throw new UploadException(__('Uploaded file format is limited'));
  212. }
  213. $destDir = RUNTIME_PATH . 'chunks';
  214. $fileName = $chunkid . "-" . $chunkindex . '.part';
  215. $destFile = $destDir . DS . $fileName;
  216. if (!is_dir($destDir)) {
  217. @mkdir($destDir, 0755, true);
  218. }
  219. if (!move_uploaded_file($this->file->getPathname(), $destFile)) {
  220. throw new UploadException(__('Chunk file write error'));
  221. }
  222. $file = new File($destFile);
  223. $this->setFile($file);
  224. return $file;
  225. }
  226. /**
  227. * 普通上传
  228. * @return \app\common\model\attachment|\think\Model
  229. * @throws UploadException
  230. */
  231. public function upload($savekey = null)
  232. {
  233. if (empty($this->file)) {
  234. throw new UploadException(__('No file upload or server upload limit exceeded'));
  235. }
  236. $this->checkSize();
  237. $this->checkExecutable();
  238. $this->checkMimetype();
  239. $this->checkImage();
  240. $savekey = $savekey ? $savekey : $this->getSavekey();
  241. $savekey = '/' . ltrim($savekey, '/');
  242. $uploadDir = substr($savekey, 0, strripos($savekey, '/') + 1);
  243. $fileName = substr($savekey, strripos($savekey, '/') + 1);
  244. $destDir = ROOT_PATH . 'public' . $uploadDir;
  245. $sha1 = $this->file->hash();
  246. $file = $this->file->move($destDir, $fileName);
  247. if (!$file) {
  248. // 上传失败获取错误信息
  249. throw new UploadException($this->file->getError());
  250. }
  251. $this->file = $file;
  252. $params = array(
  253. 'admin_id' => (int)session('admin.id'),
  254. 'user_id' => (int)cookie('uid'),
  255. 'filename' => htmlspecialchars(strip_tags($this->fileInfo['name'])),
  256. 'filesize' => $this->fileInfo['size'],
  257. 'imagewidth' => $this->fileInfo['imagewidth'],
  258. 'imageheight' => $this->fileInfo['imageheight'],
  259. 'imagetype' => $this->fileInfo['suffix'],
  260. 'imageframes' => 0,
  261. 'mimetype' => $this->fileInfo['type'],
  262. 'url' => $uploadDir . $file->getSaveName(),
  263. 'uploadtime' => time(),
  264. 'storage' => 'local',
  265. 'sha1' => $sha1,
  266. 'extparam' => '',
  267. );
  268. $attachment = new Attachment();
  269. $attachment->data(array_filter($params));
  270. $attachment->save();
  271. \think\Hook::listen("upload_after", $attachment);
  272. return $attachment;
  273. }
  274. public function setError($msg)
  275. {
  276. $this->error = $msg;
  277. }
  278. public function getError()
  279. {
  280. return $this->error;
  281. }
  282. }