Manage.php 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966
  1. <?php
  2. namespace app\admin\library\module;
  3. use Throwable;
  4. use ba\Version;
  5. use ba\Depends;
  6. use ba\Exception;
  7. use ba\Filesystem;
  8. use FilesystemIterator;
  9. use think\facade\Config;
  10. use RecursiveDirectoryIterator;
  11. use RecursiveIteratorIterator;
  12. /**
  13. * 模块管理类
  14. */
  15. class Manage
  16. {
  17. public const UNINSTALLED = 0;
  18. public const INSTALLED = 1;
  19. public const WAIT_INSTALL = 2;
  20. public const CONFLICT_PENDING = 3;
  21. public const DEPENDENT_WAIT_INSTALL = 4;
  22. public const DIRECTORY_OCCUPIED = 5;
  23. public const DISABLE = 6;
  24. /**
  25. * @var ?Manage 对象实例
  26. */
  27. protected static ?Manage $instance = null;
  28. /**
  29. * @var string 安装目录
  30. */
  31. protected string $installDir;
  32. /**
  33. * @var string 备份目录
  34. */
  35. protected string $backupsDir;
  36. /**
  37. * @var string 模板唯一标识
  38. */
  39. protected string $uid;
  40. /**
  41. * @var string 模板根目录
  42. */
  43. protected string $modulesDir;
  44. /**
  45. * 初始化
  46. * @access public
  47. * @param string $uid
  48. * @return Manage
  49. */
  50. public static function instance(string $uid = ''): Manage
  51. {
  52. if (is_null(self::$instance)) {
  53. self::$instance = new static($uid);
  54. }
  55. return self::$instance;
  56. }
  57. public function __construct(string $uid)
  58. {
  59. $this->installDir = root_path() . 'modules' . DIRECTORY_SEPARATOR;
  60. $this->backupsDir = $this->installDir . 'backups' . DIRECTORY_SEPARATOR;
  61. if (!is_dir($this->installDir)) {
  62. mkdir($this->installDir, 0755, true);
  63. }
  64. if (!is_dir($this->backupsDir)) {
  65. mkdir($this->backupsDir, 0755, true);
  66. }
  67. if ($uid) {
  68. $this->uid = $uid;
  69. $this->modulesDir = $this->installDir . $uid . DIRECTORY_SEPARATOR;
  70. }
  71. }
  72. public function getInstallState()
  73. {
  74. if (!is_dir($this->modulesDir)) {
  75. return self::UNINSTALLED;
  76. }
  77. $info = $this->getInfo();
  78. if ($info && isset($info['state'])) {
  79. return $info['state'];
  80. }
  81. // 目录已存在,但非正常的模块
  82. return Filesystem::dirIsEmpty($this->modulesDir) ? self::UNINSTALLED : self::DIRECTORY_OCCUPIED;
  83. }
  84. /**
  85. * 下载模块文件
  86. * @return string 已下载文件路径
  87. * @throws Throwable
  88. */
  89. public function download(): string
  90. {
  91. $token = request()->param("token/s");
  92. $version = request()->param('version/s');
  93. $orderId = request()->param("orderId/d");
  94. if (!$orderId) {
  95. throw new Exception('Order not found');
  96. }
  97. // 下载 - 系统版本号要求、已安装模块的互斥和依赖检测
  98. $zipFile = Server::download($this->uid, $this->installDir, [
  99. 'version' => $version,
  100. 'orderId' => $orderId,
  101. 'nuxtVersion' => Server::getNuxtVersion(),
  102. 'sysVersion' => Config::get('buildadmin.version'),
  103. 'installed' => Server::getInstalledIds($this->installDir),
  104. 'ba-user-token' => $token,
  105. ]);
  106. // 删除旧版本代码
  107. Filesystem::delDir($this->modulesDir);
  108. // 解压
  109. Filesystem::unzip($zipFile);
  110. // 删除下载的zip
  111. @unlink($zipFile);
  112. // 检查是否完整
  113. $this->checkPackage();
  114. // 设置为待安装状态
  115. $this->setInfo([
  116. 'state' => self::WAIT_INSTALL,
  117. ]);
  118. return $zipFile;
  119. }
  120. /**
  121. * 上传安装
  122. * @param string $file 已经上传完成的文件
  123. * @return array 模块的基本信息
  124. * @throws Throwable
  125. */
  126. public function upload(string $token, string $file): array
  127. {
  128. $file = Filesystem::fsFit(root_path() . 'public' . $file);
  129. if (!is_file($file)) {
  130. // 包未找到
  131. throw new Exception('Zip file not found');
  132. }
  133. $copyTo = $this->installDir . 'uploadTemp' . date('YmdHis') . '.zip';
  134. copy($file, $copyTo);
  135. // 解压
  136. $copyToDir = Filesystem::unzip($copyTo);
  137. $copyToDir .= DIRECTORY_SEPARATOR;
  138. // 删除zip
  139. @unlink($file);
  140. @unlink($copyTo);
  141. // 读取ini
  142. $info = Server::getIni($copyToDir);
  143. if (empty($info['uid'])) {
  144. Filesystem::delDir($copyToDir);
  145. // 基本配置不完整
  146. throw new Exception('Basic configuration of the Module is incomplete');
  147. }
  148. $this->uid = $info['uid'];
  149. $this->modulesDir = $this->installDir . $info['uid'] . DIRECTORY_SEPARATOR;
  150. $upgrade = false;
  151. if (is_dir($this->modulesDir)) {
  152. $oldInfo = $this->getInfo();
  153. if ($oldInfo && !empty($oldInfo['uid'])) {
  154. $versions = explode('.', $oldInfo['version']);
  155. if (isset($versions[2])) {
  156. $versions[2]++;
  157. }
  158. $nextVersion = implode('.', $versions);
  159. $upgrade = Version::compare($nextVersion, $info['version']);
  160. if ($upgrade) {
  161. // 检查模块是否已禁用
  162. if (!in_array($oldInfo['state'], [self::UNINSTALLED, self::WAIT_INSTALL, self::DISABLE])) {
  163. Filesystem::delDir($copyToDir);
  164. throw new Exception('Please disable the module before updating');
  165. }
  166. } else {
  167. Filesystem::delDir($copyToDir);
  168. // 模块已经存在
  169. throw new Exception('Module already exists');
  170. }
  171. }
  172. if (!Filesystem::dirIsEmpty($this->modulesDir) && !$upgrade) {
  173. Filesystem::delDir($copyToDir);
  174. // 模块目录被占
  175. throw new Exception('The directory required by the module is occupied');
  176. }
  177. }
  178. // 安装预检 - 系统版本号要求、已安装模块的互斥和依赖检测
  179. try {
  180. Server::installPreCheck([
  181. 'uid' => $info['uid'],
  182. 'version' => $info['version'],
  183. 'sysVersion' => Config::get('buildadmin.version'),
  184. 'nuxtVersion' => Server::getNuxtVersion(),
  185. 'moduleVersion' => $info['version'],
  186. 'ba-user-token' => $token,
  187. 'installed' => Server::getInstalledIds($this->installDir),
  188. 'server' => 1,
  189. ]);
  190. } catch (Throwable $e) {
  191. Filesystem::delDir($copyToDir);
  192. throw $e;
  193. }
  194. $newInfo = ['state' => self::WAIT_INSTALL];
  195. if ($upgrade) {
  196. $info['update'] = 1;
  197. // 清理旧版本代码
  198. Filesystem::delDir($this->modulesDir);
  199. }
  200. // 放置新模块
  201. rename($copyToDir, $this->modulesDir);
  202. // 检查新包是否完整
  203. $this->checkPackage();
  204. // 设置为待安装状态
  205. $this->setInfo($newInfo);
  206. return $info;
  207. }
  208. /**
  209. * 安装模块
  210. * @return array 模块基本信息
  211. * @throws Throwable
  212. */
  213. public function install(bool $update): array
  214. {
  215. $state = $this->getInstallState();
  216. if ($update) {
  217. if (!in_array($state, [self::UNINSTALLED, self::WAIT_INSTALL, self::DISABLE])) {
  218. throw new Exception('Please disable the module before updating');
  219. }
  220. /**
  221. * self::WAIT_INSTALL=待安装
  222. * 即本地上传文件进行升级的安装流程,文件上传成功后将被标记为待安装,免去此处的下载
  223. */
  224. if ($state == self::UNINSTALLED || $state != self::WAIT_INSTALL) {
  225. $this->download();
  226. }
  227. } else {
  228. if ($state == self::INSTALLED || $state == self::DIRECTORY_OCCUPIED || $state == self::DISABLE) {
  229. throw new Exception('Module already exists');
  230. }
  231. if ($state == self::UNINSTALLED) {
  232. $this->download();
  233. }
  234. }
  235. // 导入sql
  236. Server::importSql($this->modulesDir);
  237. // 如果是更新,先执行更新脚本
  238. $info = $this->getInfo();
  239. if ($update) {
  240. $info['update'] = 1;
  241. Server::execEvent($this->uid, 'update');
  242. }
  243. // 执行安装脚本 - 排除冲突处理时会重复提交至此的请求
  244. $extend = request()->post('extend/a', []);
  245. if (!isset($extend['conflictHandle'])) {
  246. Server::execEvent($this->uid, 'install');
  247. }
  248. // 启用插件
  249. $this->enable('install');
  250. return $info;
  251. }
  252. /**
  253. * 卸载
  254. * @throws Throwable
  255. */
  256. public function uninstall(): void
  257. {
  258. $info = $this->getInfo();
  259. if ($info['state'] != self::DISABLE) {
  260. throw new Exception('Please disable the module first', 0, [
  261. 'uid' => $this->uid,
  262. ]);
  263. }
  264. // 执行卸载脚本
  265. Server::execEvent($this->uid, 'uninstall');
  266. Filesystem::delDir($this->modulesDir);
  267. }
  268. /**
  269. * 修改模块状态
  270. * @param bool $state 新状态
  271. * @return array 模块基本信息
  272. * @throws Throwable
  273. */
  274. public function changeState(bool $state): array
  275. {
  276. $info = $this->getInfo();
  277. if (!$state) {
  278. $canDisable = [
  279. self::INSTALLED,
  280. self::CONFLICT_PENDING,
  281. self::DEPENDENT_WAIT_INSTALL,
  282. ];
  283. if (!in_array($info['state'], $canDisable)) {
  284. throw new Exception('The current state of the module cannot be set to disabled', 0, [
  285. 'uid' => $this->uid,
  286. 'state' => $info['state'],
  287. ]);
  288. }
  289. return $this->disable();
  290. }
  291. if ($info['state'] != self::DISABLE) {
  292. throw new Exception('The current state of the module cannot be set to enabled', 0, [
  293. 'uid' => $this->uid,
  294. 'state' => $info['state'],
  295. ]);
  296. }
  297. $this->setInfo([
  298. 'state' => self::WAIT_INSTALL,
  299. ]);
  300. return $info;
  301. }
  302. /**
  303. * 启用
  304. * @param string $trigger 触发启用的标志,比如:install=安装
  305. * @throws Throwable
  306. */
  307. public function enable(string $trigger): void
  308. {
  309. // 安装 WebBootstrap
  310. Server::installWebBootstrap($this->uid, $this->modulesDir);
  311. // 建立 .runtime
  312. Server::createRuntime($this->modulesDir);
  313. // 冲突检查
  314. $this->conflictHandle($trigger);
  315. // 执行启用脚本
  316. Server::execEvent($this->uid, 'enable');
  317. $this->dependUpdateHandle();
  318. }
  319. /**
  320. * 禁用
  321. * @return array 模块基本信息
  322. * @throws Throwable
  323. */
  324. public function disable(): array
  325. {
  326. $update = request()->post("update/b", false);
  327. $confirmConflict = request()->post("confirmConflict/b", false);
  328. $dependConflictSolution = request()->post("dependConflictSolution/a", []);
  329. $info = $this->getInfo();
  330. $zipFile = $this->backupsDir . $this->uid . '-install.zip';
  331. $zipDir = false;
  332. if (is_file($zipFile)) {
  333. try {
  334. $zipDir = $this->backupsDir . $this->uid . '-install' . DIRECTORY_SEPARATOR;
  335. Filesystem::unzip($zipFile, $zipDir);
  336. } catch (Exception) {
  337. // skip
  338. }
  339. }
  340. $conflictFile = Server::getFileList($this->modulesDir, true);
  341. $dependConflict = $this->disableDependCheck();
  342. if (($conflictFile || !self::isEmptyArray($dependConflict)) && !$confirmConflict) {
  343. $dependConflictTemp = [];
  344. foreach ($dependConflict as $env => $item) {
  345. foreach ($item as $depend => $v) {
  346. $dependConflictTemp[] = [
  347. 'env' => $env,
  348. 'depend' => $depend,
  349. 'dependTitle' => $depend . ' ' . $v,
  350. 'solution' => 'delete',
  351. ];
  352. }
  353. }
  354. throw new Exception('Module file updated', -1, [
  355. 'uid' => $this->uid,
  356. 'conflictFile' => $conflictFile,
  357. 'dependConflict' => $dependConflictTemp,
  358. ]);
  359. }
  360. // 执行禁用脚本
  361. Server::execEvent($this->uid, 'disable', ['update' => $update]);
  362. // 是否需要备份依赖?
  363. $delNpmDepend = false;
  364. $delNuxtNpmDepend = false;
  365. $delComposerDepend = false;
  366. foreach ($dependConflictSolution as $env => $depends) {
  367. if (!$depends) continue;
  368. if ($env == 'require' || $env == 'require-dev') {
  369. $delComposerDepend = true;
  370. } elseif ($env == 'dependencies' || $env == 'devDependencies') {
  371. $delNpmDepend = true;
  372. } elseif ($env == 'nuxtDependencies' || $env == 'nuxtDevDependencies') {
  373. $delNuxtNpmDepend = true;
  374. }
  375. }
  376. // 备份
  377. $dependJsonFiles = [
  378. 'composer' => 'composer.json',
  379. 'webPackage' => 'web' . DIRECTORY_SEPARATOR . 'package.json',
  380. 'webNuxtPackage' => 'web-nuxt' . DIRECTORY_SEPARATOR . 'package.json',
  381. ];
  382. $dependWaitInstall = [];
  383. if ($delComposerDepend) {
  384. $conflictFile[] = $dependJsonFiles['composer'];
  385. $dependWaitInstall[] = [
  386. 'pm' => false,
  387. 'command' => 'composer.update',
  388. 'type' => 'composer_dependent_wait_install',
  389. ];
  390. }
  391. if ($delNpmDepend) {
  392. $conflictFile[] = $dependJsonFiles['webPackage'];
  393. $dependWaitInstall[] = [
  394. 'pm' => true,
  395. 'command' => 'web-install',
  396. 'type' => 'npm_dependent_wait_install',
  397. ];
  398. }
  399. if ($delNuxtNpmDepend) {
  400. $conflictFile[] = $dependJsonFiles['webNuxtPackage'];
  401. $dependWaitInstall[] = [
  402. 'pm' => true,
  403. 'command' => 'nuxt-install',
  404. 'type' => 'nuxt_npm_dependent_wait_install',
  405. ];
  406. }
  407. if ($conflictFile) {
  408. // 如果是模块自带文件需要备份,加上模块目录前缀
  409. $overwriteDir = Server::getOverwriteDir();
  410. foreach ($conflictFile as $key => $item) {
  411. $paths = explode(DIRECTORY_SEPARATOR, $item);
  412. if (in_array($paths[0], $overwriteDir) || in_array($item, $dependJsonFiles)) {
  413. $conflictFile[$key] = $item;
  414. } else {
  415. $conflictFile[$key] = Filesystem::fsFit(str_replace(root_path(), '', $this->modulesDir . $item));
  416. }
  417. if (!is_file(root_path() . $conflictFile[$key])) {
  418. unset($conflictFile[$key]);
  419. }
  420. }
  421. $backupsZip = $this->backupsDir . $this->uid . '-disable-' . date('YmdHis') . '.zip';
  422. Filesystem::zip($conflictFile, $backupsZip);
  423. }
  424. // 删除依赖
  425. $serverDepend = new Depends(root_path() . 'composer.json', 'composer');
  426. $webDep = new Depends(root_path() . 'web' . DIRECTORY_SEPARATOR . 'package.json');
  427. $webNuxtDep = new Depends(root_path() . 'web-nuxt' . DIRECTORY_SEPARATOR . 'package.json');
  428. foreach ($dependConflictSolution as $env => $depends) {
  429. if (!$depends) continue;
  430. $dev = !(stripos($env, 'dev') === false);
  431. if ($env == 'require' || $env == 'require-dev') {
  432. $serverDepend->removeDepends($depends, $dev);
  433. } elseif ($env == 'dependencies' || $env == 'devDependencies') {
  434. $webDep->removeDepends($depends, $dev);
  435. } elseif ($env == 'nuxtDependencies' || $env == 'nuxtDevDependencies') {
  436. $webNuxtDep->removeDepends($depends, $dev);
  437. }
  438. }
  439. // 删除 composer.json 中的 config
  440. $composerConfig = Server::getConfig($this->modulesDir, 'composerConfig');
  441. if ($composerConfig) {
  442. $serverDepend->removeComposerConfig($composerConfig);
  443. }
  444. // 配置了不删除的文件
  445. $protectedFiles = Server::getConfig($this->modulesDir, 'protectedFiles');
  446. foreach ($protectedFiles as &$protectedFile) {
  447. $protectedFile = Filesystem::fsFit(root_path() . $protectedFile);
  448. }
  449. // 模块文件列表
  450. $moduleFile = Server::getFileList($this->modulesDir);
  451. // 删除模块文件
  452. foreach ($moduleFile as &$file) {
  453. // 纯净模式下,模块文件将被删除,此处直接检查模块目录中是否有该文件并恢复(不检查是否开启纯净模式,因为开关可能被调整)
  454. $moduleFilePath = Filesystem::fsFit($this->modulesDir . $file);
  455. $file = Filesystem::fsFit(root_path() . $file);
  456. if (!file_exists($file)) continue;
  457. if (!file_exists($moduleFilePath)) {
  458. if (!is_dir(dirname($moduleFilePath))) {
  459. mkdir(dirname($moduleFilePath), 0755, true);
  460. }
  461. copy($file, $moduleFilePath);
  462. }
  463. if (in_array($file, $protectedFiles)) {
  464. continue;
  465. }
  466. if (file_exists($file)) {
  467. unlink($file);
  468. }
  469. Filesystem::delEmptyDir(dirname($file));
  470. }
  471. // 恢复备份文件
  472. if ($zipDir) {
  473. $unrecoverableFiles = [
  474. Filesystem::fsFit(root_path() . 'composer.json'),
  475. Filesystem::fsFit(root_path() . 'web/package.json'),
  476. Filesystem::fsFit(root_path() . 'web-nuxt/package.json'),
  477. ];
  478. foreach (
  479. new RecursiveIteratorIterator(
  480. new RecursiveDirectoryIterator($zipDir, FilesystemIterator::SKIP_DOTS),
  481. RecursiveIteratorIterator::SELF_FIRST
  482. ) as $item
  483. ) {
  484. $backupsFile = Filesystem::fsFit(root_path() . str_replace($zipDir, '', $item->getPathname()));
  485. // 在模块包中,同时不在 $protectedFiles 列表的文件不恢复,这些文件可能是模块升级时备份的
  486. if (in_array($backupsFile, $moduleFile) && !in_array($backupsFile, $protectedFiles)) {
  487. continue;
  488. }
  489. if ($item->isDir()) {
  490. if (!is_dir($backupsFile)) {
  491. mkdir($backupsFile, 0755, true);
  492. }
  493. } elseif (!in_array($backupsFile, $unrecoverableFiles)) {
  494. copy($item, $backupsFile);
  495. }
  496. }
  497. }
  498. // 删除解压后的备份文件
  499. Filesystem::delDir($zipDir);
  500. // 卸载 WebBootstrap
  501. Server::uninstallWebBootstrap($this->uid);
  502. $this->setInfo([
  503. 'state' => self::DISABLE,
  504. ]);
  505. if ($update) {
  506. throw new Exception('update', -3, [
  507. 'uid' => $this->uid,
  508. ]);
  509. }
  510. if ($dependWaitInstall) {
  511. throw new Exception('dependent wait install', -2, [
  512. 'uid' => $this->uid,
  513. 'wait_install' => $dependWaitInstall,
  514. ]);
  515. }
  516. return $info;
  517. }
  518. /**
  519. * 处理依赖和文件冲突,并完成与前端的冲突处理交互
  520. * @throws Throwable
  521. */
  522. public function conflictHandle(string $trigger): bool
  523. {
  524. $info = $this->getInfo();
  525. if ($info['state'] != self::WAIT_INSTALL && $info['state'] != self::CONFLICT_PENDING) {
  526. return false;
  527. }
  528. $fileConflict = Server::getFileList($this->modulesDir, true);// 文件冲突
  529. $dependConflict = Server::dependConflictCheck($this->modulesDir);// 依赖冲突
  530. $installFiles = Server::getFileList($this->modulesDir);// 待安装文件
  531. $depends = Server::getDepend($this->modulesDir);// 待安装依赖
  532. $coverFiles = [];// 要覆盖的文件-备份
  533. $discardFiles = [];// 抛弃的文件-复制时不覆盖
  534. $serverDep = new Depends(root_path() . 'composer.json', 'composer');
  535. $webDep = new Depends(root_path() . 'web' . DIRECTORY_SEPARATOR . 'package.json');
  536. $webNuxtDep = new Depends(root_path() . 'web-nuxt' . DIRECTORY_SEPARATOR . 'package.json');
  537. if ($fileConflict || !self::isEmptyArray($dependConflict)) {
  538. $extend = request()->post('extend/a', []);
  539. if (!$extend) {
  540. // 发现冲突->手动处理->转换为方便前端使用的格式
  541. $fileConflictTemp = [];
  542. foreach ($fileConflict as $key => $item) {
  543. $fileConflictTemp[$key] = [
  544. 'newFile' => $this->uid . DIRECTORY_SEPARATOR . $item,
  545. 'oldFile' => $item,
  546. 'solution' => 'cover',
  547. ];
  548. }
  549. $dependConflictTemp = [];
  550. foreach ($dependConflict as $env => $item) {
  551. $dev = !(stripos($env, 'dev') === false);
  552. foreach ($item as $depend => $v) {
  553. $oldDepend = '';
  554. if (in_array($env, ['require', 'require-dev'])) {
  555. $oldDepend = $depend . ' ' . $serverDep->hasDepend($depend, $dev);
  556. } elseif (in_array($env, ['dependencies', 'devDependencies'])) {
  557. $oldDepend = $depend . ' ' . $webDep->hasDepend($depend, $dev);
  558. } elseif (in_array($env, ['nuxtDependencies', 'nuxtDevDependencies'])) {
  559. $oldDepend = $depend . ' ' . $webNuxtDep->hasDepend($depend, $dev);
  560. }
  561. $dependConflictTemp[] = [
  562. 'env' => $env,
  563. 'newDepend' => $depend . ' ' . $v,
  564. 'oldDepend' => $oldDepend,
  565. 'depend' => $depend,
  566. 'solution' => 'cover',
  567. ];
  568. }
  569. }
  570. $this->setInfo([
  571. 'state' => self::CONFLICT_PENDING,
  572. ]);
  573. throw new Exception('Module file conflicts', -1, [
  574. 'fileConflict' => $fileConflictTemp,
  575. 'dependConflict' => $dependConflictTemp,
  576. 'uid' => $this->uid,
  577. 'state' => self::CONFLICT_PENDING,
  578. ]);
  579. }
  580. // 处理冲突
  581. if ($fileConflict && isset($extend['fileConflict'])) {
  582. foreach ($installFiles as $ikey => $installFile) {
  583. if (isset($extend['fileConflict'][$installFile])) {
  584. if ($extend['fileConflict'][$installFile] == 'discard') {
  585. $discardFiles[] = $installFile;
  586. unset($installFiles[$ikey]);
  587. } else {
  588. $coverFiles[] = $installFile;
  589. }
  590. }
  591. }
  592. }
  593. if (!self::isEmptyArray($dependConflict) && isset($extend['dependConflict'])) {
  594. foreach ($depends as $fKey => $fItem) {
  595. foreach ($fItem as $cKey => $cItem) {
  596. if (isset($extend['dependConflict'][$fKey][$cKey])) {
  597. if ($extend['dependConflict'][$fKey][$cKey] == 'discard') {
  598. unset($depends[$fKey][$cKey]);
  599. }
  600. }
  601. }
  602. }
  603. }
  604. }
  605. // 如果有依赖更新,增加要备份的文件
  606. if ($depends) {
  607. foreach ($depends as $key => $item) {
  608. if (!$item) {
  609. continue;
  610. }
  611. if ($key == 'require' || $key == 'require-dev') {
  612. $coverFiles[] = 'composer.json';
  613. continue;
  614. }
  615. if ($key == 'dependencies' || $key == 'devDependencies') {
  616. $coverFiles[] = 'web' . DIRECTORY_SEPARATOR . 'package.json';
  617. }
  618. if ($key == 'nuxtDependencies' || $key == 'nuxtDevDependencies') {
  619. $coverFiles[] = 'web-nuxt' . DIRECTORY_SEPARATOR . 'package.json';
  620. }
  621. }
  622. }
  623. // 备份将被覆盖的文件
  624. if ($coverFiles) {
  625. $backupsZip = $trigger == 'install' ? $this->backupsDir . $this->uid . '-install.zip' : $this->backupsDir . $this->uid . '-cover-' . date('YmdHis') . '.zip';
  626. Filesystem::zip($coverFiles, $backupsZip);
  627. }
  628. if ($depends) {
  629. $npm = false;
  630. $composer = false;
  631. $nuxtNpm = false;
  632. // composer config 更新
  633. $composerConfig = Server::getConfig($this->modulesDir, 'composerConfig');
  634. if ($composerConfig) {
  635. $serverDep->setComposerConfig($composerConfig);
  636. }
  637. foreach ($depends as $key => $item) {
  638. if (!$item) {
  639. continue;
  640. }
  641. if ($key == 'require') {
  642. $composer = true;
  643. $serverDep->addDepends($item, false, true);
  644. } elseif ($key == 'require-dev') {
  645. $composer = true;
  646. $serverDep->addDepends($item, true, true);
  647. } elseif ($key == 'dependencies') {
  648. $npm = true;
  649. $webDep->addDepends($item, false, true);
  650. } elseif ($key == 'devDependencies') {
  651. $npm = true;
  652. $webDep->addDepends($item, true, true);
  653. } elseif ($key == 'nuxtDependencies') {
  654. $nuxtNpm = true;
  655. $webNuxtDep->addDepends($item, false, true);
  656. } elseif ($key == 'nuxtDevDependencies') {
  657. $nuxtNpm = true;
  658. $webNuxtDep->addDepends($item, true, true);
  659. }
  660. }
  661. if ($npm) {
  662. $info['npm_dependent_wait_install'] = 1;
  663. $info['state'] = self::DEPENDENT_WAIT_INSTALL;
  664. }
  665. if ($composer) {
  666. $info['composer_dependent_wait_install'] = 1;
  667. $info['state'] = self::DEPENDENT_WAIT_INSTALL;
  668. }
  669. if ($nuxtNpm) {
  670. $info['nuxt_npm_dependent_wait_install'] = 1;
  671. $info['state'] = self::DEPENDENT_WAIT_INSTALL;
  672. }
  673. if ($info['state'] != self::DEPENDENT_WAIT_INSTALL) {
  674. // 无冲突
  675. $this->setInfo([
  676. 'state' => self::INSTALLED,
  677. ]);
  678. } else {
  679. $this->setInfo([], $info);
  680. }
  681. } else {
  682. // 无冲突
  683. $this->setInfo([
  684. 'state' => self::INSTALLED,
  685. ]);
  686. }
  687. // 复制文件
  688. $overwriteDir = Server::getOverwriteDir();
  689. foreach ($overwriteDir as $dirItem) {
  690. $baseDir = $this->modulesDir . $dirItem;
  691. $destDir = root_path() . $dirItem;
  692. if (!is_dir($baseDir)) {
  693. continue;
  694. }
  695. foreach (
  696. new RecursiveIteratorIterator(
  697. new RecursiveDirectoryIterator($baseDir, FilesystemIterator::SKIP_DOTS),
  698. RecursiveIteratorIterator::SELF_FIRST
  699. ) as $item
  700. ) {
  701. $destDirItem = Filesystem::fsFit($destDir . DIRECTORY_SEPARATOR . str_replace($baseDir, '', $item->getPathname()));
  702. if ($item->isDir()) {
  703. Filesystem::mkdir($destDirItem);
  704. } elseif (!in_array(str_replace(root_path(), '', $destDirItem), $discardFiles)) {
  705. Filesystem::mkdir(dirname($destDirItem));
  706. copy($item, $destDirItem);
  707. }
  708. }
  709. // 纯净模式
  710. if (Config::get('buildadmin.module_pure_install')) {
  711. Filesystem::delDir($baseDir);
  712. }
  713. }
  714. return true;
  715. }
  716. /**
  717. * 依赖升级处理
  718. * @throws Throwable
  719. */
  720. public function dependUpdateHandle(): void
  721. {
  722. $info = $this->getInfo();
  723. if ($info['state'] == self::DEPENDENT_WAIT_INSTALL) {
  724. $waitInstall = [];
  725. if (isset($info['composer_dependent_wait_install'])) {
  726. $waitInstall[] = 'composer_dependent_wait_install';
  727. }
  728. if (isset($info['npm_dependent_wait_install'])) {
  729. $waitInstall[] = 'npm_dependent_wait_install';
  730. }
  731. if (isset($info['nuxt_npm_dependent_wait_install'])) {
  732. $waitInstall[] = 'nuxt_npm_dependent_wait_install';
  733. }
  734. if ($waitInstall) {
  735. throw new Exception('dependent wait install', -2, [
  736. 'uid' => $this->uid,
  737. 'state' => self::DEPENDENT_WAIT_INSTALL,
  738. 'wait_install' => $waitInstall,
  739. ]);
  740. } else {
  741. $this->setInfo([
  742. 'state' => self::INSTALLED,
  743. ]);
  744. }
  745. }
  746. }
  747. /**
  748. * 依赖安装完成标记
  749. * @throws Throwable
  750. */
  751. public function dependentInstallComplete(string $type): void
  752. {
  753. $info = $this->getInfo();
  754. if ($info['state'] == self::DEPENDENT_WAIT_INSTALL) {
  755. if ($type == 'npm') {
  756. unset($info['npm_dependent_wait_install']);
  757. }
  758. if ($type == 'nuxt_npm') {
  759. unset($info['nuxt_npm_dependent_wait_install']);
  760. }
  761. if ($type == 'composer') {
  762. unset($info['composer_dependent_wait_install']);
  763. }
  764. if ($type == 'all') {
  765. unset($info['npm_dependent_wait_install'], $info['composer_dependent_wait_install'], $info['nuxt_npm_dependent_wait_install']);
  766. }
  767. if (!isset($info['npm_dependent_wait_install']) && !isset($info['composer_dependent_wait_install']) && !isset($info['nuxt_npm_dependent_wait_install'])) {
  768. $info['state'] = self::INSTALLED;
  769. }
  770. $this->setInfo([], $info);
  771. }
  772. }
  773. /**
  774. * 禁用依赖检查
  775. * @throws Throwable
  776. */
  777. public function disableDependCheck(): array
  778. {
  779. // 读取模块所有依赖
  780. $depend = Server::getDepend($this->modulesDir);
  781. if (!$depend) {
  782. return [];
  783. }
  784. // 读取所有依赖中,系统上已经安装的依赖
  785. $serverDep = new Depends(root_path() . 'composer.json', 'composer');
  786. $webDep = new Depends(root_path() . 'web' . DIRECTORY_SEPARATOR . 'package.json');
  787. $webNuxtDep = new Depends(root_path() . 'web-nuxt' . DIRECTORY_SEPARATOR . 'package.json');
  788. foreach ($depend as $key => $depends) {
  789. $dev = !(stripos($key, 'dev') === false);
  790. if ($key == 'require' || $key == 'require-dev') {
  791. foreach ($depends as $dependKey => $dependItem) {
  792. if (!$serverDep->hasDepend($dependKey, $dev)) {
  793. unset($depends[$dependKey]);
  794. }
  795. }
  796. $depend[$key] = $depends;
  797. } elseif ($key == 'dependencies' || $key == 'devDependencies') {
  798. foreach ($depends as $dependKey => $dependItem) {
  799. if (!$webDep->hasDepend($dependKey, $dev)) {
  800. unset($depends[$dependKey]);
  801. }
  802. }
  803. $depend[$key] = $depends;
  804. } elseif ($key == 'nuxtDependencies' || $key == 'nuxtDevDependencies') {
  805. foreach ($depends as $dependKey => $dependItem) {
  806. if (!$webNuxtDep->hasDepend($dependKey, $dev)) {
  807. unset($depends[$dependKey]);
  808. }
  809. }
  810. $depend[$key] = $depends;
  811. }
  812. }
  813. return $depend;
  814. }
  815. /**
  816. * 检查包是否完整
  817. * @throws Throwable
  818. */
  819. public function checkPackage(): bool
  820. {
  821. if (!is_dir($this->modulesDir)) {
  822. throw new Exception('Module package file does not exist');
  823. }
  824. $info = $this->getInfo();
  825. $infoKeys = ['uid', 'title', 'intro', 'author', 'version', 'state'];
  826. foreach ($infoKeys as $value) {
  827. if (!array_key_exists($value, $info)) {
  828. Filesystem::delDir($this->modulesDir);
  829. throw new Exception('Basic configuration of the Module is incomplete');
  830. }
  831. }
  832. return true;
  833. }
  834. /**
  835. * 获取模块基本信息
  836. */
  837. public function getInfo(): array
  838. {
  839. return Server::getIni($this->modulesDir);
  840. }
  841. /**
  842. * 设置模块基本信息
  843. * @throws Throwable
  844. */
  845. public function setInfo(array $kv = [], array $arr = []): bool
  846. {
  847. if ($kv) {
  848. $info = $this->getInfo();
  849. foreach ($kv as $k => $v) {
  850. $info[$k] = $v;
  851. }
  852. return Server::setIni($this->modulesDir, $info);
  853. } elseif ($arr) {
  854. return Server::setIni($this->modulesDir, $arr);
  855. }
  856. throw new Exception('Parameter error');
  857. }
  858. /**
  859. * 检查多维数组是否全部为空
  860. */
  861. public static function isEmptyArray($arr): bool
  862. {
  863. foreach ($arr as $item) {
  864. if (is_array($item)) {
  865. $empty = self::isEmptyArray($item);
  866. if (!$empty) return false;
  867. } elseif ($item) {
  868. return false;
  869. }
  870. }
  871. return true;
  872. }
  873. }