1.修复上传漏洞和SQL注入漏洞-移除安装模块所有的代码
This commit is contained in:
@@ -1,158 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace app\admin\controller;
|
||||
|
||||
use ba\Exception as BaException;
|
||||
use app\admin\model\AdminLog;
|
||||
use app\admin\library\module\Server;
|
||||
use app\admin\library\module\Manage;
|
||||
use app\common\controller\Backend;
|
||||
use Webman\Http\Request;
|
||||
use support\Response;
|
||||
|
||||
class Module extends Backend
|
||||
{
|
||||
protected array $noNeedPermission = ['state', 'dependentInstallComplete'];
|
||||
|
||||
public function index(Request $request): Response
|
||||
{
|
||||
$response = $this->initializeBackend($request);
|
||||
if ($response !== null) return $response;
|
||||
|
||||
return $this->success('', [
|
||||
'installed' => Server::installedList(root_path() . 'modules' . DIRECTORY_SEPARATOR),
|
||||
'sysVersion' => config('buildadmin.version'),
|
||||
'nuxtVersion' => Server::getNuxtVersion(),
|
||||
]);
|
||||
}
|
||||
|
||||
public function state(Request $request): Response
|
||||
{
|
||||
$response = $this->initializeBackend($request);
|
||||
if ($response !== null) return $response;
|
||||
|
||||
$uid = $request->get('uid', '');
|
||||
if (!$uid) {
|
||||
return $this->error(__('Parameter error'));
|
||||
}
|
||||
return $this->success('', [
|
||||
'state' => Manage::instance($uid)->getInstallState()
|
||||
]);
|
||||
}
|
||||
|
||||
public function install(Request $request): Response
|
||||
{
|
||||
$response = $this->initializeBackend($request);
|
||||
if ($response !== null) return $response;
|
||||
|
||||
AdminLog::instance($request)->setTitle(__('Install module'));
|
||||
$uid = $request->get('uid', $request->post('uid', ''));
|
||||
$update = filter_var($request->get('update', $request->post('update', false)), FILTER_VALIDATE_BOOLEAN);
|
||||
if (!$uid) {
|
||||
return $this->error(__('Parameter error'));
|
||||
}
|
||||
$res = [];
|
||||
try {
|
||||
$res = Manage::instance($uid)->install($update);
|
||||
} catch (BaException $e) {
|
||||
return $this->error(__($e->getMessage()), $e->getData(), $e->getCode());
|
||||
} catch (\Throwable $e) {
|
||||
return $this->error(__($e->getMessage()));
|
||||
}
|
||||
return $this->success('', ['data' => $res]);
|
||||
}
|
||||
|
||||
public function dependentInstallComplete(Request $request): Response
|
||||
{
|
||||
$response = $this->initializeBackend($request);
|
||||
if ($response !== null) return $response;
|
||||
|
||||
$uid = $request->get('uid', '');
|
||||
if (!$uid) {
|
||||
return $this->error(__('Parameter error'));
|
||||
}
|
||||
try {
|
||||
Manage::instance($uid)->dependentInstallComplete('all');
|
||||
} catch (BaException $e) {
|
||||
return $this->error(__($e->getMessage()), $e->getData(), $e->getCode());
|
||||
} catch (\Throwable $e) {
|
||||
return $this->error(__($e->getMessage()));
|
||||
}
|
||||
return $this->success();
|
||||
}
|
||||
|
||||
public function changeState(Request $request): Response
|
||||
{
|
||||
$response = $this->initializeBackend($request);
|
||||
if ($response !== null) return $response;
|
||||
|
||||
AdminLog::instance($request)->setTitle(__('Change module state'));
|
||||
$uid = $request->post('uid', '');
|
||||
$state = filter_var($request->post('state', false), FILTER_VALIDATE_BOOLEAN);
|
||||
if (!$uid) {
|
||||
return $this->error(__('Parameter error'));
|
||||
}
|
||||
$info = [];
|
||||
try {
|
||||
$info = Manage::instance($uid)->changeState($state);
|
||||
} catch (BaException $e) {
|
||||
return $this->error(__($e->getMessage()), $e->getData(), $e->getCode());
|
||||
} catch (\Throwable $e) {
|
||||
return $this->error(__($e->getMessage()));
|
||||
}
|
||||
return $this->success('', ['info' => $info]);
|
||||
}
|
||||
|
||||
public function uninstall(Request $request): Response
|
||||
{
|
||||
$response = $this->initializeBackend($request);
|
||||
if ($response !== null) return $response;
|
||||
|
||||
AdminLog::instance($request)->setTitle(__('Uninstall module'));
|
||||
$uid = $request->post('uid', '');
|
||||
if (!$uid) {
|
||||
return $this->error(__('Parameter error'));
|
||||
}
|
||||
try {
|
||||
Manage::instance($uid)->uninstall();
|
||||
} catch (BaException $e) {
|
||||
return $this->error(__($e->getMessage()), $e->getData(), $e->getCode());
|
||||
} catch (\Throwable $e) {
|
||||
return $this->error(__($e->getMessage()));
|
||||
}
|
||||
return $this->success();
|
||||
}
|
||||
|
||||
public function upload(Request $request): Response
|
||||
{
|
||||
$response = $this->initializeBackend($request);
|
||||
if ($response !== null) return $response;
|
||||
|
||||
AdminLog::instance($request)->setTitle(__('Upload module'));
|
||||
|
||||
$token = $request->post('token', $request->get('token', ''));
|
||||
if (!$token) {
|
||||
return $this->error(__('Please login to the official website account first'));
|
||||
}
|
||||
|
||||
try {
|
||||
if ($request->file('file')) {
|
||||
$res = Manage::uploadFromRequest($request);
|
||||
} else {
|
||||
$file = $request->post('file', $request->get('file', ''));
|
||||
if (!$file) {
|
||||
return $this->error(__('Parameter error'));
|
||||
}
|
||||
$info = Manage::instance('')->doUpload($token, $file);
|
||||
$res = ['info' => $info];
|
||||
}
|
||||
} catch (BaException $e) {
|
||||
return $this->error(__($e->getMessage()), $e->getData(), $e->getCode());
|
||||
} catch (\Throwable $e) {
|
||||
return $this->error(__($e->getMessage()));
|
||||
}
|
||||
return $this->success('', $res);
|
||||
}
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
<?php
|
||||
return [
|
||||
'Order not found' => '订单找不到啦!',
|
||||
'Module already exists' => '模块已存在!',
|
||||
'package download failed' => '包下载失败!',
|
||||
'package check failed' => '包检查失败!',
|
||||
'No permission to write temporary files' => '没有权限写入临时文件!',
|
||||
'Zip file not found' => '找不到压缩包文件',
|
||||
'Unable to open the zip file' => '无法打开压缩包文件',
|
||||
'Unable to extract ZIP file' => '无法提取ZIP文件',
|
||||
'Unable to package zip file' => '无法打包zip文件',
|
||||
'Basic configuration of the Module is incomplete' => '模块基础配置不完整',
|
||||
'Module package file does not exist' => '模块包文件不存在',
|
||||
'Module file conflicts' => '模块文件存在冲突,请手动处理!',
|
||||
'Configuration file has no write permission' => '配置文件无写入权限',
|
||||
'The current state of the module cannot be set to disabled' => '模块当前状态无法设定为禁用',
|
||||
'The current state of the module cannot be set to enabled' => '模块当前状态无法设定为启用',
|
||||
'Module file updated' => '模块文件有更新',
|
||||
'Please disable the module first' => '请先禁用模块',
|
||||
'Please disable the module before updating' => '更新前请先禁用模块',
|
||||
'The directory required by the module is occupied' => '模块所需目录已被占用',
|
||||
'Install module' => '安装模块',
|
||||
'Unload module' => '卸载模块',
|
||||
'Update module' => '更新模块',
|
||||
'Change module state' => '改变模块状态',
|
||||
'Upload install module' => '上传安装模块',
|
||||
'Please login to the official website account first' => '请先使用BuildAdmin官网账户登录到模块市场~',
|
||||
'composer config %s conflict' => 'composer 配置项 %s 存在冲突',
|
||||
];
|
||||
@@ -1,950 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace app\admin\library\module;
|
||||
|
||||
use Throwable;
|
||||
use ba\Version;
|
||||
use ba\Depends;
|
||||
use ba\Exception;
|
||||
use ba\Filesystem;
|
||||
use FilesystemIterator;
|
||||
use RecursiveDirectoryIterator;
|
||||
use RecursiveIteratorIterator;
|
||||
use Webman\Http\Request;
|
||||
|
||||
/**
|
||||
* 模块管理类(Webman 迁移版)
|
||||
*/
|
||||
class Manage
|
||||
{
|
||||
public const UNINSTALLED = 0;
|
||||
public const INSTALLED = 1;
|
||||
public const WAIT_INSTALL = 2;
|
||||
public const CONFLICT_PENDING = 3;
|
||||
public const DEPENDENT_WAIT_INSTALL = 4;
|
||||
public const DIRECTORY_OCCUPIED = 5;
|
||||
public const DISABLE = 6;
|
||||
|
||||
protected static ?Manage $instance = null;
|
||||
|
||||
protected string $installDir;
|
||||
|
||||
protected string $backupsDir;
|
||||
|
||||
protected string $uid;
|
||||
|
||||
protected string $modulesDir;
|
||||
|
||||
public static function instance(string $uid = ''): Manage
|
||||
{
|
||||
if (self::$instance === null) {
|
||||
self::$instance = new static($uid);
|
||||
}
|
||||
return self::$instance->setModuleUid($uid);
|
||||
}
|
||||
|
||||
public function __construct(string $uid)
|
||||
{
|
||||
$this->installDir = root_path() . 'modules' . DIRECTORY_SEPARATOR;
|
||||
$this->backupsDir = $this->installDir . 'backups' . DIRECTORY_SEPARATOR;
|
||||
if (!is_dir($this->installDir)) {
|
||||
mkdir($this->installDir, 0755, true);
|
||||
}
|
||||
if (!is_dir($this->backupsDir)) {
|
||||
mkdir($this->backupsDir, 0755, true);
|
||||
}
|
||||
|
||||
if ($uid) {
|
||||
$this->setModuleUid($uid);
|
||||
} else {
|
||||
$this->uid = '';
|
||||
$this->modulesDir = $this->installDir;
|
||||
}
|
||||
}
|
||||
|
||||
public function getInstallState(): int
|
||||
{
|
||||
if (!is_dir($this->modulesDir)) {
|
||||
return self::UNINSTALLED;
|
||||
}
|
||||
$info = $this->getInfo();
|
||||
if ($info && isset($info['state'])) {
|
||||
return $info['state'];
|
||||
}
|
||||
return Filesystem::dirIsEmpty($this->modulesDir) ? self::UNINSTALLED : self::DIRECTORY_OCCUPIED;
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 Webman Request 上传安装(适配 Multipart 上传)
|
||||
* @return array 模块基本信息
|
||||
* @throws Throwable
|
||||
*/
|
||||
public static function uploadFromRequest(Request $request): array
|
||||
{
|
||||
$file = $request->file('file');
|
||||
if (!$file) {
|
||||
throw new Exception('Parameter error');
|
||||
}
|
||||
$token = $request->post('token', $request->get('token', ''));
|
||||
if (!$token) {
|
||||
throw new Exception('Please login to the official website account first');
|
||||
}
|
||||
$uploadDir = root_path() . 'public' . DIRECTORY_SEPARATOR . 'storage' . DIRECTORY_SEPARATOR . 'upload' . DIRECTORY_SEPARATOR;
|
||||
if (!is_dir($uploadDir)) {
|
||||
mkdir($uploadDir, 0755, true);
|
||||
}
|
||||
$originalName = $file->getUploadName() ?? 'module.zip';
|
||||
$baseName = basename(str_replace(['\\', '/'], DIRECTORY_SEPARATOR, $originalName));
|
||||
if (!preg_match('/^[a-zA-Z0-9._-]+\.zip$/i', $baseName)) {
|
||||
throw new Exception('The uploaded file format is not allowed');
|
||||
}
|
||||
$saveName = 'temp' . DIRECTORY_SEPARATOR . date('YmdHis') . '_' . $baseName;
|
||||
$savePath = $uploadDir . $saveName;
|
||||
$saveDir = dirname($savePath);
|
||||
if (!is_dir($saveDir)) {
|
||||
mkdir($saveDir, 0755, true);
|
||||
}
|
||||
$file->move($savePath);
|
||||
$relativePath = 'storage/upload/' . str_replace(DIRECTORY_SEPARATOR, '/', $saveName);
|
||||
try {
|
||||
return self::instance('')->doUpload($token, $relativePath);
|
||||
} finally {
|
||||
if (is_file($savePath)) {
|
||||
@unlink($savePath);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 下载模块文件
|
||||
* @throws Throwable
|
||||
*/
|
||||
public function download(): string
|
||||
{
|
||||
$req = function_exists('request') ? request() : null;
|
||||
$token = $req ? ($req->post('token', $req->get('token', ''))) : '';
|
||||
$version = $req ? ($req->post('version', $req->get('version', ''))) : '';
|
||||
$orderId = $req ? ($req->post('orderId', $req->get('orderId', 0))) : 0;
|
||||
|
||||
if (!$orderId) {
|
||||
throw new Exception('Order not found');
|
||||
}
|
||||
|
||||
$zipFile = Server::download($this->uid, $this->installDir, [
|
||||
'version' => $version,
|
||||
'orderId' => $orderId,
|
||||
'nuxtVersion' => Server::getNuxtVersion(),
|
||||
'sysVersion' => config('buildadmin.version', ''),
|
||||
'installed' => Server::getInstalledIds($this->installDir),
|
||||
'ba-user-token' => $token,
|
||||
]);
|
||||
|
||||
Filesystem::delDir($this->modulesDir);
|
||||
Filesystem::unzip($zipFile);
|
||||
@unlink($zipFile);
|
||||
|
||||
$this->checkPackage();
|
||||
|
||||
$this->setInfo([
|
||||
'state' => self::WAIT_INSTALL,
|
||||
]);
|
||||
|
||||
return $zipFile;
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传安装(token + 文件相对路径)
|
||||
* @throws Throwable
|
||||
*/
|
||||
public function doUpload(string $token, string $file): array
|
||||
{
|
||||
$file = self::resolvePublicStorageFile($file);
|
||||
|
||||
$copyTo = $this->installDir . 'uploadTemp' . date('YmdHis') . '.zip';
|
||||
copy($file, $copyTo);
|
||||
|
||||
$copyToDir = Filesystem::unzip($copyTo);
|
||||
$copyToDir .= DIRECTORY_SEPARATOR;
|
||||
|
||||
@unlink($file);
|
||||
@unlink($copyTo);
|
||||
|
||||
$info = Server::getIni($copyToDir);
|
||||
if (empty($info['uid'])) {
|
||||
Filesystem::delDir($copyToDir);
|
||||
throw new Exception('Basic configuration of the Module is incomplete');
|
||||
}
|
||||
|
||||
$this->setModuleUid($info['uid']);
|
||||
|
||||
$upgrade = false;
|
||||
if (is_dir($this->modulesDir)) {
|
||||
$oldInfo = $this->getInfo();
|
||||
if ($oldInfo && !empty($oldInfo['uid'])) {
|
||||
$versions = explode('.', $oldInfo['version'] ?? '0.0.0');
|
||||
if (isset($versions[2])) {
|
||||
$versions[2]++;
|
||||
}
|
||||
$nextVersion = implode('.', $versions);
|
||||
$upgrade = Version::compare($nextVersion, $info['version'] ?? '');
|
||||
if ($upgrade) {
|
||||
if (!in_array($oldInfo['state'], [self::UNINSTALLED, self::WAIT_INSTALL, self::DISABLE])) {
|
||||
Filesystem::delDir($copyToDir);
|
||||
throw new Exception('Please disable the module before updating');
|
||||
}
|
||||
} else {
|
||||
Filesystem::delDir($copyToDir);
|
||||
throw new Exception('Module already exists');
|
||||
}
|
||||
}
|
||||
|
||||
if (!Filesystem::dirIsEmpty($this->modulesDir) && !$upgrade) {
|
||||
Filesystem::delDir($copyToDir);
|
||||
throw new Exception('The directory required by the module is occupied');
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
Server::installPreCheck([
|
||||
'uid' => $info['uid'],
|
||||
'version' => $info['version'] ?? '',
|
||||
'sysVersion' => config('buildadmin.version', ''),
|
||||
'nuxtVersion' => Server::getNuxtVersion(),
|
||||
'moduleVersion' => $info['version'] ?? '',
|
||||
'ba-user-token' => $token,
|
||||
'installed' => Server::getInstalledIds($this->installDir),
|
||||
'server' => 1,
|
||||
]);
|
||||
} catch (Throwable $e) {
|
||||
Filesystem::delDir($copyToDir);
|
||||
throw $e;
|
||||
}
|
||||
|
||||
$newInfo = ['state' => self::WAIT_INSTALL];
|
||||
if ($upgrade) {
|
||||
$info['update'] = 1;
|
||||
Filesystem::delDir($this->modulesDir);
|
||||
}
|
||||
|
||||
rename($copyToDir, $this->modulesDir);
|
||||
|
||||
$this->checkPackage();
|
||||
|
||||
$this->setInfo($newInfo);
|
||||
|
||||
return $info;
|
||||
}
|
||||
|
||||
/**
|
||||
* 安装模块
|
||||
* @throws Throwable
|
||||
*/
|
||||
public function install(bool $update): array
|
||||
{
|
||||
$state = $this->getInstallState();
|
||||
|
||||
if ($update) {
|
||||
if (!in_array($state, [self::UNINSTALLED, self::WAIT_INSTALL, self::DISABLE])) {
|
||||
throw new Exception('Please disable the module before updating');
|
||||
}
|
||||
if ($state == self::UNINSTALLED || $state != self::WAIT_INSTALL) {
|
||||
$this->download();
|
||||
}
|
||||
} else {
|
||||
if ($state == self::INSTALLED || $state == self::DIRECTORY_OCCUPIED || $state == self::DISABLE) {
|
||||
throw new Exception('Module already exists');
|
||||
}
|
||||
if ($state == self::UNINSTALLED) {
|
||||
$this->download();
|
||||
}
|
||||
}
|
||||
|
||||
Server::importSql($this->modulesDir);
|
||||
|
||||
$info = $this->getInfo();
|
||||
if ($update) {
|
||||
$info['update'] = 1;
|
||||
Server::execEvent($this->uid, 'update');
|
||||
}
|
||||
|
||||
$req = function_exists('request') ? request() : null;
|
||||
$extend = $req ? ($req->post('extend') ?? []) : [];
|
||||
if (!isset($extend['conflictHandle'])) {
|
||||
Server::execEvent($this->uid, 'install');
|
||||
}
|
||||
|
||||
$this->enable('install');
|
||||
|
||||
return $info;
|
||||
}
|
||||
|
||||
/**
|
||||
* 卸载
|
||||
* @throws Throwable
|
||||
*/
|
||||
public function uninstall(): void
|
||||
{
|
||||
$info = $this->getInfo();
|
||||
if (($info['state'] ?? 0) != self::DISABLE) {
|
||||
throw new Exception('Please disable the module first', 0, [
|
||||
'uid' => $this->uid,
|
||||
]);
|
||||
}
|
||||
|
||||
Server::execEvent($this->uid, 'uninstall');
|
||||
|
||||
Filesystem::delDir($this->modulesDir);
|
||||
}
|
||||
|
||||
/**
|
||||
* 修改模块状态
|
||||
* @throws Throwable
|
||||
*/
|
||||
public function changeState(bool $state): array
|
||||
{
|
||||
$info = $this->getInfo();
|
||||
if (!$state) {
|
||||
$canDisable = [
|
||||
self::INSTALLED,
|
||||
self::CONFLICT_PENDING,
|
||||
self::DEPENDENT_WAIT_INSTALL,
|
||||
];
|
||||
if (!in_array($info['state'] ?? 0, $canDisable)) {
|
||||
throw new Exception('The current state of the module cannot be set to disabled', 0, [
|
||||
'uid' => $this->uid,
|
||||
'state' => $info['state'] ?? 0,
|
||||
]);
|
||||
}
|
||||
return $this->disable();
|
||||
}
|
||||
|
||||
if (($info['state'] ?? 0) != self::DISABLE) {
|
||||
throw new Exception('The current state of the module cannot be set to enabled', 0, [
|
||||
'uid' => $this->uid,
|
||||
'state' => $info['state'] ?? 0,
|
||||
]);
|
||||
}
|
||||
$this->setInfo([
|
||||
'state' => self::WAIT_INSTALL,
|
||||
]);
|
||||
return $info;
|
||||
}
|
||||
|
||||
/**
|
||||
* 启用
|
||||
* @throws Throwable
|
||||
*/
|
||||
public function enable(string $trigger): void
|
||||
{
|
||||
Server::installWebBootstrap($this->uid, $this->modulesDir);
|
||||
Server::createRuntime($this->modulesDir);
|
||||
$this->conflictHandle($trigger);
|
||||
Server::execEvent($this->uid, 'enable');
|
||||
$this->dependUpdateHandle();
|
||||
}
|
||||
|
||||
/**
|
||||
* 禁用
|
||||
* @throws Throwable
|
||||
*/
|
||||
public function disable(): array
|
||||
{
|
||||
$req = function_exists('request') ? request() : null;
|
||||
$update = $req ? filter_var($req->post('update', false), FILTER_VALIDATE_BOOLEAN) : false;
|
||||
$confirmConflict = $req ? filter_var($req->post('confirmConflict', false), FILTER_VALIDATE_BOOLEAN) : false;
|
||||
$dependConflictSolution = $req ? ($req->post('dependConflictSolution') ?? []) : [];
|
||||
|
||||
$info = $this->getInfo();
|
||||
$zipFile = $this->backupsDir . $this->uid . '-install.zip';
|
||||
$zipDir = false;
|
||||
if (is_file($zipFile)) {
|
||||
try {
|
||||
$zipDir = $this->backupsDir . $this->uid . '-install' . DIRECTORY_SEPARATOR;
|
||||
Filesystem::unzip($zipFile, $zipDir);
|
||||
} catch (Exception) {
|
||||
// skip
|
||||
}
|
||||
}
|
||||
|
||||
$conflictFile = Server::getFileList($this->modulesDir, true);
|
||||
$dependConflict = $this->disableDependCheck();
|
||||
if (($conflictFile || !self::isEmptyArray($dependConflict)) && !$confirmConflict) {
|
||||
$dependConflictTemp = [];
|
||||
foreach ($dependConflict as $env => $item) {
|
||||
foreach ($item as $depend => $v) {
|
||||
$dependConflictTemp[] = [
|
||||
'env' => $env,
|
||||
'depend' => $depend,
|
||||
'dependTitle' => $depend . ' ' . $v,
|
||||
'solution' => 'delete',
|
||||
];
|
||||
}
|
||||
}
|
||||
throw new Exception('Module file updated', -1, [
|
||||
'uid' => $this->uid,
|
||||
'conflictFile' => $conflictFile,
|
||||
'dependConflict' => $dependConflictTemp,
|
||||
]);
|
||||
}
|
||||
|
||||
Server::execEvent($this->uid, 'disable', ['update' => $update]);
|
||||
|
||||
$delNpmDepend = false;
|
||||
$delNuxtNpmDepend = false;
|
||||
$delComposerDepend = false;
|
||||
foreach ($dependConflictSolution as $env => $depends) {
|
||||
if (!$depends) continue;
|
||||
if ($env == 'require' || $env == 'require-dev') {
|
||||
$delComposerDepend = true;
|
||||
} elseif ($env == 'dependencies' || $env == 'devDependencies') {
|
||||
$delNpmDepend = true;
|
||||
} elseif ($env == 'nuxtDependencies' || $env == 'nuxtDevDependencies') {
|
||||
$delNuxtNpmDepend = true;
|
||||
}
|
||||
}
|
||||
|
||||
$dependJsonFiles = [
|
||||
'composer' => 'composer.json',
|
||||
'webPackage' => 'web' . DIRECTORY_SEPARATOR . 'package.json',
|
||||
'webNuxtPackage' => 'web-nuxt' . DIRECTORY_SEPARATOR . 'package.json',
|
||||
];
|
||||
$dependWaitInstall = [];
|
||||
if ($delComposerDepend) {
|
||||
$conflictFile[] = $dependJsonFiles['composer'];
|
||||
$dependWaitInstall[] = [
|
||||
'pm' => false,
|
||||
'command' => 'composer.update',
|
||||
'type' => 'composer_dependent_wait_install',
|
||||
];
|
||||
}
|
||||
if ($delNpmDepend) {
|
||||
$conflictFile[] = $dependJsonFiles['webPackage'];
|
||||
$dependWaitInstall[] = [
|
||||
'pm' => true,
|
||||
'command' => 'web-install',
|
||||
'type' => 'npm_dependent_wait_install',
|
||||
];
|
||||
}
|
||||
if ($delNuxtNpmDepend) {
|
||||
$conflictFile[] = $dependJsonFiles['webNuxtPackage'];
|
||||
$dependWaitInstall[] = [
|
||||
'pm' => true,
|
||||
'command' => 'nuxt-install',
|
||||
'type' => 'nuxt_npm_dependent_wait_install',
|
||||
];
|
||||
}
|
||||
if ($conflictFile) {
|
||||
$overwriteDir = Server::getOverwriteDir();
|
||||
foreach ($conflictFile as $key => $item) {
|
||||
$paths = explode(DIRECTORY_SEPARATOR, $item);
|
||||
if (in_array($paths[0], $overwriteDir) || in_array($item, $dependJsonFiles)) {
|
||||
$conflictFile[$key] = $item;
|
||||
} else {
|
||||
$conflictFile[$key] = Filesystem::fsFit(str_replace(root_path(), '', $this->modulesDir . $item));
|
||||
}
|
||||
if (!is_file(root_path() . $conflictFile[$key])) {
|
||||
unset($conflictFile[$key]);
|
||||
}
|
||||
}
|
||||
$backupsZip = $this->backupsDir . $this->uid . '-disable-' . date('YmdHis') . '.zip';
|
||||
Filesystem::zip($conflictFile, $backupsZip);
|
||||
}
|
||||
|
||||
$serverDepend = new Depends(root_path() . 'composer.json', 'composer');
|
||||
$webDep = new Depends(root_path() . 'web' . DIRECTORY_SEPARATOR . 'package.json');
|
||||
$webNuxtDep = new Depends(root_path() . 'web-nuxt' . DIRECTORY_SEPARATOR . 'package.json');
|
||||
foreach ($dependConflictSolution as $env => $depends) {
|
||||
if (!$depends) continue;
|
||||
$dev = stripos($env, 'dev') !== false;
|
||||
if ($env == 'require' || $env == 'require-dev') {
|
||||
$serverDepend->removeDepends($depends, $dev);
|
||||
} elseif ($env == 'dependencies' || $env == 'devDependencies') {
|
||||
$webDep->removeDepends($depends, $dev);
|
||||
} elseif ($env == 'nuxtDependencies' || $env == 'nuxtDevDependencies') {
|
||||
$webNuxtDep->removeDepends($depends, $dev);
|
||||
}
|
||||
}
|
||||
|
||||
$composerConfig = Server::getConfig($this->modulesDir, 'composerConfig');
|
||||
if ($composerConfig) {
|
||||
$serverDepend->removeComposerConfig($composerConfig);
|
||||
}
|
||||
|
||||
$protectedFiles = Server::getConfig($this->modulesDir, 'protectedFiles');
|
||||
foreach ($protectedFiles as &$protectedFile) {
|
||||
$protectedFile = Filesystem::fsFit(root_path() . $protectedFile);
|
||||
}
|
||||
$moduleFile = Server::getFileList($this->modulesDir);
|
||||
|
||||
foreach ($moduleFile as &$file) {
|
||||
$moduleFilePath = Filesystem::fsFit($this->modulesDir . $file);
|
||||
$file = Filesystem::fsFit(root_path() . $file);
|
||||
if (!file_exists($file)) continue;
|
||||
if (!file_exists($moduleFilePath)) {
|
||||
if (!is_dir(dirname($moduleFilePath))) {
|
||||
mkdir(dirname($moduleFilePath), 0755, true);
|
||||
}
|
||||
copy($file, $moduleFilePath);
|
||||
}
|
||||
|
||||
if (in_array($file, $protectedFiles)) {
|
||||
continue;
|
||||
}
|
||||
if (file_exists($file)) {
|
||||
unlink($file);
|
||||
}
|
||||
Filesystem::delEmptyDir(dirname($file));
|
||||
}
|
||||
|
||||
if ($zipDir) {
|
||||
$unrecoverableFiles = [
|
||||
Filesystem::fsFit(root_path() . 'composer.json'),
|
||||
Filesystem::fsFit(root_path() . 'web/package.json'),
|
||||
Filesystem::fsFit(root_path() . 'web-nuxt/package.json'),
|
||||
];
|
||||
foreach (
|
||||
new RecursiveIteratorIterator(
|
||||
new RecursiveDirectoryIterator($zipDir, FilesystemIterator::SKIP_DOTS),
|
||||
RecursiveIteratorIterator::SELF_FIRST
|
||||
) as $item
|
||||
) {
|
||||
$backupsFile = Filesystem::fsFit(root_path() . str_replace($zipDir, '', $item->getPathname()));
|
||||
|
||||
if (in_array($backupsFile, $moduleFile) && !in_array($backupsFile, $protectedFiles)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($item->isDir()) {
|
||||
if (!is_dir($backupsFile)) {
|
||||
mkdir($backupsFile, 0755, true);
|
||||
}
|
||||
} elseif (!in_array($backupsFile, $unrecoverableFiles)) {
|
||||
copy($item->getPathname(), $backupsFile);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ($zipDir && is_dir($zipDir)) {
|
||||
Filesystem::delDir($zipDir);
|
||||
}
|
||||
|
||||
Server::uninstallWebBootstrap($this->uid);
|
||||
|
||||
$this->setInfo([
|
||||
'state' => self::DISABLE,
|
||||
]);
|
||||
|
||||
if ($update) {
|
||||
throw new Exception('update', -3, [
|
||||
'uid' => $this->uid,
|
||||
]);
|
||||
}
|
||||
|
||||
if (!empty($dependWaitInstall)) {
|
||||
throw new Exception('dependent wait install', -2, [
|
||||
'uid' => $this->uid,
|
||||
'wait_install' => $dependWaitInstall,
|
||||
]);
|
||||
}
|
||||
return $info;
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理依赖和文件冲突
|
||||
* @throws Throwable
|
||||
*/
|
||||
public function conflictHandle(string $trigger): bool
|
||||
{
|
||||
$info = $this->getInfo();
|
||||
if (!in_array($info['state'] ?? 0, [self::WAIT_INSTALL, self::CONFLICT_PENDING])) {
|
||||
return false;
|
||||
}
|
||||
$fileConflict = Server::getFileList($this->modulesDir, true);
|
||||
$dependConflict = Server::dependConflictCheck($this->modulesDir);
|
||||
$installFiles = Server::getFileList($this->modulesDir);
|
||||
$depends = Server::getDepend($this->modulesDir);
|
||||
|
||||
$coverFiles = [];
|
||||
$discardFiles = [];
|
||||
$serverDep = new Depends(root_path() . 'composer.json', 'composer');
|
||||
$webDep = new Depends(root_path() . 'web' . DIRECTORY_SEPARATOR . 'package.json');
|
||||
$webNuxtDep = new Depends(root_path() . 'web-nuxt' . DIRECTORY_SEPARATOR . 'package.json');
|
||||
|
||||
$req = function_exists('request') ? request() : null;
|
||||
$extend = $req ? ($req->post('extend') ?? []) : [];
|
||||
|
||||
if ($fileConflict || !self::isEmptyArray($dependConflict)) {
|
||||
if (!$extend) {
|
||||
$fileConflictTemp = [];
|
||||
foreach ($fileConflict as $key => $item) {
|
||||
$fileConflictTemp[$key] = [
|
||||
'newFile' => $this->uid . DIRECTORY_SEPARATOR . $item,
|
||||
'oldFile' => $item,
|
||||
'solution' => 'cover',
|
||||
];
|
||||
}
|
||||
$dependConflictTemp = [];
|
||||
foreach ($dependConflict as $env => $item) {
|
||||
$dev = stripos($env, 'dev') !== false;
|
||||
foreach ($item as $depend => $v) {
|
||||
$oldDepend = '';
|
||||
if (in_array($env, ['require', 'require-dev'])) {
|
||||
$oldDepend = $depend . ' ' . $serverDep->hasDepend($depend, $dev);
|
||||
} elseif (in_array($env, ['dependencies', 'devDependencies'])) {
|
||||
$oldDepend = $depend . ' ' . $webDep->hasDepend($depend, $dev);
|
||||
} elseif (in_array($env, ['nuxtDependencies', 'nuxtDevDependencies'])) {
|
||||
$oldDepend = $depend . ' ' . $webNuxtDep->hasDepend($depend, $dev);
|
||||
}
|
||||
$dependConflictTemp[] = [
|
||||
'env' => $env,
|
||||
'newDepend' => $depend . ' ' . $v,
|
||||
'oldDepend' => $oldDepend,
|
||||
'depend' => $depend,
|
||||
'solution' => 'cover',
|
||||
];
|
||||
}
|
||||
}
|
||||
$this->setInfo([
|
||||
'state' => self::CONFLICT_PENDING,
|
||||
]);
|
||||
throw new Exception('Module file conflicts', -1, [
|
||||
'fileConflict' => $fileConflictTemp,
|
||||
'dependConflict' => $dependConflictTemp,
|
||||
'uid' => $this->uid,
|
||||
'state' => self::CONFLICT_PENDING,
|
||||
]);
|
||||
}
|
||||
|
||||
if ($fileConflict && isset($extend['fileConflict'])) {
|
||||
foreach ($installFiles as $ikey => $installFile) {
|
||||
if (isset($extend['fileConflict'][$installFile])) {
|
||||
if ($extend['fileConflict'][$installFile] == 'discard') {
|
||||
$discardFiles[] = $installFile;
|
||||
unset($installFiles[$ikey]);
|
||||
} else {
|
||||
$coverFiles[] = $installFile;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!self::isEmptyArray($dependConflict) && isset($extend['dependConflict'])) {
|
||||
foreach ($depends as $fKey => $fItem) {
|
||||
foreach ($fItem as $cKey => $cItem) {
|
||||
if (isset($extend['dependConflict'][$fKey][$cKey])) {
|
||||
if ($extend['dependConflict'][$fKey][$cKey] == 'discard') {
|
||||
unset($depends[$fKey][$cKey]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ($depends) {
|
||||
foreach ($depends as $key => $item) {
|
||||
if (!$item) continue;
|
||||
if ($key == 'require' || $key == 'require-dev') {
|
||||
$coverFiles[] = 'composer.json';
|
||||
continue;
|
||||
}
|
||||
if ($key == 'dependencies' || $key == 'devDependencies') {
|
||||
$coverFiles[] = 'web' . DIRECTORY_SEPARATOR . 'package.json';
|
||||
}
|
||||
if ($key == 'nuxtDependencies' || $key == 'nuxtDevDependencies') {
|
||||
$coverFiles[] = 'web-nuxt' . DIRECTORY_SEPARATOR . 'package.json';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ($coverFiles) {
|
||||
$backupsZip = $trigger == 'install' ? $this->backupsDir . $this->uid . '-install.zip' : $this->backupsDir . $this->uid . '-cover-' . date('YmdHis') . '.zip';
|
||||
Filesystem::zip($coverFiles, $backupsZip);
|
||||
}
|
||||
|
||||
if ($depends) {
|
||||
$npm = false;
|
||||
$composer = false;
|
||||
$nuxtNpm = false;
|
||||
|
||||
$composerConfig = Server::getConfig($this->modulesDir, 'composerConfig');
|
||||
if ($composerConfig) {
|
||||
$serverDep->setComposerConfig($composerConfig);
|
||||
}
|
||||
|
||||
foreach ($depends as $key => $item) {
|
||||
if (!$item) continue;
|
||||
if ($key == 'require') {
|
||||
$composer = true;
|
||||
$serverDep->addDepends($item, false, true);
|
||||
} elseif ($key == 'require-dev') {
|
||||
$composer = true;
|
||||
$serverDep->addDepends($item, true, true);
|
||||
} elseif ($key == 'dependencies') {
|
||||
$npm = true;
|
||||
$webDep->addDepends($item, false, true);
|
||||
} elseif ($key == 'devDependencies') {
|
||||
$npm = true;
|
||||
$webDep->addDepends($item, true, true);
|
||||
} elseif ($key == 'nuxtDependencies') {
|
||||
$nuxtNpm = true;
|
||||
$webNuxtDep->addDepends($item, false, true);
|
||||
} elseif ($key == 'nuxtDevDependencies') {
|
||||
$nuxtNpm = true;
|
||||
$webNuxtDep->addDepends($item, true, true);
|
||||
}
|
||||
}
|
||||
if ($npm) {
|
||||
$info['npm_dependent_wait_install'] = 1;
|
||||
$info['state'] = self::DEPENDENT_WAIT_INSTALL;
|
||||
}
|
||||
if ($composer) {
|
||||
$info['composer_dependent_wait_install'] = 1;
|
||||
$info['state'] = self::DEPENDENT_WAIT_INSTALL;
|
||||
}
|
||||
if ($nuxtNpm) {
|
||||
$info['nuxt_npm_dependent_wait_install'] = 1;
|
||||
$info['state'] = self::DEPENDENT_WAIT_INSTALL;
|
||||
}
|
||||
$info = $info ?? $this->getInfo();
|
||||
if (($info['state'] ?? 0) != self::DEPENDENT_WAIT_INSTALL) {
|
||||
$this->setInfo(['state' => self::INSTALLED]);
|
||||
} else {
|
||||
$this->setInfo([], $info);
|
||||
}
|
||||
} else {
|
||||
$this->setInfo(['state' => self::INSTALLED]);
|
||||
}
|
||||
|
||||
$overwriteDir = Server::getOverwriteDir();
|
||||
foreach ($overwriteDir as $dirItem) {
|
||||
$baseDir = $this->modulesDir . $dirItem;
|
||||
$destDir = root_path() . $dirItem;
|
||||
if (!is_dir($baseDir)) continue;
|
||||
|
||||
foreach (
|
||||
new RecursiveIteratorIterator(
|
||||
new RecursiveDirectoryIterator($baseDir, FilesystemIterator::SKIP_DOTS),
|
||||
RecursiveIteratorIterator::SELF_FIRST
|
||||
) as $item
|
||||
) {
|
||||
$destDirItem = Filesystem::fsFit($destDir . DIRECTORY_SEPARATOR . str_replace($baseDir, '', $item->getPathname()));
|
||||
if ($item->isDir()) {
|
||||
Filesystem::mkdir($destDirItem);
|
||||
} elseif (!in_array(str_replace(root_path(), '', $destDirItem), $discardFiles)) {
|
||||
Filesystem::mkdir(dirname($destDirItem));
|
||||
copy($item->getPathname(), $destDirItem);
|
||||
}
|
||||
}
|
||||
if (config('buildadmin.module_pure_install', false)) {
|
||||
Filesystem::delDir($baseDir);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 依赖升级处理
|
||||
* @throws Throwable
|
||||
*/
|
||||
public function dependUpdateHandle(): void
|
||||
{
|
||||
$info = $this->getInfo();
|
||||
if (($info['state'] ?? 0) == self::DEPENDENT_WAIT_INSTALL) {
|
||||
$waitInstall = [];
|
||||
if (isset($info['composer_dependent_wait_install'])) {
|
||||
$waitInstall[] = 'composer_dependent_wait_install';
|
||||
}
|
||||
if (isset($info['npm_dependent_wait_install'])) {
|
||||
$waitInstall[] = 'npm_dependent_wait_install';
|
||||
}
|
||||
if (isset($info['nuxt_npm_dependent_wait_install'])) {
|
||||
$waitInstall[] = 'nuxt_npm_dependent_wait_install';
|
||||
}
|
||||
if ($waitInstall) {
|
||||
throw new Exception('dependent wait install', -2, [
|
||||
'uid' => $this->uid,
|
||||
'state' => self::DEPENDENT_WAIT_INSTALL,
|
||||
'wait_install' => $waitInstall,
|
||||
]);
|
||||
} else {
|
||||
$this->setInfo(['state' => self::INSTALLED]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 依赖安装完成标记
|
||||
* @throws Throwable
|
||||
*/
|
||||
public function dependentInstallComplete(string $type): void
|
||||
{
|
||||
$info = $this->getInfo();
|
||||
if (($info['state'] ?? 0) == self::DEPENDENT_WAIT_INSTALL) {
|
||||
if ($type == 'npm') {
|
||||
unset($info['npm_dependent_wait_install']);
|
||||
}
|
||||
if ($type == 'nuxt_npm') {
|
||||
unset($info['nuxt_npm_dependent_wait_install']);
|
||||
}
|
||||
if ($type == 'composer') {
|
||||
unset($info['composer_dependent_wait_install']);
|
||||
}
|
||||
if ($type == 'all') {
|
||||
unset($info['npm_dependent_wait_install'], $info['composer_dependent_wait_install'], $info['nuxt_npm_dependent_wait_install']);
|
||||
}
|
||||
if (!isset($info['npm_dependent_wait_install']) && !isset($info['composer_dependent_wait_install']) && !isset($info['nuxt_npm_dependent_wait_install'])) {
|
||||
$info['state'] = self::INSTALLED;
|
||||
}
|
||||
$this->setInfo([], $info);
|
||||
}
|
||||
}
|
||||
|
||||
public function disableDependCheck(): array
|
||||
{
|
||||
$depend = Server::getDepend($this->modulesDir);
|
||||
if (!$depend) return [];
|
||||
|
||||
$serverDep = new Depends(root_path() . 'composer.json', 'composer');
|
||||
$webDep = new Depends(root_path() . 'web' . DIRECTORY_SEPARATOR . 'package.json');
|
||||
$webNuxtDep = new Depends(root_path() . 'web-nuxt' . DIRECTORY_SEPARATOR . 'package.json');
|
||||
|
||||
foreach ($depend as $key => $depends) {
|
||||
$dev = stripos($key, 'dev') !== false;
|
||||
if ($key == 'require' || $key == 'require-dev') {
|
||||
foreach ($depends as $dependKey => $dependItem) {
|
||||
if (!$serverDep->hasDepend($dependKey, $dev)) {
|
||||
unset($depends[$dependKey]);
|
||||
}
|
||||
}
|
||||
$depend[$key] = $depends;
|
||||
} elseif ($key == 'dependencies' || $key == 'devDependencies') {
|
||||
foreach ($depends as $dependKey => $dependItem) {
|
||||
if (!$webDep->hasDepend($dependKey, $dev)) {
|
||||
unset($depends[$dependKey]);
|
||||
}
|
||||
}
|
||||
$depend[$key] = $depends;
|
||||
} elseif ($key == 'nuxtDependencies' || $key == 'nuxtDevDependencies') {
|
||||
foreach ($depends as $dependKey => $dependItem) {
|
||||
if (!$webNuxtDep->hasDepend($dependKey, $dev)) {
|
||||
unset($depends[$dependKey]);
|
||||
}
|
||||
}
|
||||
$depend[$key] = $depends;
|
||||
}
|
||||
}
|
||||
return $depend;
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查包是否完整
|
||||
* @throws Throwable
|
||||
*/
|
||||
public function checkPackage(): bool
|
||||
{
|
||||
if (!is_dir($this->modulesDir)) {
|
||||
throw new Exception('Module package file does not exist');
|
||||
}
|
||||
$info = $this->getInfo();
|
||||
$infoKeys = ['uid', 'title', 'intro', 'author', 'version', 'state'];
|
||||
foreach ($infoKeys as $value) {
|
||||
if (!array_key_exists($value, $info)) {
|
||||
Filesystem::delDir($this->modulesDir);
|
||||
throw new Exception('Basic configuration of the Module is incomplete');
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public function getInfo(): array
|
||||
{
|
||||
return Server::getIni($this->modulesDir);
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws Throwable
|
||||
*/
|
||||
public function setInfo(array $kv = [], array $arr = []): bool
|
||||
{
|
||||
if ($kv) {
|
||||
$info = $this->getInfo();
|
||||
foreach ($kv as $k => $v) {
|
||||
$info[$k] = $v;
|
||||
}
|
||||
return Server::setIni($this->modulesDir, $info);
|
||||
}
|
||||
if ($arr) {
|
||||
return Server::setIni($this->modulesDir, $arr);
|
||||
}
|
||||
throw new Exception('Parameter error');
|
||||
}
|
||||
|
||||
public static function isEmptyArray($arr): bool
|
||||
{
|
||||
foreach ($arr as $item) {
|
||||
if (is_array($item)) {
|
||||
if (!self::isEmptyArray($item)) return false;
|
||||
} elseif ($item) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public function setModuleUid(string $uid): static
|
||||
{
|
||||
$this->uid = $uid;
|
||||
$this->modulesDir = $this->installDir . $uid . DIRECTORY_SEPARATOR;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析并校验模块包路径,仅允许 public/storage 下的 zip 文件,防止路径穿越
|
||||
* @throws Exception
|
||||
*/
|
||||
protected static function resolvePublicStorageFile(string $file): string
|
||||
{
|
||||
if (preg_match('#^(https?:)?//#i', $file)) {
|
||||
$parsed = parse_url($file);
|
||||
$file = $parsed['path'] ?? '';
|
||||
}
|
||||
|
||||
$relative = ltrim(str_replace('\\', '/', $file), '/');
|
||||
if ($relative === '' || str_contains($relative, '..')) {
|
||||
throw new Exception('Invalid file path');
|
||||
}
|
||||
|
||||
$publicRoot = realpath(public_path());
|
||||
if ($publicRoot === false) {
|
||||
throw new Exception('Invalid file path');
|
||||
}
|
||||
|
||||
$candidate = Filesystem::fsFit($publicRoot . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $relative));
|
||||
$fullPath = realpath($candidate);
|
||||
if ($fullPath === false || !is_file($fullPath)) {
|
||||
throw new Exception('Zip file not found');
|
||||
}
|
||||
|
||||
$publicPrefix = rtrim($publicRoot, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
|
||||
if (!str_starts_with($fullPath, $publicPrefix)) {
|
||||
throw new Exception('Invalid file path');
|
||||
}
|
||||
|
||||
$storageRoot = realpath(public_path('storage'));
|
||||
if ($storageRoot === false) {
|
||||
throw new Exception('Invalid file path');
|
||||
}
|
||||
$storagePrefix = rtrim($storageRoot, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
|
||||
if (!str_starts_with($fullPath, $storagePrefix)) {
|
||||
throw new Exception('Invalid file path');
|
||||
}
|
||||
|
||||
if (strtolower(pathinfo($fullPath, PATHINFO_EXTENSION)) !== 'zip') {
|
||||
throw new Exception('The uploaded file format is not allowed');
|
||||
}
|
||||
|
||||
return $fullPath;
|
||||
}
|
||||
}
|
||||
@@ -1,551 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace app\admin\library\module;
|
||||
|
||||
use Throwable;
|
||||
use ba\Depends;
|
||||
use ba\Exception;
|
||||
use ba\Filesystem;
|
||||
use support\think\Db;
|
||||
use FilesystemIterator;
|
||||
use RecursiveIteratorIterator;
|
||||
use RecursiveDirectoryIterator;
|
||||
use think\db\exception\PDOException;
|
||||
use app\admin\library\crud\Helper;
|
||||
use GuzzleHttp\Exception\TransferException;
|
||||
|
||||
/**
|
||||
* 模块服务类(Webman 迁移版)
|
||||
*/
|
||||
class Server
|
||||
{
|
||||
private static string $apiBaseUrl = '/api/v7.store/';
|
||||
|
||||
/**
|
||||
* 下载
|
||||
* @throws Throwable
|
||||
*/
|
||||
public static function download(string $uid, string $dir, array $extend = []): string
|
||||
{
|
||||
$tmpFile = $dir . $uid . ".zip";
|
||||
try {
|
||||
$client = get_ba_client();
|
||||
$response = $client->get(self::$apiBaseUrl . 'download', ['query' => array_merge(['uid' => $uid, 'server' => 1], $extend)]);
|
||||
$body = $response->getBody();
|
||||
$content = $body->getContents();
|
||||
if ($content == '' || stripos($content, '<title>系统发生错误</title>') !== false) {
|
||||
throw new Exception('package download failed', 0);
|
||||
}
|
||||
if (str_starts_with($content, '{')) {
|
||||
$json = (array)json_decode($content, true);
|
||||
throw new Exception($json['msg'], $json['code'], $json['data'] ?? []);
|
||||
}
|
||||
} catch (TransferException $e) {
|
||||
throw new Exception('package download failed', 0, ['msg' => $e->getMessage()]);
|
||||
}
|
||||
|
||||
if ($write = fopen($tmpFile, 'w')) {
|
||||
fwrite($write, $content);
|
||||
fclose($write);
|
||||
return $tmpFile;
|
||||
}
|
||||
throw new Exception("No permission to write temporary files");
|
||||
}
|
||||
|
||||
/**
|
||||
* 安装预检
|
||||
* @throws Throwable
|
||||
*/
|
||||
public static function installPreCheck(array $query = []): bool
|
||||
{
|
||||
try {
|
||||
$client = get_ba_client();
|
||||
$response = $client->get(self::$apiBaseUrl . 'preCheck', ['query' => $query]);
|
||||
$body = $response->getBody();
|
||||
$statusCode = $response->getStatusCode();
|
||||
$content = $body->getContents();
|
||||
if ($content == '' || stripos($content, '<title>系统发生错误</title>') !== false || $statusCode != 200) {
|
||||
return true;
|
||||
}
|
||||
if (str_starts_with($content, '{')) {
|
||||
$json = json_decode($content, true);
|
||||
if ($json && $json['code'] == 0) {
|
||||
throw new Exception($json['msg'], $json['code'], $json['data'] ?? []);
|
||||
}
|
||||
}
|
||||
} catch (TransferException $e) {
|
||||
throw new Exception('package check failed', 0, ['msg' => $e->getMessage()]);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public static function getConfig(string $dir, $key = ''): array
|
||||
{
|
||||
$configFile = $dir . 'config.json';
|
||||
if (!is_dir($dir) || !is_file($configFile)) {
|
||||
return [];
|
||||
}
|
||||
$configContent = @file_get_contents($configFile);
|
||||
$configContent = json_decode($configContent, true);
|
||||
if (!$configContent) {
|
||||
return [];
|
||||
}
|
||||
if ($key) {
|
||||
return $configContent[$key] ?? [];
|
||||
}
|
||||
return $configContent;
|
||||
}
|
||||
|
||||
public static function getDepend(string $dir, string $key = ''): array
|
||||
{
|
||||
if ($key) {
|
||||
return self::getConfig($dir, $key);
|
||||
}
|
||||
$configContent = self::getConfig($dir);
|
||||
$dependKey = ['require', 'require-dev', 'dependencies', 'devDependencies', 'nuxtDependencies', 'nuxtDevDependencies'];
|
||||
$dependArray = [];
|
||||
foreach ($dependKey as $item) {
|
||||
if (array_key_exists($item, $configContent) && $configContent[$item]) {
|
||||
$dependArray[$item] = $configContent[$item];
|
||||
}
|
||||
}
|
||||
return $dependArray;
|
||||
}
|
||||
|
||||
/**
|
||||
* 依赖冲突检查
|
||||
* @throws Throwable
|
||||
*/
|
||||
public static function dependConflictCheck(string $dir): array
|
||||
{
|
||||
$depend = self::getDepend($dir);
|
||||
$serverDep = new Depends(root_path() . 'composer.json', 'composer');
|
||||
$webDep = new Depends(root_path() . 'web' . DIRECTORY_SEPARATOR . 'package.json');
|
||||
$webNuxtDep = new Depends(root_path() . 'web-nuxt' . DIRECTORY_SEPARATOR . 'package.json');
|
||||
$sysDepend = [
|
||||
'require' => $serverDep->getDepends(),
|
||||
'require-dev' => $serverDep->getDepends(true),
|
||||
'dependencies' => $webDep->getDepends(),
|
||||
'devDependencies' => $webDep->getDepends(true),
|
||||
'nuxtDependencies' => $webNuxtDep->getDepends(),
|
||||
'nuxtDevDependencies' => $webNuxtDep->getDepends(true),
|
||||
];
|
||||
|
||||
$conflict = [];
|
||||
foreach ($depend as $key => $item) {
|
||||
$conflict[$key] = array_uintersect_assoc($item, $sysDepend[$key] ?? [], function ($a, $b) {
|
||||
return $a == $b ? -1 : 0;
|
||||
});
|
||||
}
|
||||
return $conflict;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取模块[冲突]文件列表
|
||||
*/
|
||||
public static function getFileList(string $dir, bool $onlyConflict = false): array
|
||||
{
|
||||
if (!is_dir($dir)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$fileList = [];
|
||||
$overwriteDir = self::getOverwriteDir();
|
||||
$moduleFileList = self::getRuntime($dir, 'files');
|
||||
|
||||
if ($moduleFileList) {
|
||||
if ($onlyConflict) {
|
||||
$excludeFile = ['info.ini'];
|
||||
foreach ($moduleFileList as $file) {
|
||||
$path = Filesystem::fsFit(str_replace($dir, '', $file['path']));
|
||||
$paths = explode(DIRECTORY_SEPARATOR, $path);
|
||||
$overwriteFile = in_array($paths[0], $overwriteDir) ? root_path() . $path : $dir . $path;
|
||||
if (is_file($overwriteFile) && !in_array($path, $excludeFile) && (filesize($overwriteFile) != $file['size'] || md5_file($overwriteFile) != $file['md5'])) {
|
||||
$fileList[] = $path;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
foreach ($overwriteDir as $item) {
|
||||
$baseDir = $dir . $item;
|
||||
foreach ($moduleFileList as $file) {
|
||||
if (!str_starts_with($file['path'], $baseDir)) continue;
|
||||
$fileList[] = Filesystem::fsFit(str_replace($dir, '', $file['path']));
|
||||
}
|
||||
}
|
||||
}
|
||||
return $fileList;
|
||||
}
|
||||
|
||||
foreach ($overwriteDir as $item) {
|
||||
$baseDir = $dir . $item;
|
||||
if (!is_dir($baseDir)) {
|
||||
continue;
|
||||
}
|
||||
$files = new RecursiveIteratorIterator(
|
||||
new RecursiveDirectoryIterator($baseDir, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST
|
||||
);
|
||||
foreach ($files as $file) {
|
||||
if ($file->isFile()) {
|
||||
$filePath = $file->getPathName();
|
||||
$path = str_replace($dir, '', $filePath);
|
||||
$path = str_replace(['/', '\\'], DIRECTORY_SEPARATOR, $path);
|
||||
|
||||
if ($onlyConflict) {
|
||||
$overwriteFile = root_path() . $path;
|
||||
if (is_file($overwriteFile) && (filesize($overwriteFile) != filesize($filePath) || md5_file($overwriteFile) != md5_file($filePath))) {
|
||||
$fileList[] = $path;
|
||||
}
|
||||
} else {
|
||||
$fileList[] = $path;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return $fileList;
|
||||
}
|
||||
|
||||
public static function getOverwriteDir(): array
|
||||
{
|
||||
return [
|
||||
'app',
|
||||
'config',
|
||||
'database',
|
||||
'extend',
|
||||
'modules',
|
||||
'public',
|
||||
'vendor',
|
||||
'web',
|
||||
'web-nuxt',
|
||||
];
|
||||
}
|
||||
|
||||
public static function importSql(string $dir): bool
|
||||
{
|
||||
$sqlFile = $dir . 'install.sql';
|
||||
$tempLine = '';
|
||||
$prefix = config('thinkorm.connections.mysql.prefix', config('database.connections.mysql.prefix', ''));
|
||||
if (is_file($sqlFile)) {
|
||||
$lines = file($sqlFile);
|
||||
foreach ($lines as $line) {
|
||||
if (str_starts_with($line, '--') || $line == '' || str_starts_with($line, '/*')) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$tempLine .= $line;
|
||||
if (str_ends_with(trim($line), ';')) {
|
||||
$tempLine = str_ireplace('__PREFIX__', $prefix, $tempLine);
|
||||
$tempLine = str_ireplace('INSERT INTO ', 'INSERT IGNORE INTO ', $tempLine);
|
||||
try {
|
||||
Db::execute($tempLine);
|
||||
} catch (PDOException) {
|
||||
// ignore
|
||||
}
|
||||
$tempLine = '';
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public static function installedList(string $dir): array
|
||||
{
|
||||
if (!is_dir($dir)) {
|
||||
return [];
|
||||
}
|
||||
$installedDir = scandir($dir);
|
||||
$installedList = [];
|
||||
foreach ($installedDir as $item) {
|
||||
if ($item === '.' or $item === '..' || is_file($dir . $item)) {
|
||||
continue;
|
||||
}
|
||||
$tempDir = $dir . $item . DIRECTORY_SEPARATOR;
|
||||
if (!is_dir($tempDir)) {
|
||||
continue;
|
||||
}
|
||||
$info = self::getIni($tempDir);
|
||||
if (!isset($info['uid'])) {
|
||||
continue;
|
||||
}
|
||||
$installedList[] = $info;
|
||||
}
|
||||
return $installedList;
|
||||
}
|
||||
|
||||
public static function getInstalledIds(string $dir): array
|
||||
{
|
||||
$installedIds = [];
|
||||
$installed = self::installedList($dir);
|
||||
foreach ($installed as $item) {
|
||||
$installedIds[] = $item['uid'];
|
||||
}
|
||||
return $installedIds;
|
||||
}
|
||||
|
||||
public static function getIni(string $dir): array
|
||||
{
|
||||
$infoFile = $dir . 'info.ini';
|
||||
$info = [];
|
||||
if (is_file($infoFile)) {
|
||||
$info = parse_ini_file($infoFile, true, INI_SCANNER_TYPED) ?: [];
|
||||
if (!$info) return [];
|
||||
}
|
||||
return $info;
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws Throwable
|
||||
*/
|
||||
public static function setIni(string $dir, array $arr): bool
|
||||
{
|
||||
$infoFile = $dir . 'info.ini';
|
||||
$ini = [];
|
||||
foreach ($arr as $key => $val) {
|
||||
if (is_array($val)) {
|
||||
$ini[] = "[$key]";
|
||||
foreach ($val as $ikey => $ival) {
|
||||
$ini[] = "$ikey = $ival";
|
||||
}
|
||||
} else {
|
||||
$ini[] = "$key = $val";
|
||||
}
|
||||
}
|
||||
if (!file_put_contents($infoFile, implode("\n", $ini) . "\n", LOCK_EX)) {
|
||||
throw new Exception("Configuration file has no write permission");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public static function getClass(string $uid, string $type = 'event', ?string $class = null): string
|
||||
{
|
||||
$name = parse_name($uid);
|
||||
if (!is_null($class) && strpos($class, '.')) {
|
||||
$class = explode('.', $class);
|
||||
$class[count($class) - 1] = parse_name(end($class), 1);
|
||||
$class = implode('\\', $class);
|
||||
} else {
|
||||
$class = parse_name(is_null($class) ? $name : $class, 1);
|
||||
}
|
||||
$namespace = match ($type) {
|
||||
'controller' => '\\modules\\' . $name . '\\controller\\' . $class,
|
||||
default => '\\modules\\' . $name . '\\' . $class,
|
||||
};
|
||||
return class_exists($namespace) ? $namespace : '';
|
||||
}
|
||||
|
||||
public static function execEvent(string $uid, string $event, array $params = []): void
|
||||
{
|
||||
$eventClass = self::getClass($uid);
|
||||
if (class_exists($eventClass)) {
|
||||
$handle = new $eventClass();
|
||||
if (method_exists($eventClass, $event)) {
|
||||
$handle->$event($params);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static function analysisWebBootstrap(string $uid, string $dir): array
|
||||
{
|
||||
$bootstrapFile = $dir . 'webBootstrap.stub';
|
||||
if (!file_exists($bootstrapFile)) return [];
|
||||
$bootstrapContent = file_get_contents($bootstrapFile);
|
||||
$pregArr = [
|
||||
'mainTsImport' => '/#main.ts import code start#([\s\S]*?)#main.ts import code end#/i',
|
||||
'mainTsStart' => '/#main.ts start code start#([\s\S]*?)#main.ts start code end#/i',
|
||||
'appVueImport' => '/#App.vue import code start#([\s\S]*?)#App.vue import code end#/i',
|
||||
'appVueOnMounted' => '/#App.vue onMounted code start#([\s\S]*?)#App.vue onMounted code end#/i',
|
||||
'nuxtAppVueImport' => '/#web-nuxt\/app.vue import code start#([\s\S]*?)#web-nuxt\/app.vue import code end#/i',
|
||||
'nuxtAppVueStart' => '/#web-nuxt\/app.vue start code start#([\s\S]*?)#web-nuxt\/app.vue start code end#/i',
|
||||
];
|
||||
$codeStrArr = [];
|
||||
foreach ($pregArr as $key => $item) {
|
||||
preg_match($item, $bootstrapContent, $matches);
|
||||
if (isset($matches[1]) && $matches[1]) {
|
||||
$mainImportCodeArr = array_filter(preg_split('/\r\n|\r|\n/', $matches[1]));
|
||||
if ($mainImportCodeArr) {
|
||||
$codeStrArr[$key] = "\n";
|
||||
if (count($mainImportCodeArr) == 1) {
|
||||
foreach ($mainImportCodeArr as $codeItem) {
|
||||
$codeStrArr[$key] .= $codeItem . self::buildMarkStr('module-line-mark', $uid, $key);
|
||||
}
|
||||
} else {
|
||||
$codeStrArr[$key] .= self::buildMarkStr('module-multi-line-mark-start', $uid, $key);
|
||||
foreach ($mainImportCodeArr as $codeItem) {
|
||||
$codeStrArr[$key] .= $codeItem . "\n";
|
||||
}
|
||||
$codeStrArr[$key] .= self::buildMarkStr('module-multi-line-mark-end', $uid, $key);
|
||||
}
|
||||
}
|
||||
}
|
||||
unset($matches);
|
||||
}
|
||||
return $codeStrArr;
|
||||
}
|
||||
|
||||
public static function installWebBootstrap(string $uid, string $dir): void
|
||||
{
|
||||
$bootstrapCode = self::analysisWebBootstrap($uid, $dir);
|
||||
if (!$bootstrapCode) {
|
||||
return;
|
||||
}
|
||||
|
||||
$webPath = root_path() . 'web' . DIRECTORY_SEPARATOR . 'src' . DIRECTORY_SEPARATOR;
|
||||
$webNuxtPath = root_path() . 'web-nuxt' . DIRECTORY_SEPARATOR;
|
||||
$filePaths = [
|
||||
'mainTsImport' => $webPath . 'main.ts',
|
||||
'mainTsStart' => $webPath . 'main.ts',
|
||||
'appVueImport' => $webPath . 'App.vue',
|
||||
'appVueOnMounted' => $webPath . 'App.vue',
|
||||
'nuxtAppVueImport' => $webNuxtPath . 'app.vue',
|
||||
'nuxtAppVueStart' => $webNuxtPath . 'app.vue',
|
||||
];
|
||||
|
||||
$marks = [
|
||||
'mainTsImport' => self::buildMarkStr('import-root-mark'),
|
||||
'mainTsStart' => self::buildMarkStr('start-root-mark'),
|
||||
'appVueImport' => self::buildMarkStr('import-root-mark'),
|
||||
'appVueOnMounted' => self::buildMarkStr('onMounted-root-mark'),
|
||||
'nuxtAppVueImport' => self::buildMarkStr('import-root-mark'),
|
||||
'nuxtAppVueStart' => self::buildMarkStr('start-root-mark'),
|
||||
];
|
||||
|
||||
foreach ($bootstrapCode as $key => $item) {
|
||||
if ($item && isset($marks[$key]) && isset($filePaths[$key]) && is_file($filePaths[$key])) {
|
||||
$content = file_get_contents($filePaths[$key]);
|
||||
$markPos = stripos($content, $marks[$key]);
|
||||
if ($markPos && strripos($content, self::buildMarkStr('module-line-mark', $uid, $key)) === false && strripos($content, self::buildMarkStr('module-multi-line-mark-start', $uid, $key)) === false) {
|
||||
$content = substr_replace($content, $item, $markPos + strlen($marks[$key]), 0);
|
||||
file_put_contents($filePaths[$key], $content);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static function uninstallWebBootstrap(string $uid): void
|
||||
{
|
||||
$webPath = root_path() . 'web' . DIRECTORY_SEPARATOR . 'src' . DIRECTORY_SEPARATOR;
|
||||
$webNuxtPath = root_path() . 'web-nuxt' . DIRECTORY_SEPARATOR;
|
||||
$filePaths = [
|
||||
'mainTsImport' => $webPath . 'main.ts',
|
||||
'mainTsStart' => $webPath . 'main.ts',
|
||||
'appVueImport' => $webPath . 'App.vue',
|
||||
'appVueOnMounted' => $webPath . 'App.vue',
|
||||
'nuxtAppVueImport' => $webNuxtPath . 'app.vue',
|
||||
'nuxtAppVueStart' => $webNuxtPath . 'app.vue',
|
||||
];
|
||||
|
||||
$marksKey = [
|
||||
'mainTsImport',
|
||||
'mainTsStart',
|
||||
'appVueImport',
|
||||
'appVueOnMounted',
|
||||
'nuxtAppVueImport',
|
||||
'nuxtAppVueStart',
|
||||
];
|
||||
|
||||
foreach ($marksKey as $item) {
|
||||
if (!isset($filePaths[$item]) || !is_file($filePaths[$item])) {
|
||||
continue;
|
||||
}
|
||||
$content = file_get_contents($filePaths[$item]);
|
||||
$moduleLineMark = self::buildMarkStr('module-line-mark', $uid, $item);
|
||||
$moduleMultiLineMarkStart = self::buildMarkStr('module-multi-line-mark-start', $uid, $item);
|
||||
$moduleMultiLineMarkEnd = self::buildMarkStr('module-multi-line-mark-end', $uid, $item);
|
||||
|
||||
$moduleLineMarkPos = strripos($content, $moduleLineMark);
|
||||
if ($moduleLineMarkPos !== false) {
|
||||
$delStartTemp = explode($moduleLineMark, $content);
|
||||
$delStartPos = strripos(rtrim($delStartTemp[0], "\n"), "\n");
|
||||
$delEndPos = stripos($content, "\n", $moduleLineMarkPos);
|
||||
$content = substr_replace($content, '', $delStartPos, $delEndPos - $delStartPos);
|
||||
}
|
||||
|
||||
$moduleMultiLineMarkStartPos = stripos($content, $moduleMultiLineMarkStart);
|
||||
if ($moduleMultiLineMarkStartPos !== false) {
|
||||
$moduleMultiLineMarkStartPos--;
|
||||
$moduleMultiLineMarkEndPos = stripos($content, $moduleMultiLineMarkEnd);
|
||||
$delLang = ($moduleMultiLineMarkEndPos + strlen($moduleMultiLineMarkEnd)) - $moduleMultiLineMarkStartPos;
|
||||
$content = substr_replace($content, '', $moduleMultiLineMarkStartPos, $delLang);
|
||||
}
|
||||
|
||||
if (($moduleLineMarkPos ?? false) !== false || ($moduleMultiLineMarkStartPos ?? false) !== false) {
|
||||
file_put_contents($filePaths[$item], $content);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static function buildMarkStr(string $type, string $uid = '', string $extend = ''): string
|
||||
{
|
||||
$nonTabKeys = ['mti', 'avi', 'navi', 'navs'];
|
||||
$extend = match ($extend) {
|
||||
'mainTsImport' => 'mti',
|
||||
'mainTsStart' => 'mts',
|
||||
'appVueImport' => 'avi',
|
||||
'appVueOnMounted' => 'avo',
|
||||
'nuxtAppVueImport' => 'navi',
|
||||
'nuxtAppVueStart' => 'navs',
|
||||
default => '',
|
||||
};
|
||||
return match ($type) {
|
||||
'import-root-mark' => '// modules import mark, Please do not remove.',
|
||||
'start-root-mark' => '// modules start mark, Please do not remove.',
|
||||
'onMounted-root-mark' => '// Modules onMounted mark, Please do not remove.',
|
||||
'module-line-mark' => ' // Code from module \'' . $uid . "'" . ($extend ? "($extend)" : ''),
|
||||
'module-multi-line-mark-start' => (in_array($extend, $nonTabKeys) ? '' : Helper::tab()) . "// Code from module '$uid' start" . ($extend ? "($extend)" : '') . "\n",
|
||||
'module-multi-line-mark-end' => (in_array($extend, $nonTabKeys) ? '' : Helper::tab()) . "// Code from module '$uid' end",
|
||||
default => '',
|
||||
};
|
||||
}
|
||||
|
||||
public static function getNuxtVersion(): mixed
|
||||
{
|
||||
$nuxtPackageJsonPath = Filesystem::fsFit(root_path() . 'web-nuxt/package.json');
|
||||
if (is_file($nuxtPackageJsonPath)) {
|
||||
$nuxtPackageJson = file_get_contents($nuxtPackageJsonPath);
|
||||
$nuxtPackageJson = json_decode($nuxtPackageJson, true);
|
||||
if ($nuxtPackageJson && isset($nuxtPackageJson['version'])) {
|
||||
return $nuxtPackageJson['version'];
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public static function createRuntime(string $dir): void
|
||||
{
|
||||
$runtimeFilePath = $dir . '.runtime';
|
||||
$files = new RecursiveIteratorIterator(
|
||||
new RecursiveDirectoryIterator($dir), RecursiveIteratorIterator::LEAVES_ONLY
|
||||
);
|
||||
$filePaths = [];
|
||||
foreach ($files as $file) {
|
||||
if (!$file->isDir()) {
|
||||
$pathName = $file->getPathName();
|
||||
if ($pathName == $runtimeFilePath) continue;
|
||||
$filePaths[] = [
|
||||
'path' => Filesystem::fsFit($pathName),
|
||||
'size' => filesize($pathName),
|
||||
'md5' => md5_file($pathName),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
file_put_contents($runtimeFilePath, json_encode([
|
||||
'files' => $filePaths,
|
||||
'pure' => config('buildadmin.module_pure_install', false),
|
||||
]));
|
||||
}
|
||||
|
||||
public static function getRuntime(string $dir, string $key = ''): mixed
|
||||
{
|
||||
$runtimeFilePath = $dir . '.runtime';
|
||||
$runtimeContent = @file_get_contents($runtimeFilePath);
|
||||
$runtimeContentArr = json_decode($runtimeContent, true);
|
||||
if (!$runtimeContentArr) return [];
|
||||
|
||||
if ($key) {
|
||||
return $runtimeContentArr[$key] ?? [];
|
||||
}
|
||||
return $runtimeContentArr;
|
||||
}
|
||||
}
|
||||
@@ -1,774 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace app\api\controller;
|
||||
|
||||
use Throwable;
|
||||
use ba\Random;
|
||||
use ba\Version;
|
||||
use ba\Terminal;
|
||||
use ba\Filesystem;
|
||||
use app\common\controller\Api;
|
||||
use app\admin\model\Admin as AdminModel;
|
||||
use app\admin\model\User as UserModel;
|
||||
use support\Response;
|
||||
use Webman\Http\Request;
|
||||
use Phinx\Config\Config as PhinxConfig;
|
||||
use Phinx\Migration\Manager as PhinxManager;
|
||||
use Symfony\Component\Console\Input\ArrayInput;
|
||||
use Symfony\Component\Console\Output\NullOutput;
|
||||
|
||||
/**
|
||||
* 安装控制器
|
||||
*/
|
||||
class Install extends Api
|
||||
{
|
||||
public const X64 = 'x64';
|
||||
|
||||
public const X86 = 'x86';
|
||||
|
||||
protected bool $useSystemSettings = false;
|
||||
|
||||
/**
|
||||
* 环境检查状态
|
||||
*/
|
||||
static string $ok = 'ok';
|
||||
static string $fail = 'fail';
|
||||
static string $warn = 'warn';
|
||||
|
||||
/**
|
||||
* 安装锁文件名称
|
||||
*/
|
||||
static string $lockFileName = 'install.lock';
|
||||
|
||||
/**
|
||||
* 配置文件
|
||||
*/
|
||||
static string $dbConfigFileName = 'thinkorm.php';
|
||||
static string $buildConfigFileName = 'buildadmin.php';
|
||||
|
||||
/**
|
||||
* 自动构建的前端文件的 outDir 相对于根目录
|
||||
*/
|
||||
static string $distDir = 'web' . DIRECTORY_SEPARATOR . 'dist';
|
||||
|
||||
/**
|
||||
* 需要的依赖版本
|
||||
*/
|
||||
static array $needDependentVersion = [
|
||||
'php' => '8.2.0',
|
||||
'npm' => '9.8.1',
|
||||
'cnpm' => '7.1.0',
|
||||
'node' => '20.14.0',
|
||||
'yarn' => '1.2.0',
|
||||
'pnpm' => '6.32.13',
|
||||
];
|
||||
|
||||
/**
|
||||
* 安装完成标记
|
||||
*/
|
||||
static string $InstallationCompletionMark = 'install-end';
|
||||
|
||||
/**
|
||||
* 命令执行窗口(exec 为 SSE 长连接,不会返回)
|
||||
* @throws Throwable
|
||||
*/
|
||||
public function terminal(Request $request): Response
|
||||
{
|
||||
$this->setRequest($request);
|
||||
if ($this->isInstallComplete()) {
|
||||
return $this->error(__('The system has completed installation. If you need to reinstall, please delete the %file% file first', ['%file%' => 'public/' . self::$lockFileName]));
|
||||
}
|
||||
|
||||
(new Terminal())->exec(false);
|
||||
return $this->success(); // unreachable: exec() blocks with SSE stream
|
||||
}
|
||||
|
||||
public function changePackageManager(Request $request): Response
|
||||
{
|
||||
$this->setRequest($request);
|
||||
if ($this->isInstallComplete()) {
|
||||
return $this->error(__('The system has completed installation. If you need to reinstall, please delete the %file% file first', ['%file%' => 'public/' . self::$lockFileName]));
|
||||
}
|
||||
|
||||
$newPackageManager = $request->post('manager', config('terminal.npm_package_manager'));
|
||||
if (Terminal::changeTerminalConfig()) {
|
||||
return $this->success('', [
|
||||
'manager' => $newPackageManager
|
||||
]);
|
||||
}
|
||||
return $this->error(__('Failed to switch package manager. Please modify the configuration file manually:%s', ['config/terminal.php']));
|
||||
}
|
||||
|
||||
/**
|
||||
* 环境基础检查
|
||||
*/
|
||||
public function envBaseCheck(Request $request): Response
|
||||
{
|
||||
$this->setRequest($request);
|
||||
if ($this->isInstallComplete()) {
|
||||
return $this->error(__('The system has completed installation. If you need to reinstall, please delete the %file% file first', ['%file%' => 'public/' . self::$lockFileName]), []);
|
||||
}
|
||||
if (($_ENV['DATABASE_TYPE'] ?? getenv('DATABASE_TYPE'))) {
|
||||
return $this->error(__('The .env file with database configuration was detected. Please clean up and try again!'));
|
||||
}
|
||||
|
||||
// php版本-start
|
||||
$phpVersion = phpversion();
|
||||
$phpBit = PHP_INT_SIZE == 8 ? self::X64 : self::X86;
|
||||
$phpVersionCompare = Version::compare(self::$needDependentVersion['php'], $phpVersion);
|
||||
if (!$phpVersionCompare) {
|
||||
$phpVersionLink = [
|
||||
[
|
||||
'name' => __('need') . ' >= ' . self::$needDependentVersion['php'],
|
||||
'type' => 'text'
|
||||
],
|
||||
[
|
||||
'name' => __('How to solve?'),
|
||||
'title' => __('Click to see how to solve it'),
|
||||
'type' => 'faq',
|
||||
'url' => 'https://doc.buildadmin.com/guide/install/preparePHP.html'
|
||||
]
|
||||
];
|
||||
} elseif ($phpBit != self::X64) {
|
||||
$phpVersionLink = [
|
||||
[
|
||||
'name' => __('need') . ' x64 PHP',
|
||||
'type' => 'text'
|
||||
],
|
||||
[
|
||||
'name' => __('How to solve?'),
|
||||
'title' => __('Click to see how to solve it'),
|
||||
'type' => 'faq',
|
||||
'url' => 'https://doc.buildadmin.com/guide/install/preparePHP.html'
|
||||
]
|
||||
];
|
||||
}
|
||||
// php版本-end
|
||||
|
||||
// 配置文件-start(分别检测目录和文件,便于定位问题)
|
||||
$configDir = rtrim(config_path(), '/\\');
|
||||
$dbConfigFile = $configDir . DIRECTORY_SEPARATOR . self::$dbConfigFileName;
|
||||
$configDirWritable = Filesystem::pathIsWritable($configDir);
|
||||
$dbConfigWritable = Filesystem::pathIsWritable($dbConfigFile);
|
||||
$configIsWritable = $configDirWritable && $dbConfigWritable;
|
||||
if (!$configIsWritable) {
|
||||
$configIsWritableLink = [
|
||||
[
|
||||
'name' => __('View reason'),
|
||||
'title' => __('Click to view the reason'),
|
||||
'type' => 'faq',
|
||||
'url' => 'https://doc.buildadmin.com/guide/install/dirNoPermission.html'
|
||||
]
|
||||
];
|
||||
}
|
||||
// 配置文件-end
|
||||
|
||||
// public-start
|
||||
$publicIsWritable = Filesystem::pathIsWritable(public_path());
|
||||
if (!$publicIsWritable) {
|
||||
$publicIsWritableLink = [
|
||||
[
|
||||
'name' => __('View reason'),
|
||||
'title' => __('Click to view the reason'),
|
||||
'type' => 'faq',
|
||||
'url' => 'https://doc.buildadmin.com/guide/install/dirNoPermission.html'
|
||||
]
|
||||
];
|
||||
}
|
||||
// public-end
|
||||
|
||||
// PDO-start
|
||||
$phpPdo = extension_loaded("PDO") && extension_loaded('pdo_mysql');
|
||||
if (!$phpPdo) {
|
||||
$phpPdoLink = [
|
||||
[
|
||||
'name' => __('PDO extensions need to be installed'),
|
||||
'type' => 'text'
|
||||
],
|
||||
[
|
||||
'name' => __('How to solve?'),
|
||||
'title' => __('Click to see how to solve it'),
|
||||
'type' => 'faq',
|
||||
'url' => 'https://doc.buildadmin.com/guide/install/missingExtension.html'
|
||||
]
|
||||
];
|
||||
}
|
||||
// PDO-end
|
||||
|
||||
// GD2和freeType-start
|
||||
$phpGd2 = extension_loaded('gd') && function_exists('imagettftext');
|
||||
if (!$phpGd2) {
|
||||
$phpGd2Link = [
|
||||
[
|
||||
'name' => __('The gd extension and freeType library need to be installed'),
|
||||
'type' => 'text'
|
||||
],
|
||||
[
|
||||
'name' => __('How to solve?'),
|
||||
'title' => __('Click to see how to solve it'),
|
||||
'type' => 'faq',
|
||||
'url' => 'https://doc.buildadmin.com/guide/install/gdFail.html'
|
||||
]
|
||||
];
|
||||
}
|
||||
// GD2和freeType-end
|
||||
|
||||
// proc_open
|
||||
$phpProc = function_exists('proc_open') && function_exists('proc_close') && function_exists('proc_get_status');
|
||||
if (!$phpProc) {
|
||||
$phpProcLink = [
|
||||
[
|
||||
'name' => __('View reason'),
|
||||
'title' => __('proc_open or proc_close functions in PHP Ini is disabled'),
|
||||
'type' => 'faq',
|
||||
'url' => 'https://doc.buildadmin.com/guide/install/disablement.html'
|
||||
],
|
||||
[
|
||||
'name' => __('How to modify'),
|
||||
'title' => __('Click to view how to modify'),
|
||||
'type' => 'faq',
|
||||
'url' => 'https://doc.buildadmin.com/guide/install/disablement.html'
|
||||
],
|
||||
[
|
||||
'name' => __('Security assurance?'),
|
||||
'title' => __('Using the installation service correctly will not cause any potential security problems. Click to view the details'),
|
||||
'type' => 'faq',
|
||||
'url' => 'https://doc.buildadmin.com/guide/install/senior.html'
|
||||
],
|
||||
];
|
||||
}
|
||||
// proc_open-end
|
||||
|
||||
return $this->success('', [
|
||||
'php_version' => [
|
||||
'describe' => $phpVersion . " ($phpBit)",
|
||||
'state' => $phpVersionCompare && $phpBit == self::X64 ? self::$ok : self::$fail,
|
||||
'link' => $phpVersionLink ?? [],
|
||||
],
|
||||
'config_is_writable' => [
|
||||
'describe' => $configIsWritable
|
||||
? self::writableStateDescribe(true)
|
||||
: (self::writableStateDescribe(false) . ' [' . $configDir . ']'),
|
||||
'state' => $configIsWritable ? self::$ok : self::$fail,
|
||||
'link' => $configIsWritableLink ?? []
|
||||
],
|
||||
'public_is_writable' => [
|
||||
'describe' => self::writableStateDescribe($publicIsWritable),
|
||||
'state' => $publicIsWritable ? self::$ok : self::$fail,
|
||||
'link' => $publicIsWritableLink ?? []
|
||||
],
|
||||
'php_pdo' => [
|
||||
'describe' => $phpPdo ? __('already installed') : __('Not installed'),
|
||||
'state' => $phpPdo ? self::$ok : self::$fail,
|
||||
'link' => $phpPdoLink ?? []
|
||||
],
|
||||
'php_gd2' => [
|
||||
'describe' => $phpGd2 ? __('already installed') : __('Not installed'),
|
||||
'state' => $phpGd2 ? self::$ok : self::$fail,
|
||||
'link' => $phpGd2Link ?? []
|
||||
],
|
||||
'php_proc' => [
|
||||
'describe' => $phpProc ? __('Allow execution') : __('disabled'),
|
||||
'state' => $phpProc ? self::$ok : self::$warn,
|
||||
'link' => $phpProcLink ?? []
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* npm环境检查
|
||||
*/
|
||||
public function envNpmCheck(Request $request): Response
|
||||
{
|
||||
$this->setRequest($request);
|
||||
if ($this->isInstallComplete()) {
|
||||
return $this->error('', [], 2);
|
||||
}
|
||||
|
||||
$packageManager = $request->post('manager', 'none');
|
||||
|
||||
// npm
|
||||
$npmVersion = Version::getVersion('npm');
|
||||
$npmVersionCompare = Version::compare(self::$needDependentVersion['npm'], $npmVersion);
|
||||
if (!$npmVersionCompare || !$npmVersion) {
|
||||
$npmVersionLink = [
|
||||
[
|
||||
'name' => __('need') . ' >= ' . self::$needDependentVersion['npm'],
|
||||
'type' => 'text'
|
||||
],
|
||||
[
|
||||
'name' => __('How to solve?'),
|
||||
'title' => __('Click to see how to solve it'),
|
||||
'type' => 'faq',
|
||||
'url' => 'https://doc.buildadmin.com/guide/install/prepareNpm.html'
|
||||
]
|
||||
];
|
||||
}
|
||||
|
||||
// 包管理器
|
||||
$pmVersionLink = [];
|
||||
$pmVersion = __('nothing');
|
||||
$pmVersionCompare = false;
|
||||
if (in_array($packageManager, ['npm', 'cnpm', 'pnpm', 'yarn'])) {
|
||||
$pmVersion = Version::getVersion($packageManager);
|
||||
$pmVersionCompare = Version::compare(self::$needDependentVersion[$packageManager], $pmVersion);
|
||||
|
||||
if (!$pmVersion) {
|
||||
$pmVersionLink[] = [
|
||||
'name' => __('need') . ' >= ' . self::$needDependentVersion[$packageManager],
|
||||
'type' => 'text'
|
||||
];
|
||||
if ($npmVersionCompare) {
|
||||
$pmVersionLink[] = [
|
||||
'name' => __('Click Install %s', [$packageManager]),
|
||||
'title' => '',
|
||||
'type' => 'install-package-manager'
|
||||
];
|
||||
} else {
|
||||
$pmVersionLink[] = [
|
||||
'name' => __('Please install NPM first'),
|
||||
'type' => 'text'
|
||||
];
|
||||
}
|
||||
} elseif (!$pmVersionCompare) {
|
||||
$pmVersionLink[] = [
|
||||
'name' => __('need') . ' >= ' . self::$needDependentVersion[$packageManager],
|
||||
'type' => 'text'
|
||||
];
|
||||
$pmVersionLink[] = [
|
||||
'name' => __('Please upgrade %s version', [$packageManager]),
|
||||
'type' => 'text'
|
||||
];
|
||||
}
|
||||
} elseif ($packageManager == 'ni') {
|
||||
$pmVersionCompare = true;
|
||||
}
|
||||
|
||||
// nodejs
|
||||
$nodejsVersion = Version::getVersion('node');
|
||||
$nodejsVersionCompare = Version::compare(self::$needDependentVersion['node'], $nodejsVersion);
|
||||
if (!$nodejsVersionCompare || !$nodejsVersion) {
|
||||
$nodejsVersionLink = [
|
||||
[
|
||||
'name' => __('need') . ' >= ' . self::$needDependentVersion['node'],
|
||||
'type' => 'text'
|
||||
],
|
||||
[
|
||||
'name' => __('How to solve?'),
|
||||
'title' => __('Click to see how to solve it'),
|
||||
'type' => 'faq',
|
||||
'url' => 'https://doc.buildadmin.com/guide/install/prepareNodeJs.html'
|
||||
]
|
||||
];
|
||||
}
|
||||
|
||||
return $this->success('', [
|
||||
'npm_version' => [
|
||||
'describe' => $npmVersion ?: __('Acquisition failed'),
|
||||
'state' => $npmVersionCompare ? self::$ok : self::$warn,
|
||||
'link' => $npmVersionLink ?? [],
|
||||
],
|
||||
'nodejs_version' => [
|
||||
'describe' => $nodejsVersion ?: __('Acquisition failed'),
|
||||
'state' => $nodejsVersionCompare ? self::$ok : self::$warn,
|
||||
'link' => $nodejsVersionLink ?? []
|
||||
],
|
||||
'npm_package_manager' => [
|
||||
'describe' => $pmVersion ?: __('Acquisition failed'),
|
||||
'state' => $pmVersionCompare ? self::$ok : self::$warn,
|
||||
'link' => $pmVersionLink ?? [],
|
||||
]
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 测试数据库连接
|
||||
*/
|
||||
public function testDatabase(Request $request): Response
|
||||
{
|
||||
$this->setRequest($request);
|
||||
if ($this->isInstallComplete()) {
|
||||
return $this->error(__('The system has completed installation. If you need to reinstall, please delete the %file% file first', ['%file%' => 'public/' . self::$lockFileName]));
|
||||
}
|
||||
$database = [
|
||||
'hostname' => $request->post('hostname'),
|
||||
'username' => $request->post('username'),
|
||||
'password' => $request->post('password'),
|
||||
'hostport' => $request->post('hostport'),
|
||||
'database' => '',
|
||||
];
|
||||
|
||||
$conn = $this->connectDb($database);
|
||||
if ($conn['code'] == 0) {
|
||||
return $this->error($conn['msg']);
|
||||
}
|
||||
return $this->success('', [
|
||||
'databases' => $conn['databases']
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 系统基础配置
|
||||
* post请求=开始安装
|
||||
*/
|
||||
public function baseConfig(Request $request): Response
|
||||
{
|
||||
$this->setRequest($request);
|
||||
if ($this->isInstallComplete()) {
|
||||
return $this->error(__('The system has completed installation. If you need to reinstall, please delete the %file% file first', ['%file%' => 'public/' . self::$lockFileName]));
|
||||
}
|
||||
|
||||
$envOk = $this->commandExecutionCheck();
|
||||
$rootPath = str_replace('\\', '/', root_path());
|
||||
$migrateCommand = 'php vendor/bin/phinx migrate';
|
||||
if ($request->isGet()) {
|
||||
return $this->success('', [
|
||||
'rootPath' => $rootPath,
|
||||
'executionWebCommand' => $envOk,
|
||||
'migrateCommand' => $migrateCommand,
|
||||
]);
|
||||
}
|
||||
|
||||
$connectData = $databaseParam = $request->only(['hostname', 'username', 'password', 'hostport', 'database', 'prefix']);
|
||||
|
||||
// 数据库配置测试
|
||||
$connectData['database'] = '';
|
||||
$connect = $this->connectDb($connectData, true);
|
||||
if ($connect['code'] == 0) {
|
||||
return $this->error($connect['msg']);
|
||||
}
|
||||
|
||||
// 建立数据库
|
||||
if (!in_array($databaseParam['database'], $connect['databases'])) {
|
||||
$sql = "CREATE DATABASE IF NOT EXISTS `{$databaseParam['database']}` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci";
|
||||
$connect['pdo']->exec($sql);
|
||||
}
|
||||
|
||||
// 写入数据库配置文件(thinkorm.php 使用 $env('database.xxx', 'default') 格式)
|
||||
$dbConfigFile = config_path(self::$dbConfigFileName);
|
||||
$dbConfigContent = @file_get_contents($dbConfigFile);
|
||||
if ($dbConfigContent === false || $dbConfigContent === '') {
|
||||
return $this->error(__('File has no write permission:%s', ['config/' . self::$dbConfigFileName]));
|
||||
}
|
||||
$callback = function ($matches) use ($databaseParam) {
|
||||
$key = $matches[1];
|
||||
$value = (string) ($databaseParam[$key] ?? '');
|
||||
return "\$env('database.{$key}', '" . addslashes($value) . "')";
|
||||
};
|
||||
$dbConfigText = preg_replace_callback("/\\\$env\('database\.(hostname|database|username|password|hostport|prefix)',\s*'[^']*'\)/", $callback, $dbConfigContent);
|
||||
$result = @file_put_contents($dbConfigFile, $dbConfigText);
|
||||
if (!$result) {
|
||||
return $this->error(__('File has no write permission:%s', ['config/' . self::$dbConfigFileName]));
|
||||
}
|
||||
|
||||
// 写入 .env 和 .env-example(仅使用 Dotenv 可解析的 DATABASE_XXX 格式,避免 [DATABASE] 导致解析失败)
|
||||
$databaseBlock = "\n# Database\n"
|
||||
. 'DATABASE_TYPE = mysql' . "\n"
|
||||
. 'DATABASE_HOSTNAME = ' . $databaseParam['hostname'] . "\n"
|
||||
. 'DATABASE_DATABASE = ' . $databaseParam['database'] . "\n"
|
||||
. 'DATABASE_USERNAME = ' . $databaseParam['username'] . "\n"
|
||||
. 'DATABASE_PASSWORD = ' . $databaseParam['password'] . "\n"
|
||||
. 'DATABASE_HOSTPORT = ' . $databaseParam['hostport'] . "\n"
|
||||
. 'DATABASE_CHARSET = utf8mb4' . "\n"
|
||||
. 'DATABASE_PREFIX = ' . ($databaseParam['prefix'] ?? '') . "\n";
|
||||
foreach (['.env', '.env-example'] as $envName) {
|
||||
$envFile = root_path() . $envName;
|
||||
$envFileContent = is_file($envFile) ? @file_get_contents($envFile) : '';
|
||||
if ($envFileContent !== false) {
|
||||
$cutPos = strlen($envFileContent);
|
||||
foreach (['[DATABASE]', "\n# Database\n", "\n# 数据库", "\nDATABASE_DRIVER", "\nDATABASE_TYPE"] as $marker) {
|
||||
$pos = stripos($envFileContent, $marker);
|
||||
if ($pos !== false && $pos < $cutPos) {
|
||||
$cutPos = $pos;
|
||||
}
|
||||
}
|
||||
$envFileContent = rtrim(substr($envFileContent, 0, $cutPos)) . $databaseBlock;
|
||||
$result = @file_put_contents($envFile, $envFileContent);
|
||||
if (!$result && is_file($envFile)) {
|
||||
return $this->error(__('File has no write permission:%s', ['%s' => $envName]));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 设置新的Token随机密钥key
|
||||
$oldTokenKey = config('buildadmin.token.key');
|
||||
$newTokenKey = Random::build('alnum', 32);
|
||||
$buildConfigFile = config_path(self::$buildConfigFileName);
|
||||
$buildConfigContent = @file_get_contents($buildConfigFile);
|
||||
if ($buildConfigContent === false || $buildConfigContent === '') {
|
||||
return $this->error(__('File has no write permission:%s', ['config/' . self::$buildConfigFileName]));
|
||||
}
|
||||
$buildConfigContent = preg_replace("/'key'(\s+)=>(\s+)'$oldTokenKey'/", "'key'\$1=>\$2'$newTokenKey'", $buildConfigContent);
|
||||
$result = @file_put_contents($buildConfigFile, $buildConfigContent);
|
||||
if (!$result) {
|
||||
return $this->error(__('File has no write permission:%s', ['config/' . self::$buildConfigFileName]));
|
||||
}
|
||||
|
||||
// 建立安装锁文件
|
||||
$result = @file_put_contents(public_path(self::$lockFileName), date('Y-m-d H:i:s'));
|
||||
if (!$result) {
|
||||
return $this->error(__('File has no write permission:%s', ['public/' . self::$lockFileName]));
|
||||
}
|
||||
|
||||
// 自动执行数据库迁移(无需手动运行 phinx 命令)
|
||||
$migrateResult = $this->runPhinxMigrate($databaseParam);
|
||||
if ($migrateResult !== true) {
|
||||
return $this->error($migrateResult);
|
||||
}
|
||||
|
||||
return $this->success('', [
|
||||
'rootPath' => $rootPath,
|
||||
'executionWebCommand' => $envOk,
|
||||
'migrateCommand' => $migrateCommand,
|
||||
'migrationCompleted' => true,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 程序化执行 Phinx 数据库迁移
|
||||
* @param array $databaseParam 数据库连接参数
|
||||
* @return true|string 成功返回 true,失败返回错误信息
|
||||
*/
|
||||
private function runPhinxMigrate(array $databaseParam): true|string
|
||||
{
|
||||
try {
|
||||
$baseDir = root_path();
|
||||
$phinxConfigPath = $baseDir . 'phinx.php';
|
||||
|
||||
if (!is_file($phinxConfigPath)) {
|
||||
return __('Failed to install SQL execution:%msg%', ['%msg%' => 'phinx.php not found']);
|
||||
}
|
||||
|
||||
// 临时设置环境变量,供 phinx 读取数据库配置
|
||||
$_ENV['DATABASE_HOSTNAME'] = $databaseParam['hostname'] ?? '127.0.0.1';
|
||||
$_ENV['DATABASE_DATABASE'] = $databaseParam['database'] ?? '';
|
||||
$_ENV['DATABASE_USERNAME'] = $databaseParam['username'] ?? 'root';
|
||||
$_ENV['DATABASE_PASSWORD'] = $databaseParam['password'] ?? '';
|
||||
$_ENV['DATABASE_HOSTPORT'] = $databaseParam['hostport'] ?? '3306';
|
||||
$_ENV['DATABASE_PREFIX'] = $databaseParam['prefix'] ?? '';
|
||||
putenv('DATABASE_HOSTNAME=' . $_ENV['DATABASE_HOSTNAME']);
|
||||
putenv('DATABASE_DATABASE=' . $_ENV['DATABASE_DATABASE']);
|
||||
putenv('DATABASE_USERNAME=' . $_ENV['DATABASE_USERNAME']);
|
||||
putenv('DATABASE_PASSWORD=' . $_ENV['DATABASE_PASSWORD']);
|
||||
putenv('DATABASE_HOSTPORT=' . $_ENV['DATABASE_HOSTPORT']);
|
||||
putenv('DATABASE_PREFIX=' . $_ENV['DATABASE_PREFIX']);
|
||||
|
||||
$config = PhinxConfig::fromPhp($phinxConfigPath);
|
||||
$input = new ArrayInput([]);
|
||||
$output = new NullOutput();
|
||||
$manager = new PhinxManager($config, $input, $output);
|
||||
|
||||
$environment = $config->getDefaultEnvironment();
|
||||
$manager->migrate($environment);
|
||||
return true;
|
||||
} catch (Throwable $e) {
|
||||
$msg = $e->getMessage();
|
||||
if ($e->getPrevious()) {
|
||||
$msg .= ' | ' . $e->getPrevious()->getMessage();
|
||||
}
|
||||
return __('Failed to install SQL execution:%msg%', ['%msg%' => $msg]);
|
||||
}
|
||||
}
|
||||
|
||||
protected function isInstallComplete(): bool
|
||||
{
|
||||
return is_system_installed();
|
||||
}
|
||||
|
||||
/**
|
||||
* 标记命令执行完毕
|
||||
* @throws Throwable
|
||||
*/
|
||||
public function commandExecComplete(Request $request): Response
|
||||
{
|
||||
$this->setRequest($request);
|
||||
if ($this->isInstallComplete()) {
|
||||
return $this->error(__('The system has completed installation. If you need to reinstall, please delete the %file% file first', ['%file%' => 'public/' . self::$lockFileName]));
|
||||
}
|
||||
|
||||
$param = $request->only(['type', 'adminname', 'adminpassword', 'sitename']);
|
||||
if ($param['type'] == 'web') {
|
||||
$result = @file_put_contents(public_path(self::$lockFileName), self::$InstallationCompletionMark);
|
||||
if (!$result) {
|
||||
return $this->error(__('File has no write permission:%s', ['public/' . self::$lockFileName]));
|
||||
}
|
||||
} else {
|
||||
// 管理员配置入库
|
||||
$adminModel = new AdminModel();
|
||||
$defaultAdmin = $adminModel->where('username', 'admin')->find();
|
||||
$defaultAdmin->username = $param['adminname'];
|
||||
$defaultAdmin->nickname = ucfirst($param['adminname']);
|
||||
$defaultAdmin->save();
|
||||
|
||||
if (isset($param['adminpassword']) && $param['adminpassword']) {
|
||||
$adminModel->resetPassword($defaultAdmin->id, $param['adminpassword']);
|
||||
}
|
||||
|
||||
// 默认用户密码修改
|
||||
$user = new UserModel();
|
||||
$user->resetPassword(1, Random::build());
|
||||
|
||||
// 修改站点名称
|
||||
if (class_exists(\app\admin\model\Config::class)) {
|
||||
\app\admin\model\Config::where('name', 'site_name')->update([
|
||||
'value' => $param['sitename']
|
||||
]);
|
||||
}
|
||||
}
|
||||
return $this->success();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取命令执行检查的结果
|
||||
* @return bool 是否拥有执行命令的条件
|
||||
*/
|
||||
private function commandExecutionCheck(): bool
|
||||
{
|
||||
$pm = config('terminal.npm_package_manager');
|
||||
if ($pm == 'none') {
|
||||
return false;
|
||||
}
|
||||
$check['phpPopen'] = function_exists('proc_open') && function_exists('proc_close');
|
||||
$check['npmVersionCompare'] = Version::compare(self::$needDependentVersion['npm'], Version::getVersion('npm'));
|
||||
$check['pmVersionCompare'] = Version::compare(self::$needDependentVersion[$pm], Version::getVersion($pm));
|
||||
$check['nodejsVersionCompare'] = Version::compare(self::$needDependentVersion['node'], Version::getVersion('node'));
|
||||
|
||||
$envOk = true;
|
||||
foreach ($check as $value) {
|
||||
if (!$value) {
|
||||
$envOk = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return $envOk;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取安装完成后的访问地址(根据请求来源区分 API 与前端开发模式)
|
||||
* - 通过 API 访问(8787):index.html#/admin、index.html#/
|
||||
* - 通过前端开发服务访问(1818):/#/admin、/#/
|
||||
*/
|
||||
public function accessUrls(Request $request): Response
|
||||
{
|
||||
$this->setRequest($request);
|
||||
if ($this->isInstallComplete()) {
|
||||
return $this->error(__('The system has completed installation. If you need to reinstall, please delete the %file% file first', ['%file%' => 'public/' . self::$lockFileName]));
|
||||
}
|
||||
$host = $request->header('host', '127.0.0.1:8787');
|
||||
$port = '8787';
|
||||
if (str_contains($host, ':')) {
|
||||
$port = substr($host, strrpos($host, ':') + 1);
|
||||
}
|
||||
$scheme = $request->header('x-forwarded-proto', 'http');
|
||||
$base = rtrim($scheme . '://' . $host, '/');
|
||||
|
||||
if ($port === '1818') {
|
||||
$adminUrl = $base . '/#/admin';
|
||||
$frontUrl = $base . '/#/';
|
||||
} else {
|
||||
$adminUrl = $base . '/index.html#/admin';
|
||||
$frontUrl = $base . '/index.html#/';
|
||||
}
|
||||
|
||||
return $this->success('', [
|
||||
'adminUrl' => $adminUrl,
|
||||
'frontUrl' => $frontUrl,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 安装指引
|
||||
*/
|
||||
public function manualInstall(Request $request): Response
|
||||
{
|
||||
$this->setRequest($request);
|
||||
if ($this->isInstallComplete()) {
|
||||
return $this->error(__('The system has completed installation. If you need to reinstall, please delete the %file% file first', ['%file%' => 'public/' . self::$lockFileName]));
|
||||
}
|
||||
return $this->success('', [
|
||||
'webPath' => str_replace('\\', '/', root_path() . 'web')
|
||||
]);
|
||||
}
|
||||
|
||||
public function mvDist(Request $request): Response
|
||||
{
|
||||
$this->setRequest($request);
|
||||
if ($this->isInstallComplete()) {
|
||||
return $this->error(__('The system has completed installation. If you need to reinstall, please delete the %file% file first', ['%file%' => 'public/' . self::$lockFileName]));
|
||||
}
|
||||
if (!is_file(root_path() . self::$distDir . DIRECTORY_SEPARATOR . 'index.html')) {
|
||||
return $this->error(__('No built front-end file found, please rebuild manually!'));
|
||||
}
|
||||
|
||||
if (Terminal::mvDist()) {
|
||||
return $this->success();
|
||||
}
|
||||
return $this->error(__('Failed to move the front-end file, please move it manually!'));
|
||||
}
|
||||
|
||||
/**
|
||||
* 目录是否可写
|
||||
* @param $writable
|
||||
* @return string
|
||||
*/
|
||||
private static function writableStateDescribe($writable): string
|
||||
{
|
||||
return $writable ? __('Writable') : __('No write permission');
|
||||
}
|
||||
|
||||
/**
|
||||
* 数据库连接-获取数据表列表(使用 raw PDO)
|
||||
* @param array $database hostname, hostport, username, password, database
|
||||
* @param bool $returnPdo
|
||||
* @return array
|
||||
*/
|
||||
private function connectDb(array $database, bool $returnPdo = false): array
|
||||
{
|
||||
$host = $database['hostname'] ?? '127.0.0.1';
|
||||
$port = $database['hostport'] ?? '3306';
|
||||
$user = $database['username'] ?? '';
|
||||
$pass = $database['password'] ?? '';
|
||||
$db = $database['database'] ?? '';
|
||||
|
||||
$dsn = "mysql:host={$host};port={$port};charset=utf8mb4";
|
||||
if ($db) {
|
||||
$dsn .= ";dbname={$db}";
|
||||
}
|
||||
|
||||
try {
|
||||
$pdo = new \PDO($dsn, $user, $pass, [
|
||||
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
|
||||
\PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true,
|
||||
]);
|
||||
$pdo->query("SELECT 1")->fetchAll(\PDO::FETCH_ASSOC);
|
||||
} catch (\PDOException $e) {
|
||||
$errorMsg = mb_convert_encoding($e->getMessage() ?: 'unknown', 'UTF-8', 'UTF-8,GBK,GB2312,BIG5');
|
||||
$template = __('Database connection failed:%s');
|
||||
return [
|
||||
'code' => 0,
|
||||
'msg' => strpos($template, '%s') !== false ? sprintf($template, $errorMsg) : $template . $errorMsg,
|
||||
];
|
||||
}
|
||||
|
||||
$databases = [];
|
||||
$databasesExclude = ['information_schema', 'mysql', 'performance_schema', 'sys'];
|
||||
$stmt = $pdo->query("SHOW DATABASES");
|
||||
$rows = $stmt->fetchAll(\PDO::FETCH_ASSOC);
|
||||
$stmt->closeCursor();
|
||||
foreach ($rows as $row) {
|
||||
$dbName = $row['Database'] ?? $row['database'] ?? '';
|
||||
if ($dbName && !in_array($dbName, $databasesExclude)) {
|
||||
$databases[] = $dbName;
|
||||
}
|
||||
}
|
||||
|
||||
return [
|
||||
'code' => 1,
|
||||
'msg' => '',
|
||||
'databases' => $databases,
|
||||
'pdo' => $returnPdo ? $pdo : null,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
<?php
|
||||
return [
|
||||
'Install the controller' => 'Install the controller',
|
||||
'need' => 'Need',
|
||||
'Click to see how to solve it' => 'Click to see how to solve.',
|
||||
'Please check the config directory permissions' => 'Please check the Config directory permissions',
|
||||
'Please check the public directory permissions' => 'Please check the Public directory permissions',
|
||||
'open' => 'Open',
|
||||
'close' => 'Close',
|
||||
'The installation can continue, and some operations need to be completed manually' => 'You can continue to install, and some operations need to be completed manually ',
|
||||
'Allow execution' => 'Allow execution',
|
||||
'disabled' => 'Disabled',
|
||||
'Allow operation' => 'Allow operation',
|
||||
'Acquisition failed' => 'Access failed',
|
||||
'Click Install %s' => 'Click Install %s',
|
||||
'Writable' => 'Writable',
|
||||
'No write permission' => 'No write permissions',
|
||||
'already installed' => 'Installed',
|
||||
'Not installed' => 'Not installed',
|
||||
'File has no write permission:%s' => 'File has no write permission:%s',
|
||||
'The system has completed installation. If you need to reinstall, please delete the %file% file first' => 'The system has been installed. If you need to reinstall, please delete the %file% file first.',
|
||||
'Database connection failed:%s' => 'Database connection failure:%s',
|
||||
'Failed to install SQL execution:%msg%' => 'Installation SQL execution failed: %msg%',
|
||||
'unknown' => 'Unknown',
|
||||
'Database does not exist' => 'Database does not exist!',
|
||||
'No built front-end file found, please rebuild manually!' => 'No built front-end file found, please rebuild manually.',
|
||||
'Failed to move the front-end file, please move it manually!' => 'Failed to move the front-end file, please move manually!',
|
||||
'How to solve?' => 'How to solve?',
|
||||
'View reason' => 'View reasons',
|
||||
'Click to view the reason' => 'Click to see the reason',
|
||||
'PDO extensions need to be installed' => 'pdo_mysql extensions need to be installed.',
|
||||
'proc_open or proc_close functions in PHP Ini is disabled' => 'proc_open and proc_close functions in PHP.Ini is disabled.',
|
||||
'How to modify' => 'How to modify?',
|
||||
'Click to view how to modify' => 'Click to see how to modify.',
|
||||
'Security assurance?' => 'Security assurance?',
|
||||
'Using the installation service correctly will not cause any potential security problems. Click to view the details' => 'The correct use of the installation service will not cause any potential security issues. Click to view the details.',
|
||||
'Please install NPM first' => 'Please install NPM first.',
|
||||
'Installation error:%s' => 'Installation error:%s',
|
||||
'Failed to switch package manager. Please modify the configuration file manually:%s' => 'Package manager switch failed, please modify the configuration file manually:%s.',
|
||||
'Please upgrade %s version' => 'Please upgrade the %s version',
|
||||
'nothing' => 'Nothing',
|
||||
'The gd extension and freeType library need to be installed' => 'The gd2 extension and freeType library need to be installed',
|
||||
'The .env file with database configuration was detected. Please clean up and try again!' => 'The .env file with database configuration was detected. Please clean up and try again!',
|
||||
];
|
||||
@@ -1,44 +0,0 @@
|
||||
<?php
|
||||
return [
|
||||
'Install the controller' => '安装控制器',
|
||||
'need' => '需要',
|
||||
'Click to see how to solve it' => '点击查看如何解决',
|
||||
'Please check the config directory permissions' => '请检查 config 目录权限',
|
||||
'Please check the public directory permissions' => '请检查 public 目录权限',
|
||||
'open' => '开启',
|
||||
'close' => '关闭',
|
||||
'The installation can continue, and some operations need to be completed manually' => '可以继续安装,部分操作需手动完成',
|
||||
'Allow execution' => '允许执行',
|
||||
'disabled' => '已禁用',
|
||||
'Allow operation' => '允许操作',
|
||||
'Acquisition failed' => '获取失败',
|
||||
'Click Install %s' => '点击安装%s',
|
||||
'Writable' => '可写',
|
||||
'No write permission' => '无写权限',
|
||||
'already installed' => '已安装',
|
||||
'Not installed' => '未安装',
|
||||
'File has no write permission:%s' => '文件无写入权限:%s',
|
||||
'The system has completed installation. If you need to reinstall, please delete the %file% file first' => '系统已完成安装。如果需要重新安装,请先删除 %file% 文件',
|
||||
'Database connection failed:%s' => '数据库连接失败:%s',
|
||||
'Failed to install SQL execution:%msg%' => '安装SQL执行失败:%msg%',
|
||||
'unknown' => '未知',
|
||||
'Database does not exist' => '数据库不存在!',
|
||||
'No built front-end file found, please rebuild manually!' => '没有找到构建好的前端文件,请手动重新构建!',
|
||||
'Failed to move the front-end file, please move it manually!' => '移动前端文件失败,请手动移动!',
|
||||
'How to solve?' => '如何解决?',
|
||||
'View reason' => '查看原因',
|
||||
'Click to view the reason' => '点击查看原因',
|
||||
'PDO extensions need to be installed' => '需要安装 pdo_mysql 扩展',
|
||||
'proc_open or proc_close functions in PHP Ini is disabled' => 'proc_open和proc_close函数在php.ini中被禁用掉了',
|
||||
'How to modify' => '如何修改',
|
||||
'Click to view how to modify' => '点击查看如何修改',
|
||||
'Security assurance?' => '安全保证?',
|
||||
'Using the installation service correctly will not cause any potential security problems. Click to view the details' => '安装服务使用正确不会造成任何潜在安全问题,点击查看详情',
|
||||
'Please install NPM first' => '请先安装npm',
|
||||
'Installation error:%s' => '安装出错:%s',
|
||||
'Failed to switch package manager. Please modify the configuration file manually:%s' => '包管理器切换失败,请手动修改配置文件:%s',
|
||||
'Please upgrade %s version' => '请升级%s版本',
|
||||
'nothing' => '无',
|
||||
'The gd extension and freeType library need to be installed' => '需要gd2扩展和freeType库',
|
||||
'The .env file with database configuration was detected. Please clean up and try again!' => '检测到带有数据库配置的 .env 文件。请清理后再试一次!',
|
||||
];
|
||||
@@ -1,29 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace app\common\middleware;
|
||||
|
||||
use Webman\Http\Request;
|
||||
use Webman\Http\Response;
|
||||
use Webman\MiddlewareInterface;
|
||||
|
||||
/**
|
||||
* 已安装系统禁止访问安装 API
|
||||
*/
|
||||
class InstallGuard implements MiddlewareInterface
|
||||
{
|
||||
public function process(Request $request, callable $handler): Response
|
||||
{
|
||||
if (is_system_installed()) {
|
||||
return new Response(403, ['Content-Type' => 'application/json'], json_encode([
|
||||
'code' => 0,
|
||||
'msg' => __('The system has completed installation. If you need to reinstall, please delete the %file% file first', ['%file%' => 'public/install.lock']),
|
||||
'time' => time(),
|
||||
'data' => null,
|
||||
], JSON_UNESCAPED_UNICODE));
|
||||
}
|
||||
|
||||
return $handler($request);
|
||||
}
|
||||
}
|
||||
@@ -636,8 +636,9 @@ if (!function_exists('get_account_verification_type')) {
|
||||
if ($configured) {
|
||||
$types[] = 'email';
|
||||
}
|
||||
if (class_exists(\app\admin\library\module\Server::class)) {
|
||||
$sms = \app\admin\library\module\Server::getIni(\ba\Filesystem::fsFit(root_path() . 'modules/sms/'));
|
||||
$smsIni = \ba\Filesystem::fsFit(root_path() . 'modules/sms/info.ini');
|
||||
if (is_file($smsIni)) {
|
||||
$sms = parse_ini_file($smsIni, true, INI_SCANNER_TYPED) ?: [];
|
||||
if ($sms && ($sms['state'] ?? 0) == 1) {
|
||||
$types[] = 'mobile';
|
||||
}
|
||||
@@ -646,17 +647,6 @@ if (!function_exists('get_account_verification_type')) {
|
||||
}
|
||||
}
|
||||
|
||||
if (!function_exists('is_system_installed')) {
|
||||
/**
|
||||
* 系统是否已完成安装(install.lock 内容为 install-end)
|
||||
*/
|
||||
function is_system_installed(): bool
|
||||
{
|
||||
$lockFile = public_path('install.lock');
|
||||
return is_file($lockFile) && @file_get_contents($lockFile) === 'install-end';
|
||||
}
|
||||
}
|
||||
|
||||
if (!function_exists('get_area')) {
|
||||
function get_area($request = null): array
|
||||
{
|
||||
|
||||
Reference in New Issue
Block a user