v7.0.0-beta.1 release

This commit is contained in:
HeuJung committed 2026-04-01 10:30:52 +09:00
commit 6595fd0eb5
3967 files changed
+1875383

No files matched your search

+915
View File
@@ -0,0 +1,915 @@
<?php
/**
* G7 인스톨러 - 검증 통합 API
*
* 서버 요구사항 검증 및 데이터베이스 연결 테스트 기능을 하나의 API로 통합
*
* 엔드포인트:
* - GET ?action=requirements : 서버 요구사항 검증 (action 생략 시 기본값)
* - POST ?action=test-db : 데이터베이스 연결 테스트
*/
/**
* 검증 API 클래스
*/
class ValidationApi
{
/**
* 요청 처리 메인 메서드
*/
public function handleRequest(): void
{
// JSON 헤더 설정
$this->setJsonHeaders();
// HTTP 메서드 및 action 파라미터 확인
$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? ($method === 'GET' ? 'requirements' : null);
try {
// action에 따라 적절한 메서드 호출
match ($action) {
'requirements' => $this->checkRequirements(),
'test-db' => $this->testDbConnection(),
'detect-php' => $this->detectPhpBinaries(),
'test-php-binary' => $this->testPhpBinary(),
'test-composer' => $this->testComposer(),
'check-core-pending-path' => $this->checkCorePendingPath(),
default => $this->error400('Invalid action parameter'),
};
} catch (Throwable $e) {
$this->error500($e);
}
}
/**
* JSON 응답 헤더 설정
*/
private function setJsonHeaders(): void
{
header('Content-Type: application/json; charset=utf-8');
}
/**
* GET ?action=requirements
* 서버 요구사항 검증
*
* PHP 버전, 확장 모듈, 디스크 공간, 디렉토리 권한, HTTPS 등을 검증합니다.
*/
private function checkRequirements(): void
{
// 요구사항 검증 결과 배열
$requirements = [
'php_version' => $this->checkPhpVersion(),
'php_extensions' => $this->checkPhpExtensions(),
'disabled_functions' => $this->checkDisabledFunctions(),
'php_cli_version' => $this->checkPhpCliVersion(),
'disk_space' => $this->checkDiskSpace(),
'directories' => $this->checkDirectoryPermissions(),
'required_files' => $this->checkRequiredFiles(),
'https' => $this->checkHttps(),
];
// 모든 필수 요구사항 통과 여부
$requirements['all_required_passed'] = $this->isAllRequiredPassed($requirements);
// OS 정보 (프론트엔드에서 명령어 분기용)
$requirements['is_windows'] = isWindows();
// JSON 응답 반환
echo json_encode($requirements, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
}
/**
* POST ?action=test-db
* 데이터베이스 연결 테스트
*
* POST로 전달받은 데이터베이스 연결 정보를 사용하여
* 연결 테스트 및 권한 검증을 수행합니다.
*/
private function testDbConnection(): void
{
// POST 메서드만 허용
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
echo json_encode([
'success' => false,
'message' => lang('api_method_not_allowed'),
], JSON_UNESCAPED_UNICODE);
exit;
}
try {
// POST 데이터 파싱
$input = json_decode(file_get_contents('php://input'), true);
if (! $input || ! is_array($input)) {
throw new Exception(lang('api_invalid_request'));
}
// DB 타입 확인 ('write' 또는 'read')
$type = $input['type'] ?? 'write';
$isReadDb = ($type === 'read');
// DB 연결 정보 구성
$config = [];
if ($isReadDb) {
$config['db_read_host'] = $input['host'] ?? 'localhost';
$config['db_read_port'] = $input['port'] ?? '3306';
$config['db_read_database'] = $input['database'] ?? '';
$config['db_read_username'] = $input['username'] ?? '';
$config['db_read_password'] = $input['password'] ?? '';
} else {
$config['db_write_host'] = $input['host'] ?? 'localhost';
$config['db_write_port'] = $input['port'] ?? '3306';
$config['db_write_database'] = $input['database'] ?? '';
$config['db_write_username'] = $input['username'] ?? '';
$config['db_write_password'] = $input['password'] ?? '';
}
// 필수 필드 검증
$database = $isReadDb ? $config['db_read_database'] : $config['db_write_database'];
$username = $isReadDb ? $config['db_read_username'] : $config['db_write_username'];
if (empty($database) || empty($username)) {
throw new Exception(lang('error_db_credentials_required'));
}
// 데이터베이스 연결 시도
$pdo = getDatabaseConnection($config, $isReadDb);
// 권한 검증
$privileges = checkDatabasePrivileges($pdo, $database, $isReadDb);
// 권한 부족 확인
if (! $privileges['has_all'] && ! empty($privileges['missing'])) {
$missingPrivs = implode(', ', $privileges['missing']);
$dbTypeLabel = $isReadDb ? 'Read' : 'Write';
throw new Exception(
lang('error_db_privileges_insufficient_detail', ['type' => $dbTypeLabel, 'missing' => $missingPrivs])
);
}
// 연결 및 권한 검증 성공 플래그 (Write/Read 구분)
if ($isReadDb) {
$_SESSION['db_read_tested'] = true;
$message = lang('success_db_read_connected');
} else {
$_SESSION['db_write_tested'] = true;
$message = lang('success_db_write_connected');
}
// 성공 응답
echo json_encode([
'success' => true,
'message' => $message,
'type' => $type,
'privileges' => [
'has_all' => $privileges['has_all'],
'found' => $privileges['found'],
'required' => $privileges['required'],
],
], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
} catch (PDOException $e) {
// 연결 실패 플래그
$isReadDb = isset($type) && $type === 'read';
if ($isReadDb) {
$_SESSION['db_read_tested'] = false;
} else {
$_SESSION['db_write_tested'] = false;
}
// 에러 로깅
logInstallationError(lang('error_db_connection_failed'), $e);
// 에러 응답 (200 OK + success: false)
echo json_encode([
'success' => false,
'message' => lang('error_db_connection_failed_detail', ['type' => ($isReadDb ? 'Read' : 'Write'), 'error' => $e->getMessage()]),
'type' => $type ?? 'write',
], JSON_UNESCAPED_UNICODE);
} catch (Exception $e) {
// 권한 검증 실패 또는 기타 에러
$isReadDb = isset($type) && $type === 'read';
if (isset($type)) {
if ($isReadDb) {
$_SESSION['db_read_tested'] = false;
} else {
$_SESSION['db_write_tested'] = false;
}
}
// 에러 로깅
logInstallationError(lang('error_db_test_failed'), $e);
// 에러 응답 (200 OK + success: false)
echo json_encode([
'success' => false,
'message' => $e->getMessage(),
'type' => $type ?? 'write',
], JSON_UNESCAPED_UNICODE);
}
}
// ========================================
// 서버 요구사항 검증 헬퍼 메서드
// ========================================
/**
* PHP 버전 검증
*/
private function checkPhpVersion(): array
{
$currentVersion = PHP_VERSION;
$minVersion = MIN_PHP_VERSION;
$passed = version_compare($currentVersion, $minVersion, '>=');
return [
'required' => true,
'min_version' => $minVersion,
'current_version' => $currentVersion,
'passed' => $passed,
'message' => $passed
? lang('success_php_version_detail', ['current' => $currentVersion, 'min' => $minVersion])
: lang('error_php_version_insufficient_detail', ['current' => $currentVersion, 'min' => $minVersion]),
];
}
/**
* PHP 확장 모듈 검증
*
* 필수 및 선택적 확장 모듈을 검증합니다.
* 선택적 모듈은 설치 여부만 표시하며 전체 검증 통과에 영향을 주지 않습니다.
*/
private function checkPhpExtensions(): array
{
$requiredExtensions = REQUIRED_EXTENSIONS;
$optionalExtensions = defined('OPTIONAL_EXTENSIONS') ? OPTIONAL_EXTENSIONS : [];
$installed = [];
$allRequiredPassed = true;
// 필수 확장 검증
foreach ($requiredExtensions as $extension) {
$isLoaded = extension_loaded($extension);
$installed[$extension] = [
'required' => true,
'installed' => $isLoaded,
];
if (! $isLoaded) {
$allRequiredPassed = false;
}
}
// 선택적 확장 검증 (설치 여부만 표시)
$optionalInstalled = [];
foreach ($optionalExtensions as $extension) {
$optionalInstalled[$extension] = [
'required' => false,
'installed' => extension_loaded($extension),
];
}
return [
'required' => $requiredExtensions,
'optional' => $optionalExtensions,
'installed' => $installed,
'optional_installed' => $optionalInstalled,
'all_required_passed' => $allRequiredPassed,
'message' => $allRequiredPassed
? lang('success_php_extensions')
: lang('error_php_extensions_missing'),
];
}
/**
* 디스크 공간 검증
*/
private function checkDiskSpace(): array
{
$minSpaceMb = MIN_DISK_SPACE_MB;
$freeSpaceBytes = @disk_free_space(BASE_PATH);
// disk_free_space() 실패 시
if ($freeSpaceBytes === false) {
return [
'required' => true,
'min_mb' => $minSpaceMb,
'current_mb' => 0,
'passed' => false,
'message' => lang('error_disk_space_unknown'),
];
}
$freeSpaceMb = round($freeSpaceBytes / 1024 / 1024, 2);
$passed = $freeSpaceMb >= $minSpaceMb;
return [
'required' => true,
'min_mb' => $minSpaceMb,
'current_mb' => $freeSpaceMb,
'passed' => $passed,
'message' => $passed
? lang('success_disk_space_detail', ['current' => $freeSpaceMb, 'min' => $minSpaceMb])
: lang('error_disk_space_insufficient_detail', ['current' => $freeSpaceMb, 'min' => $minSpaceMb]),
];
}
/**
* 디렉토리 권한 검증
*
* functions.php의 공통 함수를 사용하여 권한을 체크합니다.
*/
private function checkDirectoryPermissions(): array
{
// 공통 함수 호출
$check = checkDirectoryPermissions(REQUIRED_DIRECTORIES);
// API 응답 형식에 맞게 변환
$results = [];
foreach ($check['results'] as $dir => $result) {
$results[$dir] = [
'path' => $dir,
'full_path' => BASE_PATH.'/'.$dir,
'relative_path' => './'.$dir,
'exists' => $result['exists'],
'writable' => $result['writable'],
'permissions' => $result['permissions'],
'owner' => $result['owner'],
'group' => $result['group'],
'passed' => $result['passed'],
'error_type' => $result['error_type'],
'has_subdirectory_issues' => $result['has_subdirectory_issues'],
'failed_subdirectories' => $result['failed_subdirectories'],
];
}
return [
'required' => true,
'paths' => array_keys(REQUIRED_DIRECTORIES),
'results' => $results,
'required_permissions' => REQUIRED_DIRECTORY_PERMISSIONS_DISPLAY,
'web_server_group' => getWebServerGroup() ?? getWebServerUser() ?? 'www-data',
'web_server_user' => getWebServerUser(),
'all_passed' => $check['all_passed'],
'message' => $check['all_passed']
? lang('success_directories_writable')
: lang('error_directory_not_writable_detail', ['permissions' => REQUIRED_DIRECTORY_PERMISSIONS_DISPLAY]),
];
}
/**
* 필수 파일 존재 여부 검증
*
* .env 파일이 프로젝트 루트에 존재하는지 확인합니다.
*/
private function checkRequiredFiles(): array
{
$basePath = BASE_PATH;
$filePaths = [
'.env' => $basePath.'/.env',
];
$createCommands = [
'.env' => getEnvCopyCommand($basePath),
];
$files = [];
$allPassed = true;
$hasNotWritable = false;
foreach ($filePaths as $name => $fullPath) {
$exists = file_exists($fullPath);
$writable = $exists && is_writable($fullPath);
// 통과 조건: 존재 + 쓰기 가능
$passed = $exists && $writable;
if (! $passed) {
$allPassed = false;
}
// 에러 타입 결정
$errorType = null;
if (! $exists) {
$errorType = 'not_exists';
} elseif (! $writable) {
$errorType = 'not_writable';
$hasNotWritable = true;
}
$files[$name] = [
'exists' => $exists,
'writable' => $writable,
'passed' => $passed,
'error_type' => $errorType,
'command' => $createCommands[$name],
];
}
return [
'required' => true,
'files' => $files,
'all_passed' => $allPassed,
'has_not_writable' => $hasNotWritable,
'web_server_group' => getWebServerGroup() ?? getWebServerUser() ?? 'www-data',
'web_server_user' => getWebServerUser(),
'base_path' => $basePath,
'relative_base_path' => '.',
'message' => $allPassed
? lang('success_required_files')
: lang('error_required_files_missing'),
];
}
/**
* HTTPS 사용 여부 확인
*/
private function checkHttps(): array
{
$isHttps = isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) === 'on';
// HTTP_X_FORWARDED_PROTO 헤더도 확인 (프록시 환경)
if (! $isHttps && isset($_SERVER['HTTP_X_FORWARDED_PROTO'])) {
$isHttps = strtolower($_SERVER['HTTP_X_FORWARDED_PROTO']) === 'https';
}
return [
'required' => false, // HTTPS는 선택 사항
'enabled' => $isHttps,
'message' => $isHttps
? lang('https_enabled')
: lang('https_disabled'),
];
}
/**
* 필수 PHP 함수(exec, proc_open) 비활성화 여부 검증
*/
private function checkDisabledFunctions(): array
{
$requiredFunctions = ['exec', 'proc_open', 'shell_exec'];
$disabledStr = ini_get('disable_functions');
$disabledList = array_map('trim', explode(',', $disabledStr));
$disabled = [];
foreach ($requiredFunctions as $func) {
if (in_array($func, $disabledList, true)) {
$disabled[] = $func;
}
}
$passed = empty($disabled);
return [
'required' => true,
'checked_functions' => $requiredFunctions,
'disabled' => $disabled,
'passed' => $passed,
'message' => $passed
? lang('success_required_functions')
: lang('error_disabled_functions', ['functions' => implode(', ', $disabled)]),
];
}
/**
* PHP CLI 버전과 웹 PHP 버전 일치 여부 확인
*/
private function checkPhpCliVersion(): array
{
$webVersion = PHP_VERSION;
$cliVersion = null;
$cliPath = 'php';
// exec 사용 가능 여부 먼저 확인
$disabledStr = ini_get('disable_functions');
$disabledList = array_map('trim', explode(',', $disabledStr));
if (in_array('exec', $disabledList, true)) {
return [
'required' => false,
'web_version' => $webVersion,
'cli_version' => null,
'cli_path' => null,
'matched' => null,
'message' => lang('php_cli_version_check_skipped'),
];
}
$output = [];
$returnCode = -1;
exec('php --version 2>&1', $output, $returnCode);
if ($returnCode === 0 && !empty($output)) {
$outputStr = implode("\n", $output);
if (preg_match('/PHP\s+(\d+\.\d+\.\d+)/', $outputStr, $matches)) {
$cliVersion = $matches[1];
}
}
// 메이저.마이너 버전 비교 (패치 차이는 무시)
$webMajorMinor = implode('.', array_slice(explode('.', $webVersion), 0, 2));
$cliMajorMinor = $cliVersion ? implode('.', array_slice(explode('.', $cliVersion), 0, 2)) : null;
$matched = $cliMajorMinor !== null && $webMajorMinor === $cliMajorMinor;
return [
'required' => false,
'web_version' => $webVersion,
'cli_version' => $cliVersion,
'cli_path' => $cliPath,
'matched' => $matched,
'message' => $cliVersion === null
? lang('php_cli_version_unknown')
: ($matched
? lang('php_cli_version_matched', ['web' => $webVersion, 'cli' => $cliVersion])
: lang('php_cli_version_mismatch', ['web' => $webVersion, 'cli' => $cliVersion])),
];
}
/**
* GET ?action=detect-php
* 서버에서 사용 가능한 PHP 바이너리 자동 탐색
*/
private function detectPhpBinaries(): void
{
$commonPaths = [
'/usr/local/php84/bin/php',
'/usr/local/php83/bin/php',
'/usr/local/php82/bin/php',
'/usr/bin/php8.4',
'/usr/bin/php8.3',
'/usr/bin/php8.2',
'/usr/local/bin/php',
'/usr/bin/php',
];
$found = [];
$checkedPaths = [];
$minVersion = MIN_PHP_VERSION;
// PHP_BINARY 상수
if (defined('PHP_BINARY') && PHP_BINARY !== '' && !in_array(PHP_BINARY, $checkedPaths, true)) {
$checkedPaths[] = PHP_BINARY;
$result = $this->validatePhpPath(PHP_BINARY);
if ($result['valid']) {
$found[] = ['path' => PHP_BINARY, 'version' => $result['version']];
}
}
// 공통 경로 스캔
foreach ($commonPaths as $path) {
if (in_array($path, $checkedPaths, true)) {
continue;
}
$checkedPaths[] = $path;
if (!file_exists($path)) {
continue;
}
$result = $this->validatePhpPath($path);
if ($result['valid']) {
$found[] = ['path' => $path, 'version' => $result['version']];
}
}
// 시스템 PATH의 'php'
$defaultPhpAvailable = false;
if (!in_array('php', $checkedPaths, true)) {
$result = $this->validatePhpPath('php');
if ($result['valid']) {
$found[] = ['path' => 'php', 'version' => $result['version']];
$defaultPhpAvailable = true;
}
} else {
// 이미 체크된 경우 found 배열에서 확인
foreach ($found as $bin) {
if ($bin['path'] === 'php') {
$defaultPhpAvailable = true;
break;
}
}
}
// Composer 자동 감지 (감지된 PHP 중 첫 번째로 검증)
$phpForComposer = !empty($found) ? $found[0]['path'] : 'php';
$composerResult = $this->detectComposerBinary($phpForComposer);
echo json_encode([
'success' => !empty($found),
'binaries' => $found,
'default_php_available' => $defaultPhpAvailable,
'composer' => $composerResult,
'message' => empty($found) ? lang('no_php_detected') : lang('php_detected_count', ['count' => count($found)]),
], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
}
/**
* Composer 바이너리 자동 감지
*
* @param string $phpPath .phar 실행 시 사용할 PHP 경로
* @return array{found: bool, path: string|null, version: string|null}
*/
private function detectComposerBinary(string $phpPath = 'php'): array
{
// 1. 시스템 PATH의 composer
$result = $this->validateComposerPath('composer', $phpPath);
if ($result['valid']) {
return ['found' => true, 'path' => 'composer', 'version' => $result['version']];
}
// 2. 프로젝트 루트의 composer.phar
$pharPath = realpath(__DIR__ . '/../../..') . '/composer.phar';
if (file_exists($pharPath)) {
$result = $this->validateComposerPath($pharPath, $phpPath);
if ($result['valid']) {
return ['found' => true, 'path' => $pharPath, 'version' => $result['version']];
}
}
// 3. 현재 디렉토리(public/install/api)의 composer.phar
$localPhar = realpath(__DIR__) . '/composer.phar';
if (file_exists($localPhar)) {
$result = $this->validateComposerPath($localPhar, $phpPath);
if ($result['valid']) {
return ['found' => true, 'path' => $localPhar, 'version' => $result['version']];
}
}
return ['found' => false, 'path' => null, 'version' => null];
}
/**
* POST ?action=test-php-binary
* 지정된 PHP 바이너리 경로의 유효성 검증
*/
private function testPhpBinary(): void
{
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
$this->error400('POST method required');
}
$input = json_decode(file_get_contents('php://input'), true);
$path = $input['path'] ?? 'php';
$result = $this->validatePhpPath($path);
echo json_encode([
'success' => $result['valid'],
'version' => $result['version'],
'message' => $result['message'],
], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
}
/**
* POST ?action=test-composer
* Composer 바이너리 경로의 유효성 검증
*/
private function testComposer(): void
{
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
$this->error400('POST method required');
}
$input = json_decode(file_get_contents('php://input'), true);
$composerPath = trim($input['path'] ?? '');
$phpPath = trim($input['php_path'] ?? 'php');
$result = $this->validateComposerPath($composerPath, $phpPath);
echo json_encode([
'success' => $result['valid'],
'version' => $result['version'],
'message' => $result['message'],
], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
}
/**
* GET ?action=check-core-pending-path
* 코어 업데이트 _pending 경로 퍼미션/소유자 체크
*/
private function checkCorePendingPath(): void
{
$path = $_GET['path'] ?? '';
if (empty($path)) {
echo json_encode(['success' => false, 'message' => lang('error_path_required')], JSON_UNESCAPED_UNICODE);
return;
}
$absolutePath = str_starts_with($path, '/')
? $path
: BASE_PATH . '/' . $path;
if (!file_exists($absolutePath)) {
echo json_encode([
'success' => false,
'message' => lang('error_path_not_exists', ['path' => $path]),
], JSON_UNESCAPED_UNICODE);
return;
}
if (!is_dir($absolutePath)) {
echo json_encode([
'success' => false,
'message' => lang('error_core_pending_not_directory'),
], JSON_UNESCAPED_UNICODE);
return;
}
$writable = is_writable($absolutePath);
echo json_encode([
'success' => $writable,
'message' => $writable
? lang('success_core_pending_path')
: lang('error_core_pending_not_writable'),
], JSON_UNESCAPED_UNICODE);
}
/**
* PHP 바이너리 경로 유효성 검증 헬퍼
*
* @param string $path PHP 바이너리 경로
* @return array{valid: bool, version: string|null, message: string}
*/
private function validatePhpPath(string $path): array
{
if (empty($path)) {
return ['valid' => false, 'version' => null, 'message' => lang('error_php_path_empty')];
}
// file_exists 사전 체크 없이 실행 결과로 판단
$command = escapeshellarg($path) . ' --version 2>&1';
$output = [];
$returnCode = -1;
exec($command, $output, $returnCode);
if ($returnCode !== 0) {
return ['valid' => false, 'version' => null, 'message' => lang('error_php_exec_failed', ['path' => $path])];
}
$outputStr = implode("\n", $output);
if (preg_match('/PHP\s+(\d+\.\d+\.\d+)/', $outputStr, $matches)) {
$version = $matches[1];
if (version_compare($version, MIN_PHP_VERSION, '>=')) {
return [
'valid' => true,
'version' => $version,
'message' => lang('success_php_binary_version', ['path' => $path, 'version' => $version]),
];
}
return [
'valid' => false,
'version' => $version,
'message' => lang('error_php_version_too_low', ['path' => $path, 'version' => $version, 'min' => MIN_PHP_VERSION]),
];
}
return ['valid' => false, 'version' => null, 'message' => lang('error_php_version_parse_failed')];
}
/**
* Composer 바이너리 경로 유효성 검증 헬퍼
*
* @param string $composerPath Composer 바이너리 경로 (빈 문자열이면 시스템 'composer')
* @param string $phpPath PHP 바이너리 경로 (.phar 실행 시 사용)
* @return array{valid: bool, version: string|null, message: string}
*/
private function validateComposerPath(string $composerPath, string $phpPath = 'php'): array
{
// 빈 문자열이면 시스템 기본 composer 사용
$effectivePath = $composerPath ?: 'composer';
// 실행 명령어 구성
if (str_contains($effectivePath, ' ')) {
// 공백 포함 = 전체 실행 명령어 (예: "/usr/local/php84/bin/php composer.phar")
// escapeshellarg 없이 그대로 실행
$command = $effectivePath . ' --version 2>&1';
} elseif (str_ends_with($effectivePath, '.phar')) {
// .phar 파일 단독 경로 → PHP 바이너리와 결합
$command = escapeshellarg($phpPath) . ' ' . escapeshellarg($effectivePath) . ' --version 2>&1';
} else {
// composer 바이너리 경로
$command = escapeshellarg($effectivePath) . ' --version 2>&1';
}
$output = [];
$returnCode = -1;
exec($command, $output, $returnCode);
if ($returnCode !== 0) {
return ['valid' => false, 'version' => null, 'message' => lang('error_composer_exec_failed', ['path' => $effectivePath])];
}
$outputStr = implode("\n", $output);
if (preg_match('/Composer\s+(?:version\s+)?(\d+\.\d+\.\d+)/', $outputStr, $matches)) {
$version = $matches[1];
return [
'valid' => true,
'version' => $version,
'message' => lang('success_composer_version', ['path' => $effectivePath, 'version' => $version]),
];
}
return ['valid' => false, 'version' => null, 'message' => lang('error_composer_version_parse_failed')];
}
/**
* 모든 필수 요구사항 통과 여부 확인
*/
private function isAllRequiredPassed(array $requirements): bool
{
// PHP 버전 확인
if (! $requirements['php_version']['passed']) {
return false;
}
// PHP 확장 확인
if (! $requirements['php_extensions']['all_required_passed']) {
return false;
}
// 필수 함수 비활성화 확인
if (isset($requirements['disabled_functions']) && ! $requirements['disabled_functions']['passed']) {
return false;
}
// 디스크 공간 확인
if (! $requirements['disk_space']['passed']) {
return false;
}
// 디렉토리 권한 확인
if (! $requirements['directories']['all_passed']) {
return false;
}
// 필수 파일 확인
if (! $requirements['required_files']['all_passed']) {
return false;
}
// HTTPS는 선택 사항이므로 검증하지 않음
return true;
}
// ========================================
// 공통 에러 처리 메서드
// ========================================
/**
* 400 Bad Request 응답
*/
private function error400(string $message): void
{
http_response_code(400);
echo json_encode([
'success' => false,
'error' => 'Bad Request',
'message' => $message,
], JSON_UNESCAPED_UNICODE);
exit;
}
/**
* 500 Internal Server Error 응답
*/
private function error500(Throwable $e): void
{
// 에러 로깅
if (function_exists('logInstallationError')) {
logInstallationError('Validation API error', $e);
}
// 에러 응답
http_response_code(500);
echo json_encode([
'success' => false,
'error' => 'Internal Server Error',
'message' => $e->getMessage(),
'details' => $e->getMessage(),
], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
exit;
}
}
// ========================================
// 실행 부분
// ========================================
// 필수 파일 로드 (config.php가 BASE_PATH를 정의함)
require_once __DIR__.'/../includes/config.php';
require_once __DIR__.'/../includes/session.php';
require_once __DIR__.'/../includes/functions.php';
// 다국어 로드
$currentLang = getCurrentLanguage();
$translations = loadTranslations($currentLang);
// API 인스턴스 생성 및 요청 처리
$api = new ValidationApi;
$api->handleRequest();
+45
View File
@@ -0,0 +1,45 @@
<?php
/**
* 그누보드7 웹 인스톨러 - 필수 파일 존재 여부 체크 API
*
* Step 5 진입 시 JavaScript에서 호출하여 .env 파일의
* 존재 여부 및 쓰기 가능 여부를 확인합니다.
*
* @package G7\Installer
*/
// 필수 파일 include
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/functions.php';
// JSON 응답 헤더
header('Content-Type: application/json; charset=utf-8');
// GET 요청만 허용
if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
http_response_code(405);
echo json_encode([
'success' => false,
'message' => 'Only GET requests are allowed.',
], JSON_UNESCAPED_UNICODE);
exit;
}
$envPath = BASE_PATH . '/.env';
// 소유자 === 웹 서버 사용자 여부 판별 (chgrp/sudo 생략 기준)
$webUser = getWebServerUser();
$baseOwner = function_exists('posix_getpwuid') && function_exists('posix_getuid')
? (posix_getpwuid(fileowner(BASE_PATH))['name'] ?? null)
: null;
$ownerIsWebUser = $webUser && $baseOwner && $webUser === $baseOwner;
echo json_encode([
'env_exists' => file_exists($envPath),
'env_writable' => file_exists($envPath) && is_writable($envPath),
'path' => BASE_PATH,
'relative_path' => '.',
'is_windows' => isWindows(),
'owner_is_web_user' => $ownerIsWebUser,
], JSON_UNESCAPED_UNICODE);
+196
View File
@@ -0,0 +1,196 @@
<?php
/**
* G7 인스톨러 설치 프로세스 API (SSE 방식)
*
* 설치 설정을 저장하고 상태를 'started'로 변경합니다.
* 실제 설치 작업은 install-worker.php가 SSE를 통해 실행합니다.
*
* @method POST
* @response JSON {"status": "started", "message": "설치가 시작되었습니다"}
*/
// 필수 파일 포함 (config.php가 BASE_PATH를 정의함)
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/session.php';
require_once __DIR__ . '/../includes/installer-state.php';
require_once __DIR__ . '/../includes/functions.php';
// 다국어 로드
$currentLang = getCurrentLanguage();
$translations = loadTranslations($currentLang);
// JSON 응답 헤더 설정
header('Content-Type: application/json; charset=UTF-8');
/**
* POST 요청인지 확인
*/
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
echo json_encode([
'success' => false,
'message' => lang('error_method_not_allowed'),
], JSON_UNESCAPED_UNICODE);
exit;
}
try {
/**
* 세션에서 설정 정보 로드
* 세션이 비어있으면 (브라우저 재시작 등) state.json에서 로드
*/
$config = getSessionData('install_config');
// 세션이 비어있으면 state.json에서 로드
if (empty($config)) {
$state = getInstallationState();
$config = $state['config'] ?? [];
// state.json에도 config가 없으면 에러
if (empty($config)) {
http_response_code(400);
echo json_encode([
'success' => false,
'message' => lang('error_config_not_in_session'),
], JSON_UNESCAPED_UNICODE);
exit;
}
// state.json에서 로드한 config를 세션에도 저장 (이후 요청에서 사용)
setSessionData('install_config', $config);
}
/**
* 필수 설정 항목 검증
*/
$requiredFields = [
'db_write_host',
'db_write_database',
'db_write_username',
'app_name',
'app_url',
'admin_name',
'admin_email',
'admin_password',
];
$missingFields = [];
foreach ($requiredFields as $field) {
if (empty($config[$field])) {
$missingFields[] = $field;
}
}
if (!empty($missingFields)) {
http_response_code(400);
echo json_encode([
'success' => false,
'message' => lang('error_required_fields_missing', ['fields' => implode(', ', $missingFields)]),
], JSON_UNESCAPED_UNICODE);
exit;
}
/**
* 필수 파일 존재 여부 사전 체크
*/
$missingRequiredFiles = [];
if (!file_exists(BASE_PATH . '/.env')) {
$missingRequiredFiles[] = '.env';
}
if (!empty($missingRequiredFiles)) {
http_response_code(400);
echo json_encode([
'success' => false,
'message' => lang('error_env_not_found'),
'env_required' => true,
'missing_files' => $missingRequiredFiles,
'base_path' => BASE_PATH,
'is_windows' => isWindows(),
], JSON_UNESCAPED_UNICODE);
exit;
}
/**
* 현재 상태 가져오기
*/
$state = getInstallationState();
/**
* 상태 초기화
*
* 재시도/재개인 경우 (installation_status가 'running', 'failed' 또는 'aborted'인 경우):
* - completed_tasks는 유지 (이미 완료된 작업은 건너뛰기)
* - error는 초기화
* - 나머지는 running 상태로 재설정
*/
$isRetry = isset($state['installation_status']) &&
in_array($state['installation_status'], ['running', 'failed', 'aborted']);
$state['current_step'] = 5; // Step 5 = Installation (Step 4 = Extension Selection)
$state['installation_status'] = 'running';
$state['completed_tasks'] = $isRetry ? ($state['completed_tasks'] ?? []) : [];
$state['current_task'] = null;
$state['config'] = $config;
$state['error'] = null;
/**
* 로그 파일 초기화 (재시도가 아닌 경우에만)
*
* Step 4 -> Step 5로 새로 진입하는 경우 이전 로그를 초기화합니다.
* 재시도/재개인 경우에는 기존 로그를 유지합니다.
*/
if (!$isRetry) {
$logFilePath = BASE_PATH . '/storage/logs/installation.log';
if (file_exists($logFilePath)) {
@unlink($logFilePath);
}
}
/**
* 상태 저장
*/
$saved = saveInstallationState($state);
if (!$saved) {
throw new Exception(lang('state_save_failed'));
}
/**
* 로그 기록
*/
addLog(lang('log_installation_config_saved'));
/**
* 클라이언트에 즉시 응답 전송
*
* JavaScript에서 이 응답을 받은 후 install-worker.php로 SSE 연결을 시작합니다.
*/
http_response_code(200);
echo json_encode([
'success' => true,
'status' => 'started',
'message' => lang('success_installation_started'),
], JSON_UNESCAPED_UNICODE);
} catch (Exception $e) {
/**
* 에러 처리
*/
// 에러 로깅
logInstallationError(lang('error_installation_start_failed'), $e);
// 상태를 failed로 변경
$state = getInstallationState();
$state['installation_status'] = 'failed';
$state['error'] = $e->getMessage();
saveInstallationState($state);
// 에러 응답
http_response_code(500);
echo json_encode([
'success' => false,
'message' => lang('error_installation_start_exception', ['error' => $e->getMessage()]),
], JSON_UNESCAPED_UNICODE);
}
File diff suppressed because it is too large. Load diff
+529
View File
@@ -0,0 +1,529 @@
<?php
/**
* G7 인스톨러 - 롤백 함수 모음
*
* 설치 중단 시 각 작업을 롤백하는 함수들을 제공합니다.
*/
/**
* 중단된 작업을 롤백합니다.
*
* @param string $taskId 롤백할 작업 식별자
* @param array $state 현재 설치 상태
* @return array ['success' => bool, 'message' => string] 롤백 결과
*/
function rollbackTask(string $taskId, array $state): array
{
try {
switch ($taskId) {
case 'db_migrate':
return rollbackDbMigrate();
case 'db_seed':
return rollbackDbSeed($state);
case 'complete_flag':
return rollbackCompleteFlag();
// 롤백 불필요한 작업들 (새로 생성하면 되는 것들)
case 'composer_check':
case 'composer_install':
case 'env_create':
case 'env_update':
case 'key_generate':
case 'cache_clear':
case 'create_settings_json':
return [
'success' => true,
'message' => lang('rollback_not_needed_recreatable'),
];
// 롤백 불필요한 확장 작업 (재설치/재활성화 시 덮어쓰기 가능)
case 'template_install':
case 'template_activate':
case 'module_install':
case 'module_activate':
case 'plugin_install':
case 'plugin_activate':
case 'user_template_install':
case 'user_template_activate':
return [
'success' => true,
'message' => lang('rollback_not_needed_overwritable'),
];
default:
return [
'success' => false,
'message' => lang('rollback_unknown_task', ['task' => $taskId])
];
}
} catch (Exception $e) {
addLog(lang('rollback_error', ['task' => $taskId, 'error' => $e->getMessage()]));
return [
'success' => false,
'message' => lang('rollback_exception', ['error' => $e->getMessage()])
];
}
}
/**
* 마이그레이션 롤백을 실행합니다 (migrate:rollback --force)
*
* @param string|null $logPrefix 로그 접두사 (null이면 lang('log_prefix_rollback') 사용)
* @return array ['success' => bool, 'message' => string, 'output' => array]
*/
function executeMigrateRollback(?string $logPrefix = null): array
{
$logPrefix = $logPrefix ?? lang('log_prefix_rollback');
try {
addLog("{$logPrefix} " . lang('rollback_migrate_start'));
$output = [];
$returnCode = 0;
$phpBin = escapeshellarg(function_exists('getPhpBinary') ? getPhpBinary() : 'php');
$command = sprintf(
'cd /d %s && %s artisan migrate:rollback --force 2>&1',
escapeshellarg(BASE_PATH),
$phpBin
);
exec($command, $output, $returnCode);
addLog("{$logPrefix} " . lang('rollback_migrate_result', ['result' => implode("\n", $output)]));
if ($returnCode === 0) {
return [
'success' => true,
'message' => lang('rollback_migrate_success'),
'output' => $output,
];
}
addLog("{$logPrefix} " . lang('rollback_migrate_failed_code', ['code' => $returnCode]));
return [
'success' => false,
'message' => lang('rollback_migrate_failed'),
'output' => $output,
];
} catch (Exception $e) {
return [
'success' => false,
'message' => lang('rollback_migrate_error', ['error' => $e->getMessage()]),
'output' => [],
];
}
}
/**
* db_migrate 작업 롤백: migrate:rollback 실행
*
* @return array ['success' => bool, 'message' => string, 'output' => array]
*/
function rollbackDbMigrate(): array
{
return executeMigrateRollback(lang('log_prefix_rollback'));
}
/**
* 시드 데이터 TRUNCATE를 실행합니다 (PDO 세션 내 FOREIGN_KEY_CHECKS 제어)
*
* @param array $config DB 연결 설정
* @param bool $force true: 무조건 TRUNCATE, false: 미완료 시에만 TRUNCATE
* @param string|null $logPrefix 로그 접두사 (null이면 lang('log_prefix_rollback') 사용)
* @return array ['success' => bool, 'message' => string]
*/
function executeSeedTruncate(array $config, bool $force = false, ?string $logPrefix = null): array
{
$logPrefix = $logPrefix ?? lang('log_prefix_rollback');
if (empty($config['db_write_host']) || empty($config['db_write_database'])) {
addLog("{$logPrefix} " . lang('rollback_seed_no_config'));
return ['success' => true, 'message' => lang('rollback_seed_no_config')];
}
$dsn = sprintf(
'mysql:host=%s;port=%s;dbname=%s;charset=utf8mb4',
$config['db_write_host'],
$config['db_write_port'] ?? '3306',
$config['db_write_database']
);
try {
$pdo = new PDO($dsn, $config['db_write_username'], $config['db_write_password'], [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
]);
// 강제 모드가 아니면 완료 여부 확인
if (!$force) {
$stmt = $pdo->query("SHOW TABLES LIKE 'roles'");
if ($stmt->rowCount() > 0) {
$count = $pdo->query("SELECT COUNT(*) FROM roles")->fetchColumn();
if ($count > 0) {
addLog("{$logPrefix} " . lang('rollback_seed_already_done'));
return ['success' => true, 'message' => lang('rollback_seed_already_done')];
}
}
addLog("{$logPrefix} " . lang('rollback_seed_interrupted'));
} else {
addLog("{$logPrefix} " . lang('rollback_seed_force_truncate'));
}
$pdo->exec('SET FOREIGN_KEY_CHECKS = 0');
$tables = ['users', 'roles', 'permissions', 'role_user', 'permission_role'];
foreach ($tables as $table) {
try {
$pdo->exec("TRUNCATE TABLE `{$table}`");
addLog("{$logPrefix} " . lang('rollback_table_truncated', ['table' => $table]));
} catch (PDOException $e) {
addLog("{$logPrefix} " . lang('rollback_table_truncate_skipped', ['table' => $table, 'error' => $e->getMessage()]));
}
}
$pdo->exec('SET FOREIGN_KEY_CHECKS = 1');
return ['success' => true, 'message' => lang('rollback_seed_data_deleted')];
} catch (PDOException $e) {
if ($force) {
return ['success' => false, 'message' => lang('rollback_db_connection_failed', ['error' => $e->getMessage()])];
}
addLog("{$logPrefix} " . lang('rollback_db_connection_failed_skip'));
return ['success' => true, 'message' => lang('rollback_db_connection_failed_skip')];
}
}
/**
* db_seed 작업 롤백: 중단된 경우에만 TRUNCATE
*
* @param array $state 현재 설치 상태
* @return array ['success' => bool, 'message' => string]
*/
function rollbackDbSeed(array $state): array
{
try {
return executeSeedTruncate($state['config'] ?? [], false, lang('log_prefix_rollback'));
} catch (Exception $e) {
return ['success' => false, 'message' => lang('rollback_seed_error', ['error' => $e->getMessage()])];
}
}
/**
* db_migrate 작업 강제 롤백 (설정으로 돌아갈 때 사용)
*
* @return array ['success' => bool, 'message' => string, 'output' => array]
*/
function forceRollbackDbMigrate(): array
{
return executeMigrateRollback(lang('log_prefix_force_rollback'));
}
/**
* db_seed 작업 강제 롤백 (설정으로 돌아갈 때 사용)
*
* @param array $state 현재 설치 상태
* @return array ['success' => bool, 'message' => string]
*/
function forceRollbackDbSeed(array $state): array
{
try {
return executeSeedTruncate($state['config'] ?? [], true, lang('log_prefix_force_rollback'));
} catch (Exception $e) {
return ['success' => false, 'message' => lang('rollback_seed_error', ['error' => $e->getMessage()])];
}
}
/**
* complete_flag 작업 롤백: 설치 완료 플래그 제거
*/
function rollbackCompleteFlag(): array
{
try {
$envPath = BASE_PATH . '/.env';
$installedFlagPath = BASE_PATH . '/storage/app/g7_installed';
$results = [];
// .env에서 INSTALLER_COMPLETED 제거
if (file_exists($envPath)) {
$envContent = file_get_contents($envPath);
$envContent = preg_replace('/^INSTALLER_COMPLETED=.*$/m', '', $envContent);
$envContent = preg_replace("/\n\n+/", "\n\n", $envContent);
if (file_put_contents($envPath, $envContent) !== false) {
addLog(lang('rollback_env_flag_removed'));
$results[] = lang('rollback_env_flag_removed');
}
}
// g7_installed 파일 삭제
if (file_exists($installedFlagPath)) {
if (@unlink($installedFlagPath)) {
addLog(lang('rollback_installed_flag_removed'));
$results[] = lang('rollback_installed_flag_removed');
}
}
return [
'success' => true,
'message' => lang('rollback_complete_flag_removed', ['details' => implode(', ', $results)])
];
} catch (Exception $e) {
return [
'success' => false,
'message' => lang('rollback_complete_flag_error', ['error' => $e->getMessage()])
];
}
}
/**
* 디렉토리 내용을 삭제합니다.
*
* Git 추적 파일(.gitkeep 등)은 보존하고, 디렉토리 자체도 유지합니다.
* 이는 인스톨러가 프로젝트 구조에 필수적인 파일/디렉토리를
* 실수로 삭제하는 것을 방지합니다.
*
* @param string $dir 삭제할 디렉토리 경로
* @param bool $removeDir true이면 디렉토리 자체도 삭제 (기본: false, 내용만 삭제)
* @return bool 삭제 성공 여부
*/
function deleteDirectory(string $dir, bool $removeDir = false): bool
{
if (!is_dir($dir)) {
return false;
}
// 보존해야 할 파일 패턴 (Git 추적용 파일)
$preserveFiles = ['.gitkeep', '.gitignore'];
$items = array_diff(scandir($dir), ['.', '..']);
$hasPreservedFiles = false;
foreach ($items as $item) {
$path = $dir . DIRECTORY_SEPARATOR . $item;
if (is_dir($path)) {
deleteDirectory($path, true);
} else {
// 보존 대상 파일은 건너뛰기
if (in_array($item, $preserveFiles, true)) {
$hasPreservedFiles = true;
continue;
}
@unlink($path);
}
}
// 보존 파일이 남아있거나 removeDir이 false이면 디렉토리 유지
if ($hasPreservedFiles || !$removeDir) {
return true;
}
return @rmdir($dir);
}
/**
* 현재 진행 중인 작업을 롤백합니다. (abort.php에서 사용)
*
* @param array $state 현재 설치 상태
* @return array ['success' => bool, 'message' => string, 'task' => string|null]
*/
function rollbackCurrentTask(array $state): array
{
$currentTask = $state['current_task'] ?? null;
if (!$currentTask) {
addLog(lang('rollback_no_current_task'));
return [
'success' => true,
'message' => lang('rollback_no_current_task'),
'task' => null,
];
}
if (in_array($currentTask, $state['completed_tasks'] ?? [])) {
addLog(lang('rollback_task_already_completed', ['task' => $currentTask]));
return [
'success' => true,
'message' => lang('rollback_task_already_completed', ['task' => $currentTask]),
'task' => $currentTask,
];
}
addLog(lang('rollback_current_task_start', ['task' => $currentTask]));
$rollbackResult = rollbackTask($currentTask, $state);
if ($rollbackResult['success']) {
addLog(lang('abort_rollback_success', ['message' => $rollbackResult['message']]));
return [
'success' => true,
'message' => lang('abort_rollback_success', ['message' => $rollbackResult['message']]),
'task' => $currentTask,
];
} else {
addLog(lang('abort_rollback_failed', ['message' => $rollbackResult['message']]));
return [
'success' => false,
'message' => lang('failed_rollback_failed', ['message' => $rollbackResult['message']]),
'task' => $currentTask,
];
}
}
/**
* 완료된 작업들을 역순으로 롤백합니다. (reset-state.php에서 사용)
*
* @param array $completedTasks 완료된 작업 목록
* @param array $rollbackableTasks 롤백 가능한 작업 목록
* @param array $state 현재 설치 상태
* @return array ['results' => array, 'errors' => array]
*/
function rollbackCompletedTasks(array $completedTasks, array $rollbackableTasks, array $state): array
{
$results = [];
$errors = [];
if (empty($completedTasks)) {
addLog(lang('rollback_no_completed_tasks'));
return ['results' => $results, 'errors' => $errors];
}
addLog(lang('rollback_checking_tasks'));
$tasksToRollback = array_reverse(
array_intersect($rollbackableTasks, $completedTasks)
);
if (empty($tasksToRollback)) {
addLog(lang('rollback_no_matching_tasks'));
return ['results' => $results, 'errors' => $errors];
}
addLog(lang('rollback_tasks_to_rollback', ['tasks' => implode(', ', $tasksToRollback)]));
foreach ($tasksToRollback as $taskId) {
addLog(lang('rollback_task_rolling_back', ['task' => $taskId]));
if ($taskId === 'db_migrate') {
$result = forceRollbackDbMigrate();
} elseif ($taskId === 'db_seed') {
$result = forceRollbackDbSeed($state);
} else {
$result = rollbackTask($taskId, $state);
}
if ($result['success']) {
$results[] = $taskId . ': ' . $result['message'];
addLog(lang('rollback_task_success', ['task' => $taskId]));
} else {
$errors[] = $taskId . ': ' . $result['message'];
addLog(lang('rollback_task_failed', ['task' => $taskId, 'error' => $result['message']]));
}
}
return ['results' => $results, 'errors' => $errors];
}
/**
* 실패한 작업에 대한 수동 명령어를 생성합니다.
*
* @param string $taskId 작업 ID
* @param string|null $target 대상 (확장 식별자)
* @return array 수동 명령어 배열
*/
function getManualCommands(string $taskId, ?string $target = null): array
{
$commands = [];
$php = getPhpBinary();
$composer = getComposerCommandForDisplay();
switch ($taskId) {
case 'composer_install':
$commands[] = "{$composer} install --no-interaction --prefer-dist --optimize-autoloader";
break;
case 'env_create':
$commands[] = getEnvCopyCommand();
break;
case 'key_generate':
$commands[] = "{$php} artisan key:generate";
break;
case 'db_migrate':
$commands[] = "{$php} artisan migrate --force";
break;
case 'db_seed':
$commands[] = "{$php} artisan db:seed --force";
break;
case 'template_install':
if ($target) {
$commands[] = "{$php} artisan template:install {$target}";
}
break;
case 'template_activate':
if ($target) {
$commands[] = "{$php} artisan template:activate {$target}";
}
break;
case 'module_install':
if ($target) {
$commands[] = "{$php} artisan module:install {$target}";
}
break;
case 'module_activate':
if ($target) {
$commands[] = "{$php} artisan module:activate {$target}";
}
break;
case 'plugin_install':
if ($target) {
$commands[] = "{$php} artisan plugin:install {$target}";
}
break;
case 'plugin_activate':
if ($target) {
$commands[] = "{$php} artisan plugin:activate {$target}";
}
break;
case 'user_template_install':
if ($target) {
$commands[] = "{$php} artisan template:install {$target}";
}
break;
case 'user_template_activate':
if ($target) {
$commands[] = "{$php} artisan template:activate {$target}";
}
break;
case 'create_settings_json':
$commands[] = '# ' . lang('manual_cmd_settings_json');
break;
case 'cache_clear':
$commands[] = "{$php} artisan optimize:clear";
break;
case 'complete_flag':
if (isWindows()) {
$commands[] = 'echo INSTALLER_COMPLETED=true >> .env';
$commands[] = 'type nul > storage\\app\\g7_installed';
} else {
$commands[] = 'echo "INSTALLER_COMPLETED=true" >> .env';
$commands[] = 'touch storage/app/g7_installed';
}
break;
}
return $commands;
}
+153
View File
@@ -0,0 +1,153 @@
<?php
/**
* G7 인스톨러 - 선택된 확장 기능 저장 API
*
* 사용자가 선택한 확장 기능 목록을 state.json에 저장합니다.
*
* @method POST
* @body {
* "admin_templates": ["sirsoft-admin_basic"],
* "user_templates": ["sirsoft-basic"],
* "modules": ["sirsoft-board", "sirsoft-ecommerce"],
* "plugins": ["sirsoft-verification"]
* }
*
* @response {
* "success": true,
* "message": "확장 기능 선택이 저장되었습니다."
* }
*/
// 기본 설정
header('Content-Type: application/json; charset=utf-8');
// 프로젝트 루트 경로
define('BASE_PATH', realpath(dirname(__DIR__, 3)) ?: dirname(__DIR__, 3));
// 세션 및 설정 포함
require_once dirname(__DIR__) . '/includes/session.php';
require_once dirname(__DIR__) . '/includes/config.php';
require_once dirname(__DIR__) . '/includes/installer-state.php';
require_once dirname(__DIR__) . '/includes/functions.php';
// 다국어 로드
$currentLang = getCurrentLanguage();
$translations = loadTranslations($currentLang);
// POST 요청만 허용
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
echo json_encode([
'success' => false,
'error' => lang('api_method_not_allowed'),
], JSON_UNESCAPED_UNICODE);
exit;
}
// 요청 본문 파싱
$input = json_decode(file_get_contents('php://input'), true);
if (json_last_error() !== JSON_ERROR_NONE) {
http_response_code(400);
echo json_encode([
'success' => false,
'error' => lang('api_invalid_request'),
], JSON_UNESCAPED_UNICODE);
exit;
}
// 필드 검증 및 기본값 설정
$adminTemplates = isset($input['admin_templates']) && is_array($input['admin_templates'])
? $input['admin_templates']
: [];
$userTemplates = isset($input['user_templates']) && is_array($input['user_templates'])
? $input['user_templates']
: [];
$modules = isset($input['modules']) && is_array($input['modules'])
? $input['modules']
: [];
$plugins = isset($input['plugins']) && is_array($input['plugins'])
? $input['plugins']
: [];
// 확장 이름 매핑 (identifier → {ko: '...', en: '...'})
$extensionNames = isset($input['extension_names']) && is_array($input['extension_names'])
? $input['extension_names']
: [];
// 관리자 템플릿은 최소 1개 필수
if (empty($adminTemplates)) {
http_response_code(400);
echo json_encode([
'success' => false,
'error' => lang('error_admin_template_required'),
], JSON_UNESCAPED_UNICODE);
exit;
}
// 문자열 배열로 정리 (보안)
$adminTemplates = array_values(array_filter(array_map('strval', $adminTemplates)));
$userTemplates = array_values(array_filter(array_map('strval', $userTemplates)));
$modules = array_values(array_filter(array_map('strval', $modules)));
$plugins = array_values(array_filter(array_map('strval', $plugins)));
try {
// 현재 상태 가져오기
$state = getInstallationState();
// selected_extensions 업데이트
$state['selected_extensions'] = [
'admin_templates' => $adminTemplates,
'user_templates' => $userTemplates,
'modules' => $modules,
'plugins' => $plugins,
];
// 확장 이름 매핑 저장 (설치 시 표시용)
$state['extension_names'] = $extensionNames;
// Step 4 완료 표시
$state['step_status']['4'] = 'completed';
// 다음 스텝으로 이동
$state['current_step'] = 5;
// 세션도 동기화 (Step 5로 이동 허용)
$_SESSION['installer_current_step'] = 5;
// 상태 저장
$saved = saveInstallationState($state);
if (!$saved) {
throw new Exception(lang('state_save_failed'));
}
// 로그 기록
addLog(lang('log_extensions_selected', [
'admin' => count($adminTemplates),
'user' => count($userTemplates),
'modules' => count($modules),
'plugins' => count($plugins),
]));
// 성공 응답
echo json_encode([
'success' => true,
'message' => lang('log_extensions_saved'),
'data' => [
'selected_extensions' => $state['selected_extensions'],
'next_step' => 5,
],
], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
} catch (Throwable $e) {
http_response_code(500);
echo json_encode([
'success' => false,
'error' => $e->getMessage(),
], JSON_UNESCAPED_UNICODE);
}
+315
View File
@@ -0,0 +1,315 @@
<?php
/**
* G7 인스톨러 - 확장 기능 스캔 API
*
* _bundled 디렉토리에서 템플릿, 모듈, 플러그인을 스캔하여 설치 가능한 확장 목록을 반환합니다.
* 모든 확장의 메타데이터는 JSON 매니페스트 파일(template.json, module.json, plugin.json)에서 읽습니다.
*
* @response {
* "success": true,
* "data": {
* "admin_templates": [...],
* "user_templates": [...],
* "modules": [...],
* "plugins": [...]
* }
* }
*/
// 기본 설정
header('Content-Type: application/json; charset=utf-8');
// 프로젝트 루트 경로
define('BASE_PATH', realpath(dirname(__DIR__, 3)) ?: dirname(__DIR__, 3));
// 세션 및 설정 포함 (Laravel autoload 없이 독립 실행)
// 참고: 이 API는 Laravel 부팅 없이 디렉토리 스캔만 수행
require_once dirname(__DIR__).'/includes/session.php';
require_once dirname(__DIR__).'/includes/config.php';
/**
* 템플릿 디렉토리 스캔
*
* _bundled 디렉토리에서 template.json을 읽어 템플릿 정보를 수집합니다.
*
* @return array ['admin' => [...], 'user' => [...]]
*/
function scanTemplates(): array
{
$templatesDir = BASE_PATH.'/templates/_bundled';
$result = [
'admin' => [],
'user' => [],
];
if (! is_dir($templatesDir)) {
return $result;
}
$dirs = scandir($templatesDir);
foreach ($dirs as $dir) {
if ($dir === '.' || $dir === '..') {
continue;
}
$templateJsonPath = $templatesDir.'/'.$dir.'/template.json';
if (! file_exists($templateJsonPath)) {
continue;
}
$content = @file_get_contents($templateJsonPath);
if ($content === false) {
continue;
}
$data = json_decode($content, true);
if (json_last_error() !== JSON_ERROR_NONE || empty($data)) {
continue;
}
// 필수 필드 확인
$identifier = $data['identifier'] ?? $dir;
$name = $data['name'] ?? ['ko' => $dir, 'en' => $dir];
$version = $data['version'] ?? '1.0.0';
$description = $data['description'] ?? ['ko' => '', 'en' => ''];
$type = $data['type'] ?? 'user'; // admin 또는 user
$author = $data['author']['name'] ?? $data['vendor'] ?? null;
// dependencies 처리: 객체 형태면 모듈/플러그인 키를 배열로 변환
$dependencies = extractDependenciesFromJson($data);
$templateInfo = [
'identifier' => $identifier,
'name' => $name,
'version' => $version,
'description' => $description,
'type' => $type,
'dependencies' => $dependencies,
'author' => $author,
'directory' => $dir,
];
if ($type === 'admin') {
$result['admin'][] = $templateInfo;
} else {
$result['user'][] = $templateInfo;
}
}
return $result;
}
/**
* 모듈 디렉토리 스캔
*
* _bundled 디렉토리에서 module.json을 읽어 모듈 정보를 수집합니다.
*
* @return array 모듈 목록
*/
function scanModules(): array
{
$modulesDir = BASE_PATH.'/modules/_bundled';
$result = [];
if (! is_dir($modulesDir)) {
return $result;
}
$dirs = scandir($modulesDir);
foreach ($dirs as $dir) {
if ($dir === '.' || $dir === '..') {
continue;
}
// module.json 매니페스트에서 메타데이터 읽기
$moduleJsonPath = $modulesDir.'/'.$dir.'/module.json';
if (! file_exists($moduleJsonPath)) {
// module.json이 없으면 module.php만으로 식별 (역호환)
$modulePhpPath = $modulesDir.'/'.$dir.'/module.php';
if (! file_exists($modulePhpPath)) {
continue;
}
// JSON이 없는 경우 기본값으로 등록
$result[] = [
'identifier' => $dir,
'name' => ['ko' => $dir, 'en' => $dir],
'version' => '1.0.0',
'description' => ['ko' => '', 'en' => ''],
'dependencies' => [],
'author' => null,
'directory' => $dir,
];
continue;
}
$content = @file_get_contents($moduleJsonPath);
if ($content === false) {
continue;
}
$data = json_decode($content, true);
if (json_last_error() !== JSON_ERROR_NONE || empty($data)) {
continue;
}
$dependencies = extractDependenciesFromJson($data);
$result[] = [
'identifier' => $data['identifier'] ?? $dir,
'name' => $data['name'] ?? ['ko' => $dir, 'en' => $dir],
'version' => $data['version'] ?? '1.0.0',
'description' => $data['description'] ?? ['ko' => '', 'en' => ''],
'dependencies' => $dependencies,
'author' => $data['vendor'] ?? null,
'directory' => $dir,
];
}
return $result;
}
/**
* 플러그인 디렉토리 스캔
*
* _bundled 디렉토리에서 plugin.json을 읽어 플러그인 정보를 수집합니다.
*
* @return array 플러그인 목록
*/
function scanPlugins(): array
{
$pluginsDir = BASE_PATH.'/plugins/_bundled';
$result = [];
if (! is_dir($pluginsDir)) {
return $result;
}
$dirs = scandir($pluginsDir);
foreach ($dirs as $dir) {
if ($dir === '.' || $dir === '..') {
continue;
}
// plugin.json 매니페스트에서 메타데이터 읽기
$pluginJsonPath = $pluginsDir.'/'.$dir.'/plugin.json';
if (! file_exists($pluginJsonPath)) {
// plugin.json이 없으면 plugin.php만으로 식별 (역호환)
$pluginPhpPath = $pluginsDir.'/'.$dir.'/plugin.php';
if (! file_exists($pluginPhpPath)) {
continue;
}
// JSON이 없는 경우 기본값으로 등록
$result[] = [
'identifier' => $dir,
'name' => ['ko' => $dir, 'en' => $dir],
'version' => '1.0.0',
'description' => ['ko' => '', 'en' => ''],
'dependencies' => [],
'author' => null,
'directory' => $dir,
];
continue;
}
$content = @file_get_contents($pluginJsonPath);
if ($content === false) {
continue;
}
$data = json_decode($content, true);
if (json_last_error() !== JSON_ERROR_NONE || empty($data)) {
continue;
}
$dependencies = extractDependenciesFromJson($data);
$result[] = [
'identifier' => $data['identifier'] ?? $dir,
'name' => $data['name'] ?? ['ko' => $dir, 'en' => $dir],
'version' => $data['version'] ?? '1.0.0',
'description' => $data['description'] ?? ['ko' => '', 'en' => ''],
'dependencies' => $dependencies,
'author' => $data['vendor'] ?? null,
'directory' => $dir,
];
}
return $result;
}
/**
* JSON 매니페스트에서 의존성 배열 추출
*
* dependencies 구조:
* - 객체 형태: { "modules": {"sirsoft-ecommerce": ">=1.0.0"}, "plugins": {...} }
* - 배열 형태: ["module1", "module2"]
*
* @param array $data JSON 매니페스트 데이터
* @return array 의존성 identifier 목록
*/
function extractDependenciesFromJson(array $data): array
{
$rawDeps = $data['dependencies'] ?? [];
$dependencies = [];
if (is_array($rawDeps)) {
if (isset($rawDeps['modules']) || isset($rawDeps['plugins'])) {
// 객체 형태: { modules: {...}, plugins: {...} }
foreach (['modules', 'plugins'] as $depType) {
if (! empty($rawDeps[$depType]) && is_array($rawDeps[$depType])) {
$dependencies = array_merge($dependencies, array_keys($rawDeps[$depType]));
}
}
} else {
// 배열 형태: ['module1', 'module2']
$dependencies = array_values($rawDeps);
}
}
return $dependencies;
}
// ===== 메인 실행 =====
try {
// 템플릿 스캔
$templates = scanTemplates();
// 모듈 스캔
$modules = scanModules();
// 플러그인 스캔
$plugins = scanPlugins();
// Admin 템플릿 필수 검증
if (empty($templates['admin'])) {
http_response_code(400);
echo json_encode([
'success' => false,
'error' => 'no_admin_template',
'error_message' => 'Admin template is required but not found. Please ensure at least one admin template exists in the templates/_bundled directory.',
], JSON_UNESCAPED_UNICODE);
exit;
}
// 결과 반환
echo json_encode([
'success' => true,
'data' => [
'admin_templates' => $templates['admin'],
'user_templates' => $templates['user'],
'modules' => $modules,
'plugins' => $plugins,
],
], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
} catch (Throwable $e) {
http_response_code(500);
echo json_encode([
'success' => false,
'error' => $e->getMessage(),
], JSON_UNESCAPED_UNICODE);
}
+349
View File
@@ -0,0 +1,349 @@
<?php
/**
* G7 인스톨러 - 설치 상태 관리 통합 API
*
* 설치 상태 조회, 초기화, 중단 기능을 하나의 API로 통합
*
* 엔드포인트:
* - GET ?action=get : 현재 설치 상태 조회 (action 생략 시 기본값)
* - POST ?action=reset : 설치 상태 초기화 (Step 3로 이동)
* - POST ?action=abort : 설치 중단 (현재 작업만 롤백)
*/
/**
* 설치 상태 관리 API 클래스
*/
class StateManagementApi
{
/**
* 요청 처리 메인 메서드
*/
public function handleRequest(): void
{
// JSON 헤더 설정
$this->setJsonHeaders();
// HTTP 메서드 및 action 파라미터 확인
$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? ($method === 'GET' ? 'get' : null);
try {
// action에 따라 적절한 메서드 호출
match ($action) {
'get' => $this->getState(),
'reset' => $this->resetState(),
'abort' => $this->abortInstallation(),
default => $this->error400('Invalid action parameter'),
};
} catch (Exception $e) {
$this->error500($e);
}
}
/**
* JSON 응답 헤더 설정
*/
private function setJsonHeaders(): void
{
header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');
}
/**
* GET ?action=get
* 현재 설치 상태 조회
*
* JavaScript 폴링(1초 간격)으로 호출되어 실시간 진행 상황을 업데이트합니다.
*/
private function getState(): void
{
// GET 메서드만 허용
if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
http_response_code(405);
echo json_encode([
'error' => 'Method Not Allowed',
'message' => lang('error_get_method_required'),
], JSON_UNESCAPED_UNICODE);
exit;
}
// 현재 설치 상태 조회
$state = getInstallationState();
// installation_status 값을 status로 매핑
$status = 'pending';
if (isset($state['installation_status'])) {
switch ($state['installation_status']) {
case 'not_started':
case 'ready': // ready도 pending으로 매핑 (설치 대기 상태)
$status = 'pending';
break;
case 'running':
$status = 'running';
break;
case 'completed':
$status = 'completed';
break;
case 'failed':
$status = 'failed';
break;
case 'aborted':
$status = 'aborted';
break;
default:
$status = $state['installation_status'];
}
}
// 로그 파일에서 로그 읽기
$logs = getInstallationLogs();
// API 응답 형식으로 변환
$response = [
'status' => $status,
'current_step' => $state['current_step'] ?? 0,
'current_task' => $state['current_task'] ?? null,
// current_task_name은 제거 (프론트엔드에서 task ID로 번역)
'completed_tasks' => $state['completed_tasks'] ?? [],
'logs' => $logs,
'error' => $state['error'] ?? null,
'last_updated' => $state['last_updated'] ?? null,
// 실패 정보 (새로고침 후에도 표시용)
'failed_task' => $state['failed_task'] ?? null,
// failed_task_name은 제거 (프론트엔드에서 task ID로 번역)
'error_message_key' => $state['error_message_key'] ?? null,
'error_detail' => $state['error_detail'] ?? null,
'rollback_failure' => $state['rollback_failure'] ?? null,
'manual_commands' => $state['manual_commands'] ?? null,
];
// JSON 응답 반환
echo json_encode($response, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
}
/**
* POST ?action=reset
* 설치 상태 초기화 및 적절한 Step으로 이동
*
* 설치 상태를 초기화하여 설정 페이지로 돌아갈 수 있도록 합니다.
* DB 롤백은 수행하지 않습니다 (사용자가 수동으로 DB 정리 필요).
* (마이그레이션 실패 시 자동 롤백은 install-worker.php에서 처리)
*/
private function resetState(): void
{
// POST 메서드만 허용
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
echo json_encode([
'success' => false,
'message' => 'Only POST method is allowed',
], JSON_UNESCAPED_UNICODE);
exit;
}
// 현재 상태 조회
$state = getInstallationState();
// 항상 Step 4 (확장 선택)로 이동
$targetStep = 4;
addLog(lang('state_reset_requested'));
addLog(lang('state_reset_db_notice'));
// 상태 초기화 (DB 롤백 없이)
$state['current_step'] = $targetStep;
$_SESSION['installer_current_step'] = $targetStep;
$state['step_status'][$targetStep] = 'pending';
$state['installation_status'] = 'not_started';
$state['completed_tasks'] = [];
$state['current_task'] = null;
$state['error'] = null;
$state['failed_task'] = null;
$state['failed_task_target'] = null;
$state['error_message_key'] = null;
$state['error_detail'] = null;
$state['rollback_failure'] = null;
$state['manual_commands'] = null;
$state['last_updated'] = gmdate('Y-m-d\TH:i:s\Z');
// 상태 저장
$saved = saveInstallationState($state);
if (!$saved) {
throw new Exception(lang('state_save_failed'));
}
addLog(lang('state_reset_completed', ['step' => $targetStep]));
// 성공 응답
http_response_code(200);
echo json_encode([
'success' => true,
'message' => lang('state_reset_completed', ['step' => $targetStep]),
'target_step' => $targetStep,
], JSON_UNESCAPED_UNICODE);
}
/**
* POST ?action=abort
* 설치 중단 (현재 작업만 롤백)
*
* 사용자가 명시적으로 설치 중단 버튼을 클릭했을 때 호출됩니다.
* 현재 진행 중인 작업만 롤백하고, 완료된 작업은 유지합니다.
*/
private function abortInstallation(): void
{
// POST 메서드만 허용
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
echo json_encode([
'success' => false,
'message' => lang('api_method_not_allowed'),
]);
exit;
}
addLog(lang('abort_api_requested'));
// 설치 상태 가져오기
$state = getInstallationState();
// 디버그: 현재 state 상태 로깅
addLog(lang('abort_api_current_status', ['status' => $state['installation_status'] ?? 'null']));
addLog(lang('abort_api_current_task', ['task' => $state['current_task'] ?? 'null']));
addLog(lang('abort_api_completed_count', ['count' => count($state['completed_tasks'] ?? [])]));
// 설치가 이미 완료된 경우
if (isset($state['installation_status']) && $state['installation_status'] === 'completed') {
addLog(lang('abort_api_already_completed'));
echo json_encode([
'success' => false,
'message' => lang('abort_api_already_completed'),
]);
exit;
}
// 이미 중단된 경우 - 멱등성 보장 (재진입 시 400 에러 방지)
if (isset($state['installation_status']) && $state['installation_status'] === 'aborted') {
addLog(lang('abort_api_already_aborted'));
echo json_encode([
'success' => true,
'message' => lang('abort_api_already_aborted'),
]);
exit;
}
// 설치가 진행 중이 아닌 경우
if (! isset($state['installation_status']) || $state['installation_status'] !== 'running') {
addLog(lang('abort_api_not_running', ['status' => $state['installation_status'] ?? 'null']));
echo json_encode([
'success' => false,
'message' => lang('abort_api_not_running', ['status' => $state['installation_status'] ?? 'null']),
]);
exit;
}
addLog(lang('abort_user_requested'));
// 현재 진행 중인 작업만 롤백 (완료된 작업은 유지)
// 결과는 rollbackCurrentTask()에서 로깅됨
$rollbackResult = rollbackCurrentTask($state);
// 설치 상태를 'aborted'로 변경
addLog(lang('abort_api_status_change'));
$state['installation_status'] = 'aborted';
// current_step은 5를 유지 (중단된 화면을 보여주기 위해 - Step 5 = Installation)
$state['current_task'] = null;
// completed_tasks는 유지 (이미 완료된 작업은 롤백하지 않음)
$state['aborted_at'] = date('Y-m-d H:i:s');
$state['abort_reason'] = 'User requested';
// 롤백 실패 정보 저장 (새로고침 후에도 표시용)
if (isset($rollbackResult['success']) && !$rollbackResult['success']) {
$state['rollback_failure'] = [
'task' => $rollbackResult['task'] ?? null,
'message' => $rollbackResult['message'] ?? null,
'message_key' => 'failed_rollback_manual_cleanup',
'detail_key' => 'failed_rollback_manual_cleanup_detail',
];
}
// 세션도 Step 5를 유지 (중단 화면 표시)
$saveResult = saveInstallationState($state);
addLog(lang('abort_api_save_result', ['result' => $saveResult ? 'success' : 'failed']));
// 저장 후 실제 state.json 확인
$verifyState = getInstallationState();
addLog(lang('abort_api_verify_status', ['status' => $verifyState['installation_status'] ?? 'null']));
addLog(lang('abort_installation_stopped'));
// 성공 응답 (리다이렉트 없음 - 현재 Step 5 유지)
echo json_encode([
'success' => true,
'message' => lang('abort_installation_stopped'),
]);
}
/**
* 400 Bad Request 응답
*/
private function error400(string $message): void
{
http_response_code(400);
echo json_encode([
'success' => false,
'error' => 'Bad Request',
'message' => $message,
], JSON_UNESCAPED_UNICODE);
exit;
}
/**
* 500 Internal Server Error 응답
*/
private function error500(Exception $e): void
{
// 에러 로깅
if (function_exists('logInstallationError')) {
logInstallationError(lang('error_state_management'), $e);
} elseif (function_exists('addLog')) {
addLog(lang('error_log_prefix', ['error' => $e->getMessage()]));
}
// 에러 응답
http_response_code(500);
echo json_encode([
'success' => false,
'error' => 'Internal Server Error',
'message' => $e->getMessage(),
], JSON_UNESCAPED_UNICODE);
exit;
}
}
// ========================================
// 실행 부분
// ========================================
// 필수 파일 로드 (config.php가 BASE_PATH를 정의함)
require_once __DIR__.'/../includes/config.php';
require_once __DIR__.'/../includes/session.php';
require_once __DIR__.'/../includes/functions.php';
require_once __DIR__.'/../includes/installer-state.php';
// 롤백 함수 로드 (reset, abort 액션에서 필요)
require_once __DIR__.'/rollback-functions.php';
// 다국어 로드
$currentLang = getCurrentLanguage();
$translations = loadTranslations($currentLang);
// API 인스턴스 생성 및 요청 처리
$api = new StateManagementApi;
$api->handleRequest();