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