v7.0.0-beta.2 release

This commit is contained in:
HeuJung committed 2026-04-20 20:37:49 +09:00
1 parent 6595fd0eb5
commit fa8eba7a0d
1165 files changed
+107118 -762127

No files matched your search

+44 -3
View File
@@ -162,6 +162,14 @@ class ValidationApi
$message = lang('success_db_write_connected');
}
// 기존 테이블 감지 (Write DB만 수행 — 이슈 #244 대응)
// 사용자가 입력한 db_prefix를 g7 시그니처에 적용하여 정확히 비교
$existingTables = null;
if (!$isReadDb) {
$tablePrefix = (string) ($input['db_prefix'] ?? 'g7_');
$existingTables = checkExistingTables($pdo, $database, $tablePrefix);
}
// 성공 응답
echo json_encode([
'success' => true,
@@ -172,6 +180,7 @@ class ValidationApi
'found' => $privileges['found'],
'required' => $privileges['required'],
],
'existing_tables' => $existingTables,
], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
} catch (PDOException $e) {
// 연결 실패 플래그
@@ -340,6 +349,7 @@ class ValidationApi
'relative_path' => './'.$dir,
'exists' => $result['exists'],
'writable' => $result['writable'],
'readable' => $result['readable'],
'permissions' => $result['permissions'],
'owner' => $result['owner'],
'group' => $result['group'],
@@ -381,6 +391,7 @@ class ValidationApi
'.env' => getEnvCopyCommand($basePath),
];
$webServerUser = getWebServerUser();
$files = [];
$allPassed = true;
$hasNotWritable = false;
@@ -395,12 +406,29 @@ class ValidationApi
$allPassed = false;
}
// 권한 비트/소유자 정보 수집 (ownership_mismatch 판별용)
$permissions = 'N/A';
$permsOctal = 0;
$owner = null;
if ($exists) {
$perms = fileperms($fullPath);
$permissions = substr(sprintf('%o', $perms), -3);
$permsOctal = octdec($permissions);
$owner = getFileOwnerName($fullPath);
}
// 에러 타입 결정
// ownership_mismatch: 파일이 존재하고 권한이 0644 이상인데도 쓰기 불가
// → 소유자와 웹서버 실행 사용자 불일치
$errorType = null;
if (! $exists) {
$errorType = 'not_exists';
} elseif (! $writable) {
$errorType = 'not_writable';
if ($permsOctal >= 0644 && $webServerUser && $owner && $owner !== $webServerUser) {
$errorType = 'ownership_mismatch';
} else {
$errorType = 'not_writable';
}
$hasNotWritable = true;
}
@@ -409,18 +437,31 @@ class ValidationApi
'writable' => $writable,
'passed' => $passed,
'error_type' => $errorType,
'permissions' => $permissions,
'owner' => $owner,
'web_server_user' => $webServerUser,
'command' => $createCommands[$name],
];
}
// base_path 소유자 정보 — .env 파일 생성 시 chgrp 포함 여부 판단용
// 프로젝트 루트 소유자가 웹서버 실행 사용자와 다른 경우, 생성 직후 ownership_mismatch가
// 재현되므로 복사 명령 자체에 chgrp + chmod 664를 미리 포함시키기 위함
$basePathOwner = function_exists('posix_getpwuid') && is_dir($basePath)
? (posix_getpwuid(fileowner($basePath))['name'] ?? null)
: null;
$basePathOwnerMatchesWebUser = $basePathOwner && $webServerUser && $basePathOwner === $webServerUser;
return [
'required' => true,
'files' => $files,
'all_passed' => $allPassed,
'has_not_writable' => $hasNotWritable,
'web_server_group' => getWebServerGroup() ?? getWebServerUser() ?? 'www-data',
'web_server_user' => getWebServerUser(),
'web_server_group' => getWebServerGroup() ?? $webServerUser ?? 'www-data',
'web_server_user' => $webServerUser,
'base_path' => $basePath,
'base_path_owner' => $basePathOwner,
'base_path_owner_matches_web_user' => $basePathOwnerMatchesWebUser,
'relative_base_path' => '.',
'message' => $allPassed
? lang('success_required_files')
+108 -5
View File
@@ -112,6 +112,42 @@ try {
exit;
}
/**
* 설치 모드 수신 (sse | polling, 기본 sse)
*
* POST 본문(JSON 또는 form)에서 installation_mode 필드로 전달됩니다.
* - sse: 기존 방식 (install-worker.php GET + EventSource)
* - polling: install-process.php 응답 완료 후 인라인으로 runInstallationTasks() 실행,
* 프론트엔드는 state-management.php를 1초 간격으로 폴링
*/
$requestBody = [];
$rawInput = file_get_contents('php://input');
if (!empty($rawInput)) {
$decoded = json_decode($rawInput, true);
if (is_array($decoded)) {
$requestBody = $decoded;
}
}
$installationMode = $requestBody['installation_mode']
?? $_POST['installation_mode']
?? 'sse';
if (!in_array($installationMode, ['sse', 'polling'], true)) {
$installationMode = 'sse';
}
/**
* 기존 DB 처리 액션 수신 (skip | drop_tables, 기본 skip)
*
* 이슈 #244: Step 3에서 기존 DB 감지 후 사용자가 "강제 진행" 선택 시 전달.
*/
$existingDbAction = $requestBody['existing_db_action']
?? $_POST['existing_db_action']
?? 'skip';
if (!in_array($existingDbAction, ['skip', 'drop_tables'], true)) {
$existingDbAction = 'skip';
}
/**
* 현재 상태 가져오기
*/
@@ -134,6 +170,8 @@ try {
$state['current_task'] = null;
$state['config'] = $config;
$state['error'] = null;
$state['installation_mode'] = $installationMode;
$state['existing_db_action'] = $existingDbAction;
/**
* 로그 파일 초기화 (재시도가 아닌 경우에만)
@@ -163,17 +201,82 @@ try {
addLog(lang('log_installation_config_saved'));
/**
* 클라이언트에 즉시 응답 전송
*
* JavaScript에서 이 응답을 받은 후 install-worker.php로 SSE 연결을 시작합니다.
* 응답 JSON 준비 (echo 이전에 미리 문자열화하여 Content-Length 계산용)
*/
http_response_code(200);
echo json_encode([
$responseJson = json_encode([
'success' => true,
'status' => 'started',
'message' => lang('success_installation_started'),
'installation_mode' => $installationMode,
], JSON_UNESCAPED_UNICODE);
/**
* 폴링 모드: 응답을 완전히 종료한 후 워커 인라인 실행
*
* 핵심 과제: 브라우저의 `await fetch(install-process.php)`가 응답 완료를
* 인식해야 JS가 폴링 시작 코드로 진행 가능하다. Apache mod_php에서는
* ob_end_flush() + flush() 만으로는 HTTP 연결이 끊기지 않아, 워커가
* 인라인으로 10분간 실행되는 동안 브라우저 fetch 가 대기하게 된다.
*
* 해결:
* - PHP-FPM: fastcgi_finish_request() — 응답 즉시 종료
* - mod_php 폴백: Content-Length + Connection: close 헤더 명시 →
* 브라우저가 지정된 바이트 수만 읽고 연결을 닫음
*/
if ($installationMode === 'polling') {
ignore_user_abort(true);
// CRITICAL: 세션 잠금 해제 — 워커가 인라인으로 10분간 실행되는 동안
// 세션 파일이 잠겨있으면 폴링용 state-management.php?action=get 요청이
// session_start()에서 대기하여 진행 상황을 전혀 확인할 수 없게 됨.
//
// task-runner의 완료 시점 $_SESSION['installer_current_step']=5 쓰기는
// 세션이 닫힌 후에는 효과 없으므로, 미리 여기서 저장한다.
if (session_status() === PHP_SESSION_ACTIVE) {
$_SESSION['installer_current_step'] = 5;
session_write_close();
}
// 기존 출력 버퍼 전부 비우기 (헤더 설정 전)
while (ob_get_level() > 0) {
@ob_end_clean();
}
// 응답 헤더 — 브라우저가 응답 완료를 인식하도록 Content-Length + Connection: close
http_response_code(200);
header('Content-Type: application/json; charset=UTF-8');
header('Content-Length: ' . strlen($responseJson));
header('Connection: close');
echo $responseJson;
// 출력 플러시 + PHP-FPM 지원 시 연결 종료
@flush();
if (function_exists('fastcgi_finish_request')) {
@fastcgi_finish_request();
}
// 워커 타임아웃 설정 (SSE 모드와 동일)
@set_time_limit(600);
@ini_set('display_errors', '0');
error_reporting(E_ALL);
addLog('=== Install Worker Polling Started ===');
addLog('Client IP: ' . ($_SERVER['REMOTE_ADDR'] ?? 'unknown'));
// 폴링 모드 — NullEmitter 등록 후 task runner 실행
require_once __DIR__ . '/../includes/progress-emitter.php';
require_once __DIR__ . '/../includes/task-runner.php';
setProgressEmitter(new NullEmitter());
runInstallationTasks();
exit;
}
// SSE 모드: 일반 JSON 응답
http_response_code(200);
echo $responseJson;
} catch (Exception $e) {
/**
* 에러 처리
File diff suppressed because it is too large. Load diff
+60 -3
View File
@@ -78,6 +78,7 @@ function scanTemplates(): array
// dependencies 처리: 객체 형태면 모듈/플러그인 키를 배열로 변환
$dependencies = extractDependenciesFromJson($data);
$dependenciesDetailed = extractDependenciesDetailedFromJson($data);
$templateInfo = [
'identifier' => $identifier,
@@ -86,6 +87,7 @@ function scanTemplates(): array
'description' => $description,
'type' => $type,
'dependencies' => $dependencies,
'dependencies_detailed' => $dependenciesDetailed,
'author' => $author,
'directory' => $dir,
];
@@ -155,6 +157,7 @@ function scanModules(): array
}
$dependencies = extractDependenciesFromJson($data);
$dependenciesDetailed = extractDependenciesDetailedFromJson($data);
$result[] = [
'identifier' => $data['identifier'] ?? $dir,
@@ -162,6 +165,7 @@ function scanModules(): array
'version' => $data['version'] ?? '1.0.0',
'description' => $data['description'] ?? ['ko' => '', 'en' => ''],
'dependencies' => $dependencies,
'dependencies_detailed' => $dependenciesDetailed,
'author' => $data['vendor'] ?? null,
'directory' => $dir,
];
@@ -225,6 +229,7 @@ function scanPlugins(): array
}
$dependencies = extractDependenciesFromJson($data);
$dependenciesDetailed = extractDependenciesDetailedFromJson($data);
$result[] = [
'identifier' => $data['identifier'] ?? $dir,
@@ -232,6 +237,7 @@ function scanPlugins(): array
'version' => $data['version'] ?? '1.0.0',
'description' => $data['description'] ?? ['ko' => '', 'en' => ''],
'dependencies' => $dependencies,
'dependencies_detailed' => $dependenciesDetailed,
'author' => $data['vendor'] ?? null,
'directory' => $dir,
];
@@ -241,7 +247,7 @@ function scanPlugins(): array
}
/**
* JSON 매니페스트에서 의존성 배열 추출
* JSON 매니페스트에서 의존성 identifier 배열 추출 (하위 호환 유지).
*
* dependencies 구조:
* - 객체 형태: { "modules": {"sirsoft-ecommerce": ">=1.0.0"}, "plugins": {...} }
@@ -257,14 +263,12 @@ function extractDependenciesFromJson(array $data): array
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);
}
}
@@ -272,6 +276,59 @@ function extractDependenciesFromJson(array $data): array
return $dependencies;
}
/**
* JSON 매니페스트에서 타입+버전이 보존된 의존성 상세 배열 추출.
*
* 반환: [['type' => 'modules'|'plugins', 'identifier' => '...', 'version' => '>=0.1.1'], ...]
* 프론트엔드 validateExtensionSelection()에서 의존성 그래프 검증에 사용합니다.
*
* @param array $data JSON 매니페스트 데이터
* @return array 의존성 상세 배열
*/
function extractDependenciesDetailedFromJson(array $data): array
{
$rawDeps = $data['dependencies'] ?? [];
$detailed = [];
if (!is_array($rawDeps)) {
return $detailed;
}
if (isset($rawDeps['modules']) || isset($rawDeps['plugins'])) {
foreach (['modules', 'plugins'] as $depType) {
if (! empty($rawDeps[$depType]) && is_array($rawDeps[$depType])) {
foreach ($rawDeps[$depType] as $identifier => $version) {
if (is_int($identifier)) {
// 배열 원소: 값이 identifier
$detailed[] = [
'type' => $depType,
'identifier' => (string) $version,
'version' => '*',
];
} else {
$detailed[] = [
'type' => $depType,
'identifier' => (string) $identifier,
'version' => is_string($version) ? $version : '*',
];
}
}
}
}
} else {
// 레거시 배열 형태 — 타입을 알 수 없으므로 'unknown'으로 표기
foreach ($rawDeps as $identifier) {
$detailed[] = [
'type' => 'unknown',
'identifier' => (string) $identifier,
'version' => '*',
];
}
}
return $detailed;
}
// ===== 메인 실행 =====
try {
+21 -5
View File
@@ -70,12 +70,22 @@ class StateManagementApi
exit;
}
// state.json 파일 실제 존재 여부 (getInstallationState는 부재 시 DEFAULT_INSTALLATION_STATE를 반환하므로
// isset($state['installation_status']) 로는 "기본 상태"와 "실제 파일 상태"를 구분할 수 없다)
$stateFileExists = file_exists(STATE_PATH);
$installedFlagPath = BASE_PATH . '/storage/app/g7_installed';
// 현재 설치 상태 조회
$state = getInstallationState();
// installation_status 값을 status로 매핑
$status = 'pending';
if (isset($state['installation_status'])) {
if (!$stateFileExists && file_exists($installedFlagPath)) {
// state.json 삭제 + g7_installed 플래그 존재 → 설치 완료 후 정리된 상태
// 폴링이 완료 시점을 놓치면 이후 주기에서 이 분기로 completed 전환
$status = 'completed';
} elseif ($stateFileExists && isset($state['installation_status'])) {
switch ($state['installation_status']) {
case 'not_started':
case 'ready': // ready도 pending으로 매핑 (설치 대기 상태)
@@ -98,27 +108,33 @@ class StateManagementApi
}
}
// 로그 파일에서 로그 읽기
$logs = getInstallationLogs();
// 폴링 모드 증분 조회 지원 (?log_offset=N)
$logOffset = isset($_GET['log_offset']) ? max(0, (int) $_GET['log_offset']) : 0;
// 로그 파일에서 로그 읽기 (offset 이후만)
$logs = getInstallationLogs($logOffset);
$logTotal = getInstallationLogCount();
// 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,
'log_total' => $logTotal,
'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,
// SSE/폴링 듀얼 모드 지원
'installation_mode' => $state['installation_mode'] ?? 'sse',
];
// JSON 응답 반환