SystemFileServices.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  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\services\FormBuilder as Form;
  20. use crmeb\utils\JwtAuth;
  21. use Firebase\JWT\ExpiredException;
  22. use think\facade\Log;
  23. use think\facade\Route as Url;
  24. /**
  25. * 文件校验
  26. * Class SystemFileServices
  27. * @package app\services\system\log
  28. */
  29. class SystemFileServices extends BaseServices
  30. {
  31. /**
  32. * 构造方法
  33. * SystemFileServices constructor.
  34. * @param SystemFileDao $dao
  35. */
  36. public function __construct(SystemFileDao $dao)
  37. {
  38. $this->dao = $dao;
  39. }
  40. /**
  41. * @param array $admin
  42. * @param string $password
  43. * @param string $type
  44. * @return array
  45. * @throws \think\db\exception\DataNotFoundException
  46. * @throws \think\db\exception\DbException
  47. * @throws \think\db\exception\ModelNotFoundException
  48. *
  49. * @date 2022/09/07
  50. * @author yyw
  51. */
  52. public function Login(string $password, string $type)
  53. {
  54. if (config('filesystem.password') !== $password) {
  55. throw new AdminException(400140);
  56. }
  57. $md5Password = md5($password);
  58. /** @var JwtAuth $jwtAuth */
  59. $jwtAuth = app()->make(JwtAuth::class);
  60. $tokenInfo = $jwtAuth->createToken($md5Password, $type, ['pwd' => $md5Password]);
  61. CacheService::set(md5($tokenInfo['token']), $tokenInfo['token'], 3600);
  62. return [
  63. 'token' => md5($tokenInfo['token']),
  64. 'expires_time' => $tokenInfo['params']['exp'],
  65. ];
  66. }
  67. /**
  68. * 获取Admin授权信息
  69. * @param string $token
  70. * @return bool
  71. * @throws \Psr\SimpleCache\InvalidArgumentException
  72. */
  73. public function parseToken(string $token): bool
  74. {
  75. /** @var CacheService $cacheService */
  76. $cacheService = app()->make(CacheService::class);
  77. if (!$token || $token === 'undefined') {
  78. throw new AuthException(110008);
  79. }
  80. /** @var JwtAuth $jwtAuth */
  81. $jwtAuth = app()->make(JwtAuth::class);
  82. //设置解析token
  83. [$id, $type, $pwd] = $jwtAuth->parseToken($token);
  84. //检测token是否过期
  85. $md5Token = md5($token);
  86. if (!$cacheService->has($md5Token) || !($cacheService->get($md5Token))) {
  87. throw new AuthException(110008);
  88. }
  89. //验证token
  90. try {
  91. $jwtAuth->verifyToken();
  92. } catch (\Throwable $e) {
  93. if (!request()->isCli()) {
  94. $cacheService->delete($md5Token);
  95. }
  96. throw new AuthException(110008);
  97. }
  98. if ($id !== md5(config('filesystem.password'))) {
  99. throw new AuthException(110008);
  100. }
  101. if ($pwd !== md5(config('filesystem.password'))) {
  102. throw new AuthException(110008);
  103. }
  104. return true;
  105. }
  106. /**
  107. * 获取文件校验列表
  108. * @return array
  109. * @throws \think\db\exception\DataNotFoundException
  110. * @throws \think\db\exception\DbException
  111. * @throws \think\db\exception\ModelNotFoundException
  112. */
  113. public function getFileList()
  114. {
  115. $rootPath = app()->getRootPath();
  116. $key = 'system_file_app_crmeb_public';
  117. $arr = CacheService::get(md5($key));
  118. if (!$arr) {
  119. $app = $this->getDir($rootPath . 'app');
  120. $extend = $this->getDir($rootPath . 'crmeb');
  121. $arr = array_merge($app, $extend);
  122. CacheService::set(md5($key), $arr, 3600 * 24);
  123. }
  124. $fileAll = [];//本地文件
  125. $cha = [];//不同的文件
  126. $len = strlen($rootPath);
  127. $file = $this->dao->getAll();//数据库中的文件
  128. if (empty($file)) {
  129. foreach ($arr as $k => $v) {
  130. $update_time = stat($v);
  131. $fileAll[$k]['cthash'] = md5_file($v);
  132. $fileAll[$k]['filename'] = substr($v, $len);
  133. $fileAll[$k]['atime'] = $update_time['atime'];
  134. $fileAll[$k]['mtime'] = $update_time['mtime'];
  135. $fileAll[$k]['ctime'] = $update_time['ctime'];
  136. }
  137. $data_num = array_chunk($fileAll, 100);
  138. $res = true;
  139. $res = $this->transaction(function () use ($data_num, $res) {
  140. foreach ($data_num as $k => $v) {
  141. $res = $res && $this->dao->saveAll($v);
  142. }
  143. return $res;
  144. });
  145. if ($res) {
  146. $cha = [];//不同的文件
  147. } else {
  148. $cha = $fileAll;
  149. }
  150. } else {
  151. $file = array_combine(array_column($file, 'filename'), $file);
  152. foreach ($arr as $ko => $vo) {
  153. $update_time = stat($vo);
  154. $cthash = md5_file($vo);
  155. $cha[] = [
  156. 'filename' => str_replace($rootPath, '', $vo),
  157. 'cthash' => $cthash,
  158. 'atime' => date('Y-m-d H:i:s', $update_time['atime']),
  159. 'mtime' => date('Y-m-d H:i:s', $update_time['mtime']),
  160. 'ctime' => date('Y-m-d H:i:s', $update_time['ctime']),
  161. 'type' => '新增的',
  162. ];
  163. if (isset($file[$vo]) && $file[$vo] != $cthash) {
  164. $cha[] = [
  165. 'type' => '已修改',
  166. ];
  167. unset($file[$vo]);
  168. }
  169. }
  170. foreach ($file as $k => $v) {
  171. $cha[] = [
  172. 'filename' => $v['filename'],
  173. 'cthash' => $v['cthash'],
  174. 'atime' => date('Y-m-d H:i:s', $v['atime']),
  175. 'mtime' => date('Y-m-d H:i:s', $v['mtime']),
  176. 'ctime' => date('Y-m-d H:i:s', $v['ctime']),
  177. 'type' => '已删除',
  178. ];
  179. }
  180. }
  181. $ctime = array_column($cha, 'ctime');
  182. array_multisort($ctime, SORT_DESC, $cha);
  183. return $cha;
  184. }
  185. /**
  186. * 获取文件夹中的文件 包括子文件
  187. * @param $dir
  188. * @return array
  189. */
  190. public function getDir($dir)
  191. {
  192. $data = [];
  193. $this->searchDir($dir, $data);
  194. return $data;
  195. }
  196. /**
  197. * 获取文件夹中的文件 包括子文件 不能直接用 直接使用 $this->getDir()方法 P156
  198. * @param $path
  199. * @param $data
  200. */
  201. public function searchDir($path, &$data)
  202. {
  203. if (is_dir($path) && !strpos($path, 'uploads')) {
  204. $files = scandir($path);
  205. foreach ($files as $file) {
  206. if ($file != '.' && $file != '..') {
  207. $this->searchDir($path . '/' . $file, $data);
  208. }
  209. }
  210. }
  211. if (is_file($path)) {
  212. $data[] = $path;
  213. }
  214. }
  215. //打开目录
  216. public function opendir($dir, $fileDir, $superior)
  217. {
  218. $markList = app()->make(SystemFileInfoServices::class)->getColumn([], 'mark', 'full_path');
  219. $fileAll = array('dir' => [], 'file' => []);
  220. //根目录
  221. $rootDir = $this->formatPath(app()->getRootPath());
  222. //防止查看站点以外的目录
  223. if (strpos($dir, $rootDir) === false || $dir == '') {
  224. $dir = $rootDir;
  225. }
  226. //判断是否是返回上级
  227. if ($superior) {
  228. if (strpos(dirname($dir), $rootDir) !== false) {
  229. $dir = dirname($dir);
  230. } else {
  231. $dir = $rootDir;
  232. }
  233. } else {
  234. $dir = $dir . '/' . $fileDir;
  235. }
  236. $list = scandir($dir);
  237. foreach ($list as $key => $v) {
  238. if ($v != '.' && $v != '..') {
  239. if (is_dir($dir . DS . $v)) {
  240. $fileAll['dir'][] = FileClass::listInfo($dir . DS . $v);
  241. }
  242. if (is_file($dir . DS . $v)) {
  243. $fileAll['file'][] = FileClass::listInfo($dir . DS . $v);
  244. }
  245. }
  246. }
  247. //兼容windows
  248. $uname = php_uname('s');
  249. if (strstr($uname, 'Windows') !== false) {
  250. $dir = ltrim($dir, '\\');
  251. $rootDir = str_replace('\\', '\\\\', $rootDir);
  252. }
  253. $list = array_merge($fileAll['dir'], $fileAll['file']);
  254. $navList = [];
  255. foreach ($list as $key => $value) {
  256. $list[$key]['real_path'] = str_replace($rootDir, '', $value['pathname']);
  257. $list[$key]['mtime'] = date('Y-m-d H:i:s', $value['mtime']);
  258. $navList[$key]['title'] = $value['filename'];
  259. if ($value['isDir']) $navList[$key]['loading'] = false;
  260. $navList[$key]['children'] = [];
  261. $navList[$key]['path'] = $value['path'];
  262. $navList[$key]['isDir'] = $value['isDir'];
  263. $navList[$key]['isLeaf'] = !$value['isDir'];
  264. $navList[$key]['pathname'] = $value['pathname'];
  265. $navList[$key]['contextmenu'] = true;
  266. $list[$key]['mark'] = $markList[str_replace(root_path(), '/', $value['pathname'])] ?? '';
  267. $count = app()->make(SystemFileInfoServices::class)->count(['full_path' => $list[$key]['real_path']]);
  268. if (!$count) app()->make(SystemFileInfoServices::class)->save([
  269. 'name' => $value['filename'],
  270. 'path' => str_replace('/' . $value['filename'], '', $list[$key]['real_path']),
  271. 'full_path' => $list[$key]['real_path'],
  272. 'type' => $value['type'],
  273. 'create_time' => date('Y-m-d H:i:s', $value['ctime']),
  274. 'update_time' => date('Y-m-d H:i:s', time()),
  275. ]);
  276. }
  277. $routeList = [['key' => '根目录', 'route' => '']];
  278. $pathArray = explode('/', str_replace($rootDir, '', $dir));
  279. $str = '';
  280. foreach ($pathArray as $item) {
  281. if ($item) {
  282. $str = $str . '/' . $item;
  283. $routeList[] = ['key' => $item, 'route' => $rootDir . $str];
  284. }
  285. }
  286. return compact('dir', 'list', 'navList', 'routeList');
  287. }
  288. //读取文件
  289. public function openfile($filepath)
  290. {
  291. //根目录
  292. $rootDir = $this->formatPath(app()->getRootPath());
  293. //防止查看站点以外的文件
  294. if (strpos($filepath, $rootDir) === false || $filepath == '') {
  295. throw new AdminException('无法打开站点以外的文件');
  296. }
  297. $filepath = $this->formatPath($filepath);
  298. $content = FileClass::readFile($filepath);//防止页面内嵌textarea标签
  299. $ext = FileClass::getExt($filepath);
  300. $encoding = mb_detect_encoding($content, mb_detect_order());
  301. //前端组件支持的语言类型
  302. //['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']
  303. $extarray = [
  304. 'js' => 'javascript'
  305. , 'htm' => 'html'
  306. , 'shtml' => 'html'
  307. , 'html' => 'html'
  308. , 'xml' => 'xml'
  309. , 'php' => 'php'
  310. , 'sql' => 'mysql'
  311. , 'css' => 'css'
  312. , 'txt' => 'plaintext'
  313. , 'vue' => 'html'
  314. , 'json' => 'json'
  315. , 'lock' => 'json'
  316. , 'md' => 'markdown'
  317. , 'bat' => 'bat'
  318. , 'ini' => 'ini'
  319. ];
  320. $mode = empty($extarray[$ext]) ? 'php' : $extarray[$ext];
  321. return compact('content', 'mode', 'filepath', 'encoding');
  322. }
  323. //保存文件
  324. public function savefile($filepath, $comment)
  325. {
  326. $filepath = $this->formatPath($filepath);
  327. if (!FileClass::isWritable($filepath)) {
  328. throw new AdminException('请检查目录权限,需要给全部文件777WWW权限');
  329. }
  330. return FileClass::writeFile($filepath, $comment);
  331. }
  332. // 文件重命名
  333. public function rename($newname, $oldname)
  334. {
  335. if (($newname != $oldname) && is_writable($oldname)) {
  336. return rename($oldname, $newname);
  337. }
  338. return true;
  339. }
  340. /**
  341. * 删除文件或文件夹
  342. * @param string $path
  343. * @return bool
  344. *
  345. * @date 2022/09/20
  346. * @author yyw
  347. */
  348. public function delFolder(string $path)
  349. {
  350. $path = $this->formatPath($path);
  351. if (is_file($path)) {
  352. return unlink($path);
  353. }
  354. $dir = opendir($path);
  355. while ($fileName = readdir($dir)) {
  356. $file = $path . '/' . $fileName;
  357. if ($fileName != '.' && $fileName != '..') {
  358. if (is_dir($file)) {
  359. self::delFolder($file);
  360. } else {
  361. unlink($file);
  362. }
  363. }
  364. }
  365. closedir($dir);
  366. return rmdir($path);
  367. }
  368. /**
  369. * 新建文件夹
  370. * @param string $path
  371. * @param string $name
  372. * @param int $permissions
  373. * @return bool
  374. *
  375. * @date 2022/09/20
  376. * @author yyw
  377. */
  378. public function createFolder(string $path, string $name, int $permissions = 0755)
  379. {
  380. $path = $this->formatPath($path, $name);
  381. /** @var FileClass $fileClass */
  382. $fileClass = app()->make(FileClass::class);
  383. return $fileClass->createDir($path, $permissions);
  384. }
  385. /**
  386. * 新建文件
  387. * @param string $path
  388. * @param string $name
  389. * @return bool
  390. *
  391. * @date 2022/09/20
  392. * @author yyw
  393. */
  394. public function createFile(string $path, string $name)
  395. {
  396. $path = $this->formatPath($path, $name);
  397. /** @var FileClass $fileClass */
  398. $fileClass = app()->make(FileClass::class);
  399. return $fileClass->createFile($path);
  400. }
  401. public function copyFolder($surDir, $toDir)
  402. {
  403. return FileClass::copyDir($surDir, $toDir);
  404. }
  405. /**
  406. * 格式化路径
  407. * @param string $path
  408. * @param string $name
  409. * @return string
  410. *
  411. * @date 2022/09/20
  412. * @author yyw
  413. */
  414. public function formatPath(string $path = '', string $name = ''): string
  415. {
  416. if ($path) {
  417. $path = rtrim($path, DS);
  418. if ($name) $path = $path . DS . $name;
  419. $uname = php_uname('s');
  420. if (strstr($uname, 'Windows') !== false)
  421. $path = ltrim(str_replace('\\', '\\\\', $path), '.');
  422. }
  423. return $path;
  424. }
  425. /**
  426. * 文件备注表单
  427. * @param $path
  428. * @param $fileToken
  429. * @return array
  430. * @throws \FormBuilder\Exception\FormBuilderException
  431. * @author 吴汐
  432. * @email 442384644@qq.com
  433. * @date 2023/04/10
  434. */
  435. public function markForm($path, $fileToken)
  436. {
  437. $full_path = str_replace(root_path(), '/', $path);
  438. $mark = app()->make(SystemFileInfoServices::class)->value(['full_path' => str_replace(root_path(), '/', $path)], 'mark');
  439. $f = [];
  440. $f[] = Form::hidden('full_path', $full_path);
  441. $f[] = Form::input('mark', '文件备注', $mark);
  442. return create_form('文件备注', $f, Url::buildUrl('/system/file/mark/save?fileToken=' . $fileToken . '&type=mark'), 'POST');
  443. }
  444. /**
  445. * 保存文件备注
  446. * @param $full_path
  447. * @param $mark
  448. * @author 吴汐
  449. * @email 442384644@qq.com
  450. * @date 2023/04/10
  451. */
  452. public function fileMarkSave($full_path, $mark)
  453. {
  454. $res = app()->make(SystemFileInfoServices::class)->update(['full_path' => $full_path], ['mark' => $mark]);
  455. if (!$res) {
  456. throw new AdminException(100006);
  457. }
  458. }
  459. }