控制台应用,yzncms本身基于tp5.1框架,里面的队列用不了,bug,坑
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Upload.php 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | Yzncms [ 御宅男工作室 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2018 http://yzncms.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
  8. // +----------------------------------------------------------------------
  9. // | Author: fastadmin: https://www.fastadmin.net/
  10. // +----------------------------------------------------------------------
  11. // +----------------------------------------------------------------------
  12. // | 上传基础类
  13. // +----------------------------------------------------------------------
  14. namespace app\common\library;
  15. use app\common\exception\UploadException;
  16. use app\common\model\Attachment;
  17. use think\facade\Hook;
  18. use think\File;
  19. class Upload
  20. {
  21. protected $file = null;
  22. protected $fileInfo = null;
  23. protected $merging = false;
  24. protected $chunkDir = null;
  25. public function __construct($file = null)
  26. {
  27. $this->chunkDir = ROOT_PATH . 'runtime' . DS . 'chunks';
  28. if ($file) {
  29. $this->setFile($file);
  30. }
  31. }
  32. public function setFile($file)
  33. {
  34. if (empty($file)) {
  35. throw new UploadException('未上传文件或超出服务器上传限制');
  36. }
  37. $fileInfo = $file->getInfo();
  38. $suffix = strtolower(pathinfo($fileInfo['name'], PATHINFO_EXTENSION));
  39. $suffix = $suffix && preg_match("/^[a-zA-Z0-9]+$/", $suffix) ? $suffix : 'file';
  40. $fileInfo['suffix'] = $suffix;
  41. //$fileInfo['imagewidth'] = 0;
  42. //$fileInfo['imageheight'] = 0;
  43. $this->file = $file;
  44. $this->fileInfo = $fileInfo;
  45. $this->checkExecutable();
  46. }
  47. protected function checkExecutable()
  48. {
  49. //禁止上传PHP和HTML文件
  50. if (in_array($this->fileInfo['type'], ['text/x-php', 'text/html']) || in_array($this->fileInfo['suffix'], ['php', 'asp', 'exe', 'cmd', 'sh', 'bat', 'html', 'htm', 'phtml', 'phar']) || preg_match("/^php(.*)/i", $this->fileInfo['suffix'])) {
  51. throw new UploadException('上传文件格式受限制');
  52. }
  53. return true;
  54. }
  55. protected function checkImage($force = false)
  56. {
  57. //验证是否为图片文件
  58. 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', 'wbmp'])) {
  59. $imgInfo = getimagesize($this->fileInfo['tmp_name']);
  60. if (!$imgInfo || !isset($imgInfo[0]) || !isset($imgInfo[1])) {
  61. throw new UploadException('上传文件不是有效的图片文件');
  62. }
  63. //$this->fileInfo['imagewidth'] = isset($imgInfo[0]) ? $imgInfo[0] : 0;
  64. //$this->fileInfo['imageheight'] = isset($imgInfo[1]) ? $imgInfo[1] : 0;
  65. return true;
  66. } else {
  67. return !$force;
  68. }
  69. }
  70. protected function checkSize($dir)
  71. {
  72. // 附件大小限制
  73. $size_limit = $dir == 'images' ? config('site.upload_image_size') : config('site.upload_file_size');
  74. $size_limit = $size_limit * 1024;
  75. // 判断附件大小是否超过限制
  76. if ($size_limit > 0 && ($this->fileInfo['size'] > $size_limit)) {
  77. throw new UploadException('附件过大');
  78. }
  79. }
  80. protected function checkMimetype($dir)
  81. {
  82. $typeArr = explode('/', $this->fileInfo['type']);
  83. // 附件类型限制
  84. $ext_limit = $dir == 'images' ? config('site.upload_image_ext') : config('site.upload_file_ext');
  85. $ext_limit = $ext_limit != '' ? parse_attr($ext_limit) : [];
  86. // 判断附件格式是否符合
  87. $file_ext = $this->fileInfo['suffix'];
  88. $error_msg = '';
  89. if ($ext_limit == '') {
  90. $error_msg = '获取文件后缀限制信息失败!';
  91. }
  92. if (preg_grep("/php/i", $ext_limit)) {
  93. $error_msg = '禁止上传非法文件!';
  94. }
  95. if (!preg_grep("/$file_ext/i", $ext_limit) || !in_array($file_ext, $ext_limit)) {
  96. $error_msg = '附件类型不正确!';
  97. }
  98. if ($error_msg != '') {
  99. throw new UploadException($error_msg);
  100. }
  101. $typeArr = explode('/', $this->fileInfo['type']);
  102. //Mimetype值不正确
  103. if (stripos($this->fileInfo['type'], '/') === false) {
  104. throw new UploadException('上传文件格式受限制');
  105. }
  106. //验证文件后缀
  107. if (in_array($this->fileInfo['suffix'], $ext_limit) || in_array('.' . $this->fileInfo['suffix'], $ext_limit)
  108. || in_array($typeArr[0] . "/*", $ext_limit) || in_array($this->fileInfo['type'], $ext_limit)) {
  109. return true;
  110. }
  111. throw new UploadException('上传文件格式受限制');
  112. }
  113. /**
  114. * 保存附件
  115. * @param string $dir 附件存放的目录
  116. * @param string $from 来源
  117. * @return string|\think\response\Json
  118. */
  119. public function upload($dir = '', $from = '', $savekey = null)
  120. {
  121. if (empty($this->file)) {
  122. throw new UploadException('未上传文件或超出服务器上传限制');
  123. }
  124. $this->checkSize($dir);
  125. $this->checkMimetype($dir);
  126. $this->checkExecutable();
  127. $this->checkImage();
  128. // 判断附件是否已存在
  129. if ($file_exists = Attachment::get(['md5' => $this->file->hash('md5')])) {
  130. return json([
  131. 'code' => 1,
  132. 'msg' => $file_exists['name'] . '上传成功',
  133. 'id' => $file_exists['id'],
  134. 'path' => $file_exists['path'],
  135. "state" => "SUCCESS", // 上传状态,上传成功时必须返回"SUCCESS" 兼容百度
  136. "url" => $file_exists['path'], // 返回的地址 兼容百度
  137. "title" => $file_exists['name'], // 附件名 兼容百度
  138. "success" => 1, //兼容editormd
  139. "message" => $file_exists['name'], // 附件名 兼容editormd
  140. ]);
  141. }
  142. // 附件上传钩子,用于第三方文件上传扩展
  143. if (config('site.upload_driver') != 'local') {
  144. $hook_result = Hook::listen('upload_after', ['dir' => $dir, 'file' => $this->file, 'from' => $from], true);
  145. if (false !== $hook_result) {
  146. return $hook_result;
  147. }
  148. }
  149. $savekey = $savekey ?: $this->getSavekey($dir);
  150. $savekey = ltrim($savekey, '/');
  151. $uploadDir = substr($savekey, 0, strripos($savekey, '/') + 1);
  152. $fileName = substr($savekey, strripos($savekey, '/') + 1);
  153. $destDir = ROOT_PATH . 'public/' . str_replace('/', DS, $uploadDir);
  154. $sha1 = $this->file->hash();
  155. $md5 = $this->file->md5();
  156. //如果是合并文件
  157. if ($this->merging) {
  158. $destFile = $destDir . $fileName;
  159. $sourceFile = $this->file->getRealPath() ?: $this->file->getPathname();
  160. $fileinfo = $this->file->getInfo();
  161. $this->file = null;
  162. if (!is_dir($destDir)) {
  163. @mkdir($destDir, 0755, true);
  164. }
  165. rename($sourceFile, $destFile);
  166. $info = new File($destFile);
  167. $info->setSaveName($fileName)->setUploadInfo($fileinfo);
  168. } else {
  169. // 移动到框架应用根目录指定目录下
  170. $info = $this->file->move($destDir, $fileName);
  171. }
  172. if ($info) {
  173. // 水印功能
  174. if ($dir == 'images' && config('site.upload_thumb_water') == 1 && config('site.upload_thumb_water_pic') != "") {
  175. model('Attachment')->create_water($info->getRealPath(), config('site.upload_thumb_water_pic'));
  176. }
  177. // 获取附件信息
  178. $file_info = [
  179. 'admin_id' => (int) session('admin.id'),
  180. 'user_id' => (int) cookie('uid'),
  181. 'name' => mb_substr(htmlspecialchars(strip_tags($this->fileInfo['name'])), 0, 100),
  182. 'mime' => $this->fileInfo['type'],
  183. 'path' => cdnurl(config('public_url') . $uploadDir . $info->getSaveName()),
  184. 'ext' => $this->fileInfo['suffix'],
  185. 'size' => $this->fileInfo['size'],
  186. 'md5' => $md5,
  187. 'sha1' => $sha1,
  188. ];
  189. if ($file_add = Attachment::create($file_info)) {
  190. return json([
  191. 'code' => 1,
  192. 'msg' => $file_info['name'] . '上传成功',
  193. 'id' => $file_add['id'],
  194. 'path' => $file_info['path'],
  195. "state" => "SUCCESS", // 上传状态,上传成功时必须返回"SUCCESS" 兼容百度
  196. "url" => $file_info['path'], // 返回的地址 兼容百度
  197. "title" => $file_info['name'], // 附件名 兼容百度
  198. "success" => 1, //兼容editormd
  199. "message" => $file_info['name'], // 附件名 兼容editormd
  200. ]);
  201. } else {
  202. throw new UploadException('上传成功,写入数据库失败');
  203. }
  204. } else {
  205. throw new UploadException('上传失败');
  206. }
  207. }
  208. /**
  209. * 合并分片文件
  210. * @param string $chunkid
  211. * @param int $chunkcount
  212. * @param string $filename
  213. * @return attachment|\think\Model
  214. * @throws UploadException
  215. */
  216. public function merge($chunkid, $chunkcount, $filename, $dir, $from)
  217. {
  218. if (!preg_match('/^[a-z0-9\-]{36}$/', $chunkid)) {
  219. throw new UploadException('未知参数');
  220. }
  221. $filePath = $this->chunkDir . DS . $chunkid;
  222. $completed = true;
  223. //检查所有分片是否都存在
  224. for ($i = 0; $i < $chunkcount; $i++) {
  225. if (!file_exists("{$filePath}-{$i}.part")) {
  226. $completed = false;
  227. break;
  228. }
  229. }
  230. if (!$completed) {
  231. $this->clean($chunkid);
  232. throw new UploadException('分片文件错误');
  233. }
  234. //如果所有文件分片都上传完毕,开始合并
  235. $uploadPath = $filePath;
  236. if (!$destFile = @fopen($uploadPath, "wb")) {
  237. $this->clean($chunkid);
  238. throw new UploadException('分片合并错误');
  239. }
  240. if (flock($destFile, LOCK_EX)) {
  241. // 进行排他型锁定
  242. for ($i = 0; $i < $chunkcount; $i++) {
  243. $partFile = "{$filePath}-{$i}.part";
  244. if (!$handle = @fopen($partFile, "rb")) {
  245. break;
  246. }
  247. while ($buff = fread($handle, filesize($partFile))) {
  248. fwrite($destFile, $buff);
  249. }
  250. @fclose($handle);
  251. @unlink($partFile); //删除分片
  252. }
  253. flock($destFile, LOCK_UN);
  254. }
  255. @fclose($destFile);
  256. $attachment = null;
  257. try {
  258. $file = new File($uploadPath);
  259. $info = [
  260. 'name' => $filename,
  261. 'type' => $file->getMime(),
  262. 'tmp_name' => $uploadPath,
  263. 'error' => 0,
  264. 'size' => $file->getSize(),
  265. ];
  266. $file->setSaveName($filename)->setUploadInfo($info);
  267. $file->isTest(true);
  268. //重新设置文件
  269. $this->setFile($file);
  270. unset($file);
  271. $this->merging = true;
  272. //允许大文件
  273. $this->config['maxsize'] = "1024G";
  274. $attachment = $this->upload($dir, $from);
  275. } catch (\Exception $e) {
  276. @unlink($destFile);
  277. throw new UploadException($e->getMessage());
  278. }
  279. return $attachment;
  280. }
  281. /**
  282. * 清理分片文件
  283. * @param $chunkid
  284. */
  285. public function clean($chunkid)
  286. {
  287. if (!preg_match('/^[a-z0-9\_]+$/', $chunkid)) {
  288. throw new UploadException('未知参数');
  289. }
  290. $iterator = new \GlobIterator($this->chunkDir . DS . $chunkid . '-*', FilesystemIterator::KEY_AS_FILENAME);
  291. $array = iterator_to_array($iterator);
  292. foreach ($array as &$item) {
  293. $sourceFile = $item->getRealPath() ?: $item->getPathname();
  294. $item = null;
  295. @unlink($sourceFile);
  296. }
  297. }
  298. /**
  299. * 分片上传
  300. */
  301. public function chunk($chunkid, $chunkindex, $chunkcount, $chunkfilesize = null, $chunkfilename = null, $direct = false)
  302. {
  303. if ($this->fileInfo['type'] != 'application/octet-stream') {
  304. throw new UploadException('上传文件格式受限制');
  305. }
  306. if (!preg_match('/^[a-z0-9\-]{36}$/', $chunkid)) {
  307. throw new UploadException('未知参数');
  308. }
  309. $fileName = $chunkid . "-" . $chunkindex . '.part';
  310. $destFile = $this->chunkDir . DS . $fileName;
  311. if (!is_dir($this->chunkDir)) {
  312. @mkdir($this->chunkDir, 0755, true);
  313. }
  314. if (!move_uploaded_file($this->file->getPathname(), $destFile)) {
  315. throw new UploadException('分片写入失败');
  316. }
  317. $file = new File($destFile);
  318. $info = [
  319. 'name' => $fileName,
  320. 'type' => $file->getMime(),
  321. 'tmp_name' => $destFile,
  322. 'error' => 0,
  323. 'size' => $file->getSize(),
  324. ];
  325. $file->setSaveName($fileName)->setUploadInfo($info);
  326. $this->setFile($file);
  327. return $file;
  328. }
  329. protected function getSavekey($dir, $savekey = null, $filename = null, $md5 = null)
  330. {
  331. if ($filename) {
  332. $suffix = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
  333. } else {
  334. $suffix = $this->fileInfo['suffix'] ?? '';
  335. }
  336. $suffix = $suffix && preg_match("/^[a-zA-Z0-9]+$/", $suffix) ? $suffix : 'file';
  337. $filename = $filename ?: ($this->fileInfo['name'] ?? 'unknown');
  338. $filename = xss_clean(strip_tags(htmlspecialchars($filename)));
  339. $fileprefix = substr($filename, 0, strripos($filename, '.'));
  340. $md5 = $md5 ? $md5 : (isset($this->fileInfo['tmp_name']) ? md5_file($this->fileInfo['tmp_name']) : '');
  341. $replaceArr = [
  342. '{dir}' => $dir,
  343. '{year}' => date("Y"),
  344. '{mon}' => date("m"),
  345. '{day}' => date("d"),
  346. '{hour}' => date("H"),
  347. '{min}' => date("i"),
  348. '{sec}' => date("s"),
  349. '{random}' => \util\Random::alnum(16),
  350. '{random32}' => \util\Random::alnum(32),
  351. '{filename}' => substr($filename, 0, 100),
  352. '{fileprefix}' => substr($fileprefix, 0, 100),
  353. '{suffix}' => $suffix,
  354. '{.suffix}' => $suffix ? '.' . $suffix : '',
  355. '{filemd5}' => $md5,
  356. ];
  357. $savekey = $savekey ?: config('savekey');
  358. $savekey = str_replace(array_keys($replaceArr), array_values($replaceArr), $savekey);
  359. return $savekey;
  360. }
  361. }