SystemFileServices.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2016~2023 https://www.crmeb.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed CRMEB并不是自由软件,未经许可不能去掉CRMEB相关版权
  8. // +----------------------------------------------------------------------
  9. // | Author: CRMEB Team <admin@crmeb.com>
  10. // +----------------------------------------------------------------------
  11. namespace app\services\system\log;
  12. use app\dao\system\log\SystemFileDao;
  13. use app\services\BaseServices;
  14. use app\services\system\admin\SystemAdminServices;
  15. use crmeb\exceptions\AdminException;
  16. use crmeb\exceptions\AuthException;
  17. use crmeb\services\CacheService;
  18. use crmeb\services\FileService as FileClass;
  19. use crmeb\utils\JwtAuth;
  20. use Firebase\JWT\ExpiredException;
  21. use think\facade\Log;
  22. /**
  23. * 文件校验
  24. * Class SystemFileServices
  25. * @package app\services\system\log
  26. */
  27. class SystemFileServices extends BaseServices
  28. {
  29. /**
  30. * 构造方法
  31. * SystemFileServices constructor.
  32. * @param SystemFileDao $dao
  33. */
  34. public function __construct(SystemFileDao $dao)
  35. {
  36. $this->dao = $dao;
  37. }
  38. /**
  39. * @param array $admin
  40. * @param string $password
  41. * @param string $type
  42. * @return array
  43. * @throws \think\db\exception\DataNotFoundException
  44. * @throws \think\db\exception\DbException
  45. * @throws \think\db\exception\ModelNotFoundException
  46. *
  47. * @date 2022/09/07
  48. * @author yyw
  49. */
  50. public function Login(string $password, string $type)
  51. {
  52. if (config('filesystem.password') !== $password) {
  53. throw new AdminException(400140);
  54. }
  55. $md5Password = md5($password);
  56. /** @var JwtAuth $jwtAuth */
  57. $jwtAuth = app()->make(JwtAuth::class);
  58. $tokenInfo = $jwtAuth->createToken($md5Password, $type, ['pwd' => $md5Password]);
  59. CacheService::set(md5($tokenInfo['token']), $tokenInfo['token'], 3600);
  60. return [
  61. 'token' => md5($tokenInfo['token']),
  62. 'expires_time' => $tokenInfo['params']['exp'],
  63. ];
  64. }
  65. /**
  66. * 获取Admin授权信息
  67. * @param string $token
  68. * @return bool
  69. * @throws \Psr\SimpleCache\InvalidArgumentException
  70. */
  71. public function parseToken(string $token): bool
  72. {
  73. /** @var CacheService $cacheService */
  74. $cacheService = app()->make(CacheService::class);
  75. if (!$token || $token === 'undefined') {
  76. throw new AuthException(110008);
  77. }
  78. /** @var JwtAuth $jwtAuth */
  79. $jwtAuth = app()->make(JwtAuth::class);
  80. //设置解析token
  81. [$id, $type, $pwd] = $jwtAuth->parseToken($token);
  82. //检测token是否过期
  83. $md5Token = md5($token);
  84. if (!$cacheService->has($md5Token) || !($cacheService->get($md5Token))) {
  85. throw new AuthException(110008);
  86. }
  87. //验证token
  88. try {
  89. $jwtAuth->verifyToken();
  90. } catch (\Throwable $e) {
  91. if (!request()->isCli()) {
  92. $cacheService->delete($md5Token);
  93. }
  94. throw new AuthException(110008);
  95. }
  96. if ($id !== md5(config('filesystem.password'))) {
  97. throw new AuthException(110008);
  98. }
  99. if ($pwd !== md5(config('filesystem.password'))) {
  100. throw new AuthException(110008);
  101. }
  102. return true;
  103. }
  104. /**
  105. * 获取文件校验列表
  106. * @return array
  107. * @throws \think\db\exception\DataNotFoundException
  108. * @throws \think\db\exception\DbException
  109. * @throws \think\db\exception\ModelNotFoundException
  110. */
  111. public function getFileList()
  112. {
  113. $rootPath = app()->getRootPath();
  114. $key = 'system_file_app_crmeb_public';
  115. $arr = CacheService::get(md5($key));
  116. if (!$arr) {
  117. $app = $this->getDir($rootPath . 'app');
  118. $extend = $this->getDir($rootPath . 'crmeb');
  119. $arr = array_merge($app, $extend);
  120. CacheService::set(md5($key), $arr, 3600 * 24);
  121. }
  122. $fileAll = [];//本地文件
  123. $cha = [];//不同的文件
  124. $len = strlen($rootPath);
  125. $file = $this->dao->getAll();//数据库中的文件
  126. if (empty($file)) {
  127. foreach ($arr as $k => $v) {
  128. $update_time = stat($v);
  129. $fileAll[$k]['cthash'] = md5_file($v);
  130. $fileAll[$k]['filename'] = substr($v, $len);
  131. $fileAll[$k]['atime'] = $update_time['atime'];
  132. $fileAll[$k]['mtime'] = $update_time['mtime'];
  133. $fileAll[$k]['ctime'] = $update_time['ctime'];
  134. }
  135. $data_num = array_chunk($fileAll, 100);
  136. $res = true;
  137. $res = $this->transaction(function () use ($data_num, $res) {
  138. foreach ($data_num as $k => $v) {
  139. $res = $res && $this->dao->saveAll($v);
  140. }
  141. return $res;
  142. });
  143. if ($res) {
  144. $cha = [];//不同的文件
  145. } else {
  146. $cha = $fileAll;
  147. }
  148. } else {
  149. $file = array_combine(array_column($file, 'filename'), $file);
  150. foreach ($arr as $ko => $vo) {
  151. $update_time = stat($vo);
  152. $cthash = md5_file($vo);
  153. $cha[] = [
  154. 'filename' => str_replace($rootPath, '', $vo),
  155. 'cthash' => $cthash,
  156. 'atime' => date('Y-m-d H:i:s', $update_time['atime']),
  157. 'mtime' => date('Y-m-d H:i:s', $update_time['mtime']),
  158. 'ctime' => date('Y-m-d H:i:s', $update_time['ctime']),
  159. 'type' => '新增的',
  160. ];
  161. if (isset($file[$vo]) && $file[$vo] != $cthash) {
  162. $cha[] = [
  163. 'type' => '已修改',
  164. ];
  165. unset($file[$vo]);
  166. }
  167. }
  168. foreach ($file as $k => $v) {
  169. $cha[] = [
  170. 'filename' => $v['filename'],
  171. 'cthash' => $v['cthash'],
  172. 'atime' => date('Y-m-d H:i:s', $v['atime']),
  173. 'mtime' => date('Y-m-d H:i:s', $v['mtime']),
  174. 'ctime' => date('Y-m-d H:i:s', $v['ctime']),
  175. 'type' => '已删除',
  176. ];
  177. }
  178. }
  179. $ctime = array_column($cha, 'ctime');
  180. array_multisort($ctime, SORT_DESC, $cha);
  181. return $cha;
  182. }
  183. /**
  184. * 获取文件夹中的文件 包括子文件
  185. * @param $dir
  186. * @return array
  187. */
  188. public function getDir($dir)
  189. {
  190. $data = [];
  191. $this->searchDir($dir, $data);
  192. return $data;
  193. }
  194. /**
  195. * 获取文件夹中的文件 包括子文件 不能直接用 直接使用 $this->getDir()方法 P156
  196. * @param $path
  197. * @param $data
  198. */
  199. public function searchDir($path, &$data)
  200. {
  201. if (is_dir($path) && !strpos($path, 'uploads')) {
  202. $files = scandir($path);
  203. foreach ($files as $file) {
  204. if ($file != '.' && $file != '..') {
  205. $this->searchDir($path . '/' . $file, $data);
  206. }
  207. }
  208. }
  209. if (is_file($path)) {
  210. $data[] = $path;
  211. }
  212. }
  213. //打开目录
  214. public function opendir()
  215. {
  216. $fileAll = array('dir' => [], 'file' => []);
  217. //根目录
  218. $rootdir = $this->formatPath(app()->getRootPath());
  219. // return $rootdir;
  220. //当前目录
  221. $request_dir = app('request')->param('dir');
  222. //防止查看站点以外的目录
  223. if (strpos($request_dir, $rootdir) === false) {
  224. $request_dir = $rootdir;
  225. }
  226. //判断是否是返回上级
  227. if (app('request')->param('superior') && !empty($request_dir)) {
  228. if (strpos(dirname($request_dir), $rootdir) !== false) {
  229. $dir = dirname($request_dir);
  230. } else {
  231. $dir = $rootdir;
  232. }
  233. } else {
  234. $dir = !empty($request_dir) ? $request_dir : $rootdir;
  235. $dir = rtrim($dir, DS) . DS . app('request')->param('filedir');
  236. }
  237. $list = scandir($dir);
  238. foreach ($list as $key => $v) {
  239. if ($v != '.' && $v != '..') {
  240. if (is_dir($dir . DS . $v)) {
  241. $fileAll['dir'][] = FileClass::listInfo($dir . DS . $v);
  242. }
  243. if (is_file($dir . DS . $v)) {
  244. $fileAll['file'][] = FileClass::listInfo($dir . DS . $v);
  245. }
  246. }
  247. }
  248. //兼容windows
  249. $uname = php_uname('s');
  250. if (strstr($uname, 'Windows') !== false) {
  251. $dir = ltrim($dir, '\\');
  252. $rootdir = str_replace('\\', '\\\\', $rootdir);
  253. }
  254. $list = array_merge($fileAll['dir'], $fileAll['file']);
  255. $navList = [];
  256. foreach ($list as $key => $value) {
  257. $list[$key]['real_path'] = str_replace($rootdir, '', $value['pathname']);
  258. $list[$key]['mtime'] = date('Y-m-d H:i:s', $value['mtime']);
  259. $navList[$key]['title'] = $value['filename'];
  260. if ($value['isDir']) $navList[$key]['loading'] = false;
  261. $navList[$key]['children'] = [];
  262. $navList[$key]['path'] = $value['path'];
  263. $navList[$key]['isDir'] = $value['isDir'];
  264. $navList[$key]['pathname'] = $value['pathname'];
  265. $navList[$key]['contextmenu'] = true;
  266. }
  267. return compact('dir', 'list', 'navList');
  268. }
  269. //读取文件
  270. public function openfile($filepath)
  271. {
  272. $filepath = $this->formatPath($filepath);
  273. $content = FileClass::readFile($filepath);//防止页面内嵌textarea标签
  274. $ext = FileClass::getExt($filepath);
  275. $encoding = mb_detect_encoding($content, mb_detect_order());
  276. //前端组件支持的语言类型
  277. //['plaintext', 'json', 'abap', 'apex', 'azcli', 'bat', 'cameligo', 'clojure', 'coffeescript', 'c', 'cpp', 'csharp', 'csp', 'css', 'dart', 'dockerfile', 'fsharp', 'go', 'graphql', 'handlebars', 'hcl', 'html', 'ini', 'java', 'javascript', 'julia', 'kotlin', 'less', 'lexon', 'lua', 'markdown', 'mips', 'msdax', 'mysql', 'objective-c', 'pascal', 'pascaligo', 'perl', 'pgsql', 'php', 'postiats', 'powerquery', 'powershell', 'pug', 'python', 'r', 'razor', 'redis', 'redshift', 'restructuredtext', 'ruby', 'rust', 'sb', 'scala', 'scheme', 'scss', 'shell', 'sol', 'aes', 'sql', 'st', 'swift', 'systemverilog', 'verilog', 'tcl', 'twig', 'typescript', 'vb', 'xml', 'yaml']
  278. $extarray = [
  279. 'js' => 'javascript'
  280. , 'htm' => 'html'
  281. , 'shtml' => 'html'
  282. , 'html' => 'html'
  283. , 'xml' => 'xml'
  284. , 'php' => 'php'
  285. , 'sql' => 'mysql'
  286. , 'css' => 'css'
  287. , 'txt' => 'plaintext'
  288. , 'vue' => 'html'
  289. , 'json' => 'json'
  290. , 'lock' => 'json'
  291. , 'md' => 'markdown'
  292. , 'bat' => 'bat'
  293. , 'ini' => 'ini'
  294. ];
  295. $mode = empty($extarray[$ext]) ? 'php' : $extarray[$ext];
  296. return compact('content', 'mode', 'filepath', 'encoding');
  297. }
  298. //保存文件
  299. public function savefile($filepath, $comment)
  300. {
  301. $filepath = $this->formatPath($filepath);
  302. if (!FileClass::isWritable($filepath)) {
  303. throw new AdminException(400611);
  304. }
  305. return FileClass::writeFile($filepath, $comment);
  306. }
  307. // 文件重命名
  308. public function rename($newname, $oldname)
  309. {
  310. if (($newname != $oldname) && is_writable($oldname)) {
  311. return rename($oldname, $newname);
  312. }
  313. return true;
  314. }
  315. /**
  316. * 删除文件或文件夹
  317. * @param string $path
  318. * @return bool
  319. *
  320. * @date 2022/09/20
  321. * @author yyw
  322. */
  323. public function delFolder(string $path)
  324. {
  325. $path = $this->formatPath($path);
  326. if (is_file($path)) {
  327. return unlink($path);
  328. }
  329. $dir = opendir($path);
  330. while ($fileName = readdir($dir)) {
  331. $file = $path . '/' . $fileName;
  332. if ($fileName != '.' && $fileName != '..') {
  333. if (is_dir($file)) {
  334. self::delFolder($file);
  335. } else {
  336. unlink($file);
  337. }
  338. }
  339. }
  340. closedir($dir);
  341. return rmdir($path);
  342. }
  343. /**
  344. * 新建文件夹
  345. * @param string $path
  346. * @param string $name
  347. * @param int $permissions
  348. * @return bool
  349. *
  350. * @date 2022/09/20
  351. * @author yyw
  352. */
  353. public function createFolder(string $path, string $name, int $permissions = 0755)
  354. {
  355. $path = $this->formatPath($path, $name);
  356. /** @var FileClass $fileClass */
  357. $fileClass = app()->make(FileClass::class);
  358. return $fileClass->createDir($path, $permissions);
  359. }
  360. /**
  361. * 新建文件
  362. * @param string $path
  363. * @param string $name
  364. * @return bool
  365. *
  366. * @date 2022/09/20
  367. * @author yyw
  368. */
  369. public function createFile(string $path, string $name)
  370. {
  371. $path = $this->formatPath($path, $name);
  372. /** @var FileClass $fileClass */
  373. $fileClass = app()->make(FileClass::class);
  374. return $fileClass->createFile($path);
  375. }
  376. public function copyFolder($surDir, $toDir)
  377. {
  378. return FileClass::copyDir($surDir, $toDir);
  379. }
  380. /**
  381. * 格式化路径
  382. * @param string $path
  383. * @param string $name
  384. * @return string
  385. *
  386. * @date 2022/09/20
  387. * @author yyw
  388. */
  389. public function formatPath(string $path = '', string $name = ''): string
  390. {
  391. if ($path) {
  392. $path = rtrim($path, DS);
  393. if ($name) $path = $path . DS . $name;
  394. $uname = php_uname('s');
  395. // $search = '/';
  396. if (strstr($uname, 'Windows') !== false)
  397. $path = ltrim(str_replace('\\', '\\\\', $path), '.');
  398. }
  399. return $path;
  400. }
  401. }