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 응답 반환
+526
View File
@@ -1689,6 +1689,75 @@ hr {
color: #991b1b;
}
/* 기존 DB 테이블 감지 인라인 카드 (#244)
.test-result .alert 가 display:flex 라 카드 자식이 가로로 정렬되므로
block 으로 오버라이드하고 카드 내부에 자체 spacing 적용 */
.test-result .db-existing-tables-card {
display: block;
align-items: initial;
gap: 0;
margin-top: var(--spacing-md);
padding: var(--spacing-lg);
background: linear-gradient(135deg, #fffbeb 0%, #fef3c7 100%);
border: 1px solid #fde68a;
border-radius: var(--border-radius-lg);
color: #78350f;
box-shadow: var(--shadow-sm);
}
.test-result .db-existing-tables-card .db-existing-header {
font-size: var(--font-size-lg);
font-weight: var(--font-weight-semibold);
margin-bottom: var(--spacing-sm);
}
.test-result .db-existing-tables-card .db-existing-desc {
margin: 0 0 var(--spacing-md) 0;
line-height: var(--line-height-relaxed);
}
.test-result .db-existing-tables-card .db-existing-tables-label,
.test-result .db-existing-tables-card .db-existing-backup-label {
margin: var(--spacing-md) 0 var(--spacing-xs) 0;
font-weight: var(--font-weight-semibold);
}
.test-result .db-existing-tables-card .db-existing-tables-list {
background: rgba(255, 255, 255, 0.6);
border: 1px solid #fde68a;
border-radius: var(--border-radius);
padding: var(--spacing-sm) var(--spacing-md);
margin: 0 0 var(--spacing-sm) 0;
font-family: var(--font-family-mono, monospace);
font-size: var(--font-size-sm);
line-height: var(--line-height-relaxed);
white-space: pre-wrap;
word-break: break-all;
max-height: 8rem;
overflow-y: auto;
}
.test-result .db-existing-tables-card .code-box {
margin: 0 0 var(--spacing-md) 0;
}
.test-result .db-existing-tables-card .db-backup-confirm-checkbox {
display: flex;
align-items: center;
gap: var(--spacing-sm);
margin-top: var(--spacing-md);
padding: var(--spacing-sm) var(--spacing-md);
background: rgba(255, 255, 255, 0.5);
border: 1px solid #fde68a;
border-radius: var(--border-radius);
cursor: pointer;
font-weight: var(--font-weight-medium);
}
.test-result .db-existing-tables-card .db-backup-confirm-checkbox input[type="checkbox"] {
cursor: pointer;
}
/* 다크모드 테스트 결과 (Step 3: DB/PHP 연결 테스트) */
[data-theme="dark"] .test-result .alert-success {
background: linear-gradient(135deg, rgba(52, 211, 153, 0.1) 0%, rgba(52, 211, 153, 0.15) 100%);
@@ -3707,4 +3776,461 @@ body {
.selection-summary .summary-count {
font-size: var(--font-size-xl);
}
}
/* ============================================================
설치 진행 방식 선택 (SSE / 폴링)
============================================================ */
.installation-mode-card {
margin-bottom: var(--spacing-md);
}
.installation-mode-options {
display: flex;
flex-direction: column;
gap: var(--spacing-sm);
}
.installation-mode-option {
display: flex;
align-items: flex-start;
gap: var(--spacing-sm);
padding: var(--spacing-md);
border: 1px solid var(--border-color, #d1d5db);
border-radius: var(--radius-md, 8px);
cursor: pointer;
transition: border-color 0.15s ease, background-color 0.15s ease;
}
.installation-mode-option:hover {
border-color: var(--color-primary, #3b82f6);
background-color: var(--bg-hover, #f9fafb);
}
.installation-mode-option input[type="radio"] {
margin-top: 4px;
flex-shrink: 0;
}
.installation-mode-option input[type="radio"]:checked + .installation-mode-text strong {
color: var(--color-primary, #3b82f6);
}
.installation-mode-option:has(input[type="radio"]:checked) {
border-color: var(--color-primary, #3b82f6);
background-color: var(--bg-selected, #eff6ff);
}
.installation-mode-text {
display: flex;
flex-direction: column;
gap: 4px;
}
.installation-mode-text strong {
font-size: var(--font-size-base);
color: var(--text-primary);
}
.installation-mode-desc {
font-size: var(--font-size-sm);
color: var(--text-secondary, #6b7280);
line-height: 1.4;
}
@media (prefers-color-scheme: dark) {
.installation-mode-option {
border-color: var(--border-color-dark, #374151);
}
.installation-mode-option:has(input[type="radio"]:checked) {
background-color: var(--bg-selected-dark, #1e3a8a33);
}
}
/* ============================================================
Step 3: 기존 DB 테이블 감지 배지 + 모달
============================================================ */
.db-existing-tables-badge {
margin-top: var(--spacing-sm);
cursor: pointer;
user-select: none;
}
.db-existing-tables-badge:hover {
opacity: 0.9;
}
.modal-existing-tables {
display: none;
position: fixed;
inset: 0;
z-index: 10000;
}
.modal-existing-tables.modal-open {
display: block;
}
.modal-existing-tables .modal-backdrop {
position: fixed;
inset: 0;
background: rgba(0, 0, 0, 0.5);
}
.modal-existing-tables .modal-content {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: var(--bg-card, #fff);
padding: var(--spacing-lg, 24px);
border-radius: var(--radius-md, 8px);
max-width: 600px;
width: 90%;
max-height: 85vh;
overflow-y: auto;
box-shadow: 0 10px 25px rgba(0, 0, 0, 0.3);
}
.modal-existing-tables .modal-title {
margin: 0 0 var(--spacing-md) 0;
font-size: var(--font-size-lg);
color: var(--color-warning, #d97706);
}
.modal-existing-tables .modal-body {
display: flex;
flex-direction: column;
gap: var(--spacing-sm);
}
.modal-existing-tables .modal-tables-label,
.modal-existing-tables .modal-backup-label {
margin: var(--spacing-sm) 0 4px 0;
font-weight: 600;
font-size: var(--font-size-sm);
}
.modal-existing-tables .modal-tables-list {
padding: var(--spacing-sm);
background: var(--bg-muted, #f3f4f6);
border-radius: var(--radius-sm, 4px);
font-size: var(--font-size-xs);
white-space: pre-wrap;
word-break: break-all;
max-height: 150px;
overflow-y: auto;
}
.modal-existing-tables .modal-confirm-checkbox {
display: flex;
gap: var(--spacing-sm);
align-items: flex-start;
margin-top: var(--spacing-sm);
cursor: pointer;
}
.modal-existing-tables .modal-actions {
display: flex;
justify-content: flex-end;
gap: var(--spacing-sm);
margin-top: var(--spacing-lg);
}
.btn-danger {
background-color: var(--color-danger, #dc2626);
color: #fff;
}
.btn-danger:hover:not(:disabled) {
background-color: var(--color-danger-hover, #b91c1c);
}
.btn-danger:disabled {
opacity: 0.5;
cursor: not-allowed;
}
/* Step 4 의존성 경고 */
.dependency-warning-list {
margin: var(--spacing-sm) 0;
padding-left: var(--spacing-lg);
}
.dependency-warning-list li {
margin-bottom: 4px;
font-size: var(--font-size-sm);
}
/* Step 4 자동 선택된 확장 카드 */
.extension-card.dep-auto-selected.selected {
border-color: #d97706;
background-color: rgba(217, 119, 6, 0.08);
}
.extension-card.dep-auto-selected.selected .extension-card-icon {
background-color: #d97706;
color: white;
}
.extension-card.dep-auto-selected.selected .extension-card-select {
color: #d97706;
}
.extension-card.dep-auto-selected.selected .extension-card-footer {
border-top-color: rgba(217, 119, 6, 0.2);
}
/* 자동 선택 배지 */
.dep-auto-badge {
display: inline-flex;
align-items: center;
gap: 4px;
margin-top: 4px;
padding: 2px 8px;
font-size: 0.7rem;
font-weight: 600;
color: #92400e;
background-color: rgba(217, 119, 6, 0.12);
border: 1px solid rgba(217, 119, 6, 0.25);
border-radius: 4px;
line-height: 1.4;
}
.dep-auto-badge i {
font-size: 0.6rem;
}
.dep-auto-badge-owner {
font-weight: 400;
opacity: 0.8;
}
/* 버전 충돌 표시 */
.dep-version-conflict {
color: var(--color-danger, #dc2626);
font-weight: 600;
font-size: 0.8em;
}
/* 의존성 잠금 토스트 */
.dep-lock-toast {
position: fixed;
bottom: 24px;
left: 50%;
transform: translateX(-50%) translateY(20px);
padding: 12px 20px;
background-color: #1e293b;
color: #f8fafc;
border-radius: 8px;
font-size: var(--font-size-sm);
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.2);
z-index: 10000;
opacity: 0;
transition: opacity 0.3s ease, transform 0.3s ease;
max-width: 90vw;
text-align: center;
}
.dep-lock-toast i {
margin-right: 6px;
color: #fbbf24;
}
.dep-lock-toast.show {
opacity: 1;
transform: translateX(-50%) translateY(0);
}
/* 다크 모드 */
[data-theme="dark"] .extension-card.dep-auto-selected.selected {
border-color: #f59e0b;
background-color: rgba(245, 158, 11, 0.12);
}
[data-theme="dark"] .extension-card.dep-auto-selected.selected .extension-card-icon {
background-color: #f59e0b;
}
[data-theme="dark"] .dep-auto-badge {
color: #fcd34d;
background-color: rgba(245, 158, 11, 0.15);
border-color: rgba(245, 158, 11, 0.3);
}
[data-theme="dark"] .dep-lock-toast {
background-color: #334155;
}
/* ========================================================================
Step 3 Vendor 설치 방식 카드
======================================================================== */
.vendor-mode-cards {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
gap: var(--spacing-md);
}
.vendor-mode-card {
position: relative;
display: flex;
flex-direction: column;
gap: var(--spacing-sm);
padding: var(--spacing-md);
background-color: var(--bg-color);
border: 2px solid var(--border-color);
border-radius: var(--border-radius-lg);
cursor: pointer;
transition: all 0.2s ease;
user-select: none;
}
.vendor-mode-card:hover:not(.disabled) {
border-color: var(--primary-color);
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}
.vendor-mode-card.selected {
border-color: var(--primary-color);
background-color: rgba(59, 130, 246, 0.08);
}
.vendor-mode-card.disabled {
cursor: not-allowed;
opacity: 0.55;
background-color: var(--bg-gray, rgba(0, 0, 0, 0.03));
}
.vendor-mode-card.disabled:hover {
border-color: var(--border-color);
box-shadow: none;
}
/* 네이티브 라디오 버튼 숨김 (카드 전체가 클릭 타겟) */
.vendor-mode-card-input {
position: absolute;
opacity: 0;
pointer-events: none;
width: 0;
height: 0;
}
/* 헤더 — 아이콘 + 제목 + 체크 아이콘 */
.vendor-mode-card-header {
display: flex;
align-items: flex-start;
gap: var(--spacing-sm);
}
.vendor-mode-card-icon {
width: 40px;
height: 40px;
display: flex;
align-items: center;
justify-content: center;
background-color: var(--bg-gray, rgba(0, 0, 0, 0.05));
border-radius: var(--border-radius);
flex-shrink: 0;
color: var(--text-muted);
font-size: 1.25rem;
transition: all 0.2s ease;
}
.vendor-mode-card.selected .vendor-mode-card-icon {
background-color: var(--primary-color);
color: white;
}
.vendor-mode-card-title-wrapper {
flex: 1;
min-width: 0;
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 6px;
}
.vendor-mode-card-title {
margin: 0;
font-size: var(--font-size-base);
font-weight: var(--font-weight-semibold);
color: var(--text-color);
line-height: 1.3;
}
/* 우측 체크 아이콘 (선택 시 표시) */
.vendor-mode-card-check {
font-size: 1.25rem;
color: var(--border-color);
transition: all 0.2s ease;
margin-top: 2px;
flex-shrink: 0;
}
.vendor-mode-card.selected .vendor-mode-card-check {
color: var(--primary-color);
}
.vendor-mode-card:hover:not(.disabled) .vendor-mode-card-check {
color: var(--primary-color);
}
/* 배지 */
.vendor-mode-card-badge {
display: inline-flex;
align-items: center;
padding: 2px 8px;
border-radius: var(--border-radius);
font-size: var(--font-size-xs);
font-weight: var(--font-weight-semibold);
line-height: 1.4;
white-space: nowrap;
}
.vendor-mode-card-badge-recommended {
background-color: rgba(59, 130, 246, 0.15);
color: var(--primary-color);
}
.vendor-mode-card-badge-dev {
background-color: rgba(168, 85, 247, 0.15);
color: #9333ea;
}
.vendor-mode-card-badge-shared {
background-color: rgba(16, 185, 129, 0.15);
color: #059669;
}
/* 설명 */
.vendor-mode-card-description {
margin: 0;
font-size: var(--font-size-sm);
color: var(--text-muted);
line-height: 1.5;
}
/* 상태 메시지 */
.vendor-mode-card-status {
margin: 0;
padding-top: var(--spacing-xs);
border-top: 1px dashed var(--border-color);
font-size: var(--font-size-xs);
line-height: 1.4;
display: flex;
align-items: center;
gap: 4px;
}
.vendor-mode-card-status-ok {
color: var(--color-success, #10b981);
}
.vendor-mode-card-status-error {
color: var(--color-error, #ef4444);
}
/* 반응형 — 좁은 화면에서는 1열 */
@media (max-width: 640px) {
.vendor-mode-cards {
grid-template-columns: 1fr;
}
}
@@ -0,0 +1,292 @@
/**
* G7 인스톨러 - 설치 진행 모니터 (SSE/폴링 듀얼 모드)
*
* 두 모드 공통 콜백 인터페이스를 통해 UI 업데이트 로직을 공유합니다.
* - SseMonitor: EventSource 기반 실시간 스트리밍
* - PollingMonitor: setInterval 기반 state-management.php 폴링
*
* 콜백:
* onConnected() — 연결 성공 (SSE 전용, 폴링은 첫 poll 시 즉시 호출)
* onTaskStart(taskId, name, target) — 새 작업 시작
* onTaskComplete(taskId, message, target) — 작업 완료
* onLog(message) — 로그 라인 추가
* onComplete(data) — 전체 설치 성공
* onError(errorData) — 실패 (data: {message, message_key, error, task, target, manual_commands})
* onAbort(state) — 사용자 중단
* onRollbackFailed(data) — 롤백 실패
* onConnectionTimeout() — SSE 5초 내 연결 실패 (SSE 전용)
*/
(function (global) {
'use strict';
/**
* 기본 모니터 클래스 (공통 인터페이스)
*/
class InstallationMonitor {
constructor(callbacks, options = {}) {
this.callbacks = callbacks || {};
this.options = options;
this.stopped = false;
}
start() {
throw new Error('start() must be implemented by subclass');
}
stop() {
this.stopped = true;
}
_invoke(name, ...args) {
const cb = this.callbacks[name];
if (typeof cb === 'function') {
try {
cb(...args);
} catch (e) {
console.error(`[InstallationMonitor] callback ${name} failed:`, e);
}
}
}
}
/**
* SSE 기반 모니터 (EventSource)
*/
class SseMonitor extends InstallationMonitor {
constructor(callbacks, options = {}) {
super(callbacks, options);
this.workerUrl = options.workerUrl;
this.connectionTimeoutMs = options.connectionTimeoutMs || 5000;
this.eventSource = null;
this.connected = false;
this.connectionTimer = null;
}
start() {
this.eventSource = new EventSource(this.workerUrl);
this.connectionTimer = setTimeout(() => {
if (!this.connected && !this.stopped) {
this.stop();
this._invoke('onConnectionTimeout');
}
}, this.connectionTimeoutMs);
this.eventSource.addEventListener('connected', () => {
clearTimeout(this.connectionTimer);
this.connected = true;
this._invoke('onConnected');
});
this.eventSource.addEventListener('task_start', (e) => {
const data = JSON.parse(e.data);
this._invoke('onTaskStart', data.task, data.name, data.target || null);
});
this.eventSource.addEventListener('task_complete', (e) => {
const data = JSON.parse(e.data);
this._invoke('onTaskComplete', data.task, data.message, data.target || null);
});
this.eventSource.addEventListener('log', (e) => {
const data = JSON.parse(e.data);
this._invoke('onLog', data.message);
});
this.eventSource.addEventListener('completed', (e) => {
const data = JSON.parse(e.data);
this.stop();
this._invoke('onComplete', data);
});
this.eventSource.addEventListener('aborted', (e) => {
let data = {};
try {
data = JSON.parse(e.data);
} catch (_) {}
this.stop();
this._invoke('onAbort', data);
});
this.eventSource.addEventListener('rollback_failed', (e) => {
let data = {};
try {
data = JSON.parse(e.data);
} catch (_) {}
this._invoke('onRollbackFailed', data);
});
this.eventSource.addEventListener('error', (e) => {
// 서버에서 보낸 명시적 error 이벤트 (e.data 있음)
if (!e.data) {
return;
}
let data = {};
try {
data = JSON.parse(e.data);
} catch (_) {
data = { message: 'Unknown error' };
}
this.stop();
this._invoke('onError', data);
});
// 연결 오류 (네이티브 onerror) — e.data 없음
this.eventSource.onerror = () => {
clearTimeout(this.connectionTimer);
if (!this.connected && !this.stopped) {
this.stop();
this._invoke('onConnectionTimeout');
}
};
}
stop() {
super.stop();
if (this.connectionTimer) {
clearTimeout(this.connectionTimer);
this.connectionTimer = null;
}
if (this.eventSource) {
this.eventSource.close();
this.eventSource = null;
}
}
}
/**
* 폴링 기반 모니터 (state-management.php?action=get)
*
* 1초 간격으로 state를 조회하고 diff 발생 시 콜백을 호출합니다.
*/
class PollingMonitor extends InstallationMonitor {
constructor(callbacks, options = {}) {
super(callbacks, options);
this.stateUrl = options.stateUrl;
this.intervalMs = options.intervalMs || 1000;
this.timer = null;
this.lastLogOffset = 0;
this.lastCompletedTasks = [];
this.lastCurrentTask = null;
this.lastStatus = null;
this.terminated = false;
}
start() {
this._invoke('onConnected');
this._poll();
this.timer = setInterval(() => this._poll(), this.intervalMs);
}
stop() {
super.stop();
this.terminated = true;
if (this.timer) {
clearInterval(this.timer);
this.timer = null;
}
}
async _poll() {
if (this.terminated) return;
try {
const url = `${this.stateUrl}${this.stateUrl.includes('?') ? '&' : '?'}log_offset=${this.lastLogOffset}`;
const res = await fetch(url, { cache: 'no-store' });
if (!res.ok) {
return; // 일시적인 네트워크 오류는 무시 (다음 tick에서 재시도)
}
const state = await res.json();
this._diffAndEmit(state);
} catch (e) {
console.warn('[PollingMonitor] poll failed:', e);
}
}
_diffAndEmit(state) {
// 1. 새 로그 송출
if (Array.isArray(state.logs) && state.logs.length > 0) {
for (const log of state.logs) {
const msg = (typeof log === 'object' && log.message) ? log.message : String(log);
this._invoke('onLog', msg);
}
}
if (typeof state.log_total === 'number') {
this.lastLogOffset = state.log_total;
}
// 2. current_task 변화 감지 → onTaskStart
const currentTask = state.current_task || null;
if (currentTask && currentTask !== this.lastCurrentTask) {
// target 분리: "taskId:target" 형식
let taskId = currentTask;
let target = null;
const colonIdx = currentTask.indexOf(':');
if (colonIdx !== -1) {
taskId = currentTask.substring(0, colonIdx);
target = currentTask.substring(colonIdx + 1);
}
this._invoke('onTaskStart', taskId, null, target);
this.lastCurrentTask = currentTask;
}
// 3. completed_tasks diff → onTaskComplete
const completedTasks = Array.isArray(state.completed_tasks) ? state.completed_tasks : [];
for (const key of completedTasks) {
if (!this.lastCompletedTasks.includes(key)) {
let taskId = key;
let target = null;
const colonIdx = key.indexOf(':');
if (colonIdx !== -1) {
taskId = key.substring(0, colonIdx);
target = key.substring(colonIdx + 1);
}
this._invoke('onTaskComplete', taskId, null, target);
}
}
this.lastCompletedTasks = completedTasks.slice();
// 4. rollback_failure 저장 (에러/중단 처리 시 UI에 표시)
if (state.rollback_failure && this.lastStatus !== state.status) {
this._invoke('onRollbackFailed', {
message: state.rollback_failure.message || null,
detail: state.rollback_failure.detail_key || null,
});
}
// 5. status 전환 감지
const status = state.status;
if (status && status !== this.lastStatus) {
switch (status) {
case 'completed':
this.stop();
this._invoke('onComplete', { message: state.error_detail || null, redirect: '/install/' });
break;
case 'failed':
this.stop();
this._invoke('onError', {
message: state.error_detail || null,
message_key: state.error_message_key || null,
error: state.error_detail || null,
task: state.failed_task || null,
target: null,
manual_commands: state.manual_commands || null,
});
break;
case 'aborted':
this.stop();
this._invoke('onAbort', state);
break;
}
}
this.lastStatus = status;
}
}
// 전역 노출
global.G7InstallationMonitor = {
InstallationMonitor,
SseMonitor,
PollingMonitor,
};
})(window);
File diff suppressed because it is too large. Load diff
+9 -3
View File
@@ -63,11 +63,11 @@ define('OPTIONAL_EXTENSIONS', [
define('MIN_DISK_SPACE_MB', 500);
// 디렉토리 권한 설정 (8진수)
// chown + chmod 모델: 소유자(www-data) rwx, 그룹(www-data) rwx, 기타 ---
define('REQUIRED_DIRECTORY_PERMISSIONS', 0770);
// 업계 표준 755 (WordPress/Drupal/Joomla/Laravel 공통) — 실제 통과 기준은 is_writable() && is_readable()
define('REQUIRED_DIRECTORY_PERMISSIONS', 0755);
// 권한 표시용 문자열 (사용자에게 보여줄 형식)
define('REQUIRED_DIRECTORY_PERMISSIONS_DISPLAY', '770');
define('REQUIRED_DIRECTORY_PERMISSIONS_DISPLAY', '755');
// 권한 검증이 필요한 디렉토리 목록
// 값이 true인 경우 하위 디렉토리까지 재귀적으로 체크
@@ -120,6 +120,12 @@ define('DEFAULT_INSTALL_CONFIG', [
// PHP CLI / Composer 경로 설정
'php_binary' => 'php', // PHP CLI 바이너리 경로 (예: /usr/local/php82/bin/php)
'composer_binary' => '', // Composer 바이너리 경로 (빈 값 = 시스템 PATH 사용)
// Vendor 설치 모드 (auto|composer|bundled)
// - auto: composer 사용 가능 시 composer, 불가 시 vendor-bundle.zip 추출
// - composer: 강제 composer 실행
// - bundled: 강제 vendor-bundle.zip 추출 (공유 호스팅 환경)
'vendor_mode' => 'auto',
]);
// 설치 단계별 파일 매핑
+105 -41
View File
@@ -756,29 +756,37 @@ function checkDirectoryPermissions(array $directories): array
$results = [];
$allPassed = true;
$requiredPerms = REQUIRED_DIRECTORY_PERMISSIONS;
$requiredPermsDisplay = REQUIRED_DIRECTORY_PERMISSIONS_DISPLAY;
// 웹서버 실행 사용자 (ownership_mismatch 판별용)
$webServerUser = getWebServerUser();
foreach ($directories as $path => $checkRecursive) {
$fullPath = BASE_PATH . '/' . $path;
// 디렉토리 존재 여부 확인 (생성하지 않음)
$exists = is_dir($fullPath);
// 쓰기 권한 확인
// 실제 동작 기준 검증: 비트 값이 아닌 is_writable/is_readable로 판정
// 업계 표준에 따라 어떤 권한 조합이든 실제 동작하면 통과 (0755/0775/0770/0777 등)
$writable = $exists && is_writable($fullPath);
$readable = $exists && is_readable($fullPath);
// 권한 코드 가져오기 (8진수 3자리)
// 권한 코드는 정보 표시용으로만 유지
$permissions = 'N/A';
$hasCorrectPermissions = false;
$permsOctal = 0;
if ($exists) {
$perms = fileperms($fullPath);
$permissions = substr(sprintf('%o', $perms), -3);
$permsOctal = octdec($permissions);
}
// 설정된 권한과 비교
$currentPermsOctal = octdec($permissions);
$hasCorrectPermissions = ($currentPermsOctal & $requiredPerms) === $requiredPerms;
// 소유자/소유그룹 정보 가져오기
$owner = null;
$group = null;
if ($exists) {
$owner = getFileOwnerName($fullPath);
$group = getFileGroupName($fullPath);
}
// 재귀 체크 여부 확인
@@ -791,49 +799,41 @@ function checkDirectoryPermissions(array $directories): array
$hasSubdirectoryIssues = count($failedSubdirectories) > 0;
}
// 상위 디렉토리 자체의 통과 여부
$parentPassed = $writable && $hasCorrectPermissions;
// 상위 디렉토리 자체의 통과 여부 — is_writable && is_readable만 충족하면 OK
$parentPassed = $writable && $readable;
// 최종 통과 여부: 상위 + 하위 모두 통과해야 함
$passed = $parentPassed && !$hasSubdirectoryIssues;
// 에러 타입 구분
// ownership_mismatch: 권한 비트는 0755 이상이지만 소유자가 웹서버 사용자와 달라
// 실제 쓰기 불가 (전통적 Apache: 파일 소유자 != www-data)
$errorType = null;
if (!$exists) {
$errorType = 'not_exists';
} elseif (!$parentPassed) {
// 상위 디렉토리 자체의 문제
if (!$hasCorrectPermissions && $writable) {
// 권한 코드는 낮지만 쓰기 가능 (소유자/그룹 권한)
$errorType = 'permission_low_but_writable';
} elseif (!$hasCorrectPermissions) {
// 권한 코드가 필요한 것보다 낮음
$errorType = 'permission_too_low';
} elseif (!$writable) {
// 권한 코드는 충분하지만 쓰기 권한 없음
} elseif (!$writable) {
// 권한 비트가 충분(0755+)한데도 쓰기 불가 → 소유권 불일치 가능성
if ($permsOctal >= 0755 && $webServerUser && $owner && $owner !== $webServerUser) {
$errorType = 'ownership_mismatch';
} else {
$errorType = 'not_writable';
}
} elseif (!$readable) {
$errorType = 'not_readable';
} elseif ($hasSubdirectoryIssues) {
// 상위는 OK, 하위 디렉토리만 문제
$errorType = 'subdirectory_issues';
}
// 소유자/소유그룹 정보 가져오기
$owner = null;
$group = null;
if ($exists) {
$owner = getFileOwnerName($fullPath);
$group = getFileGroupName($fullPath);
}
$results[$path] = [
'exists' => $exists,
'writable' => $writable,
'readable' => $readable,
'permissions' => $permissions,
'required_permissions' => $requiredPermsDisplay,
'has_correct_permissions' => $hasCorrectPermissions,
'owner' => $owner,
'group' => $group,
'web_server_user' => $webServerUser,
'passed' => $passed,
'error_type' => $errorType,
'has_subdirectory_issues' => $hasSubdirectoryIssues,
@@ -1075,14 +1075,17 @@ function getEnvCopyCommand(string $basePath = ''): string
}
/**
* OS에 맞는 디렉토리 권한 수정 명령어를 반환합니다.
* OS에 맞는 권한 수정 명령어를 반환합니다.
*
* 업계 표준(WordPress/Drupal/Joomla/Laravel)에 맞춰 디렉토리 755, 파일 644로 통일.
* chown/setgid 의존성을 제거하여 공유호스팅 호환성 확보.
* 실제 통과 기준은 is_writable() && is_readable()이므로 비트 값은 참고용.
*
* @param string $webGroup 웹 서버 그룹명
* @param string $pathList 대상 경로 (공백 구분)
* @param string $mode 'ownership' (chown+chmod) 또는 'file' (파일 권한)
* @param string $mode 'ownership' (디렉토리) 또는 'file' (파일)
* @return string 권한 수정 명령어
*/
function getPermissionFixCommand(string $webGroup, string $pathList, string $mode = 'ownership', bool $skipChown = false): string
function getPermissionFixCommand(string $pathList, string $mode = 'ownership'): string
{
if (isWindows()) {
$winPath = str_replace('/', '\\', $pathList);
@@ -1094,15 +1097,76 @@ function getPermissionFixCommand(string $webGroup, string $pathList, string $mod
}
if ($mode === 'file') {
if ($skipChown) {
return 'chmod 660 ' . $pathList;
}
return 'sudo chown ' . $webGroup . ':' . $webGroup . ' ' . $pathList . ' && sudo chmod 660 ' . $pathList;
return 'chmod 644 ' . $pathList;
}
if ($skipChown) {
return 'chmod -R 2770 ' . $pathList;
}
return 'sudo chown -R ' . $webGroup . ':' . $webGroup . ' ' . $pathList . ' && sudo chmod -R 2770 ' . $pathList;
return 'chmod -R 755 ' . $pathList;
}
/**
* 기존 DB 테이블 감지 (이슈 #244 대응).
*
* Write DB에 테이블이 존재하는지 확인하고, G7 시그니처 테이블과 비교하여
* 설치 진행 가능 여부를 판정합니다.
*
* severity:
* - 'empty' : 빈 DB (정상 진행)
* - 'g7_existing' : G7 시그니처 4개 모두 존재 (기존 설치 감지)
* - 'mixed' : G7 일부 + 기타 혼재
* - 'foreign_data' : G7 시그니처 없음 + 기타 테이블 존재
*
* @param PDO $pdo 연결된 PDO 인스턴스
* @param string $database 대상 데이터베이스명
* @return array
*/
function checkExistingTables(PDO $pdo, string $database, string $tablePrefix = ''): array
{
try {
$stmt = $pdo->query('SHOW TABLES');
$tables = $stmt ? $stmt->fetchAll(PDO::FETCH_COLUMN) : [];
} catch (PDOException $e) {
return [
'has_tables' => false,
'is_g7_install' => false,
'g7_tables_found' => [],
'other_tables_count' => 0,
'all_tables' => [],
'severity' => 'empty',
'error' => $e->getMessage(),
];
}
if (empty($tables)) {
return [
'has_tables' => false,
'is_g7_install' => false,
'g7_tables_found' => [],
'other_tables_count' => 0,
'all_tables' => [],
'severity' => 'empty',
];
}
// G7 핵심 시그니처 테이블 — PO 결정: 4개 모두 일치 시 "G7 설치됨"으로 판단
// 테이블 prefix를 적용하여 비교 (예: prefix='g7_'이면 'g7_users', 'g7_migrations' 등)
$coreSignatures = ['users', 'migrations', 'roles', 'permissions'];
$g7Signatures = array_map(fn ($t) => $tablePrefix . $t, $coreSignatures);
$g7TablesFound = array_values(array_intersect($g7Signatures, $tables));
$severity = 'foreign_data';
if (count($g7TablesFound) >= 4) {
$severity = 'g7_existing';
} elseif (count($g7TablesFound) > 0) {
$severity = 'mixed';
}
return [
'has_tables' => true,
'is_g7_install' => $severity === 'g7_existing',
'g7_tables_found' => $g7TablesFound,
'other_tables_count' => max(0, count($tables) - count($g7TablesFound)),
'all_tables' => $tables,
'severity' => $severity,
];
}
+65 -15
View File
@@ -30,6 +30,8 @@ function getInstallationState(): array
clearstatcache(true, STATE_PATH);
// state.json 파일이 없으면 기본 상태 반환
// (설치 완료 후 워커가 DELETE_INSTALLER_AFTER_COMPLETE로 정상 삭제하는 경우가 있으므로
// 부재 자체는 에러가 아님. 호출자가 g7_installed 플래그 등으로 완료 여부 판정)
if (!file_exists(STATE_PATH)) {
return $defaultState;
}
@@ -53,7 +55,9 @@ function getInstallationState(): array
// JSON 파싱 실패 시 기본 상태 반환 (재귀 호출 제거 - 무한 루프 방지)
if (json_last_error() !== JSON_ERROR_NONE) {
error_log("Failed to parse state file JSON: " . json_last_error_msg());
$contentLen = strlen($content);
$preview = substr($content, 0, 200);
error_log("Failed to parse state file JSON (length={$contentLen}): " . json_last_error_msg() . " / preview: " . $preview);
return $defaultState;
}
@@ -87,16 +91,30 @@ function saveInstallationState(array $state): bool
// JSON 형식으로 저장
$content = json_encode($state, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
// 파일 쓰기
$result = @file_put_contents(STATE_PATH, $content);
if ($result === false) {
error_log("Failed to write state file: " . STATE_PATH);
if ($content === false) {
error_log("Failed to encode state as JSON: " . json_last_error_msg());
return false;
}
// 파일 권한 설정
@chmod(STATE_PATH, 0664);
// 원자적 쓰기: tmp 파일에 쓰고 rename으로 교체
// 동시 쓰기 경쟁 상황에서 부분 쓰기(half-written file)로 인한 JSON 손상 방지.
// Linux에서 rename()은 atomic syscall이므로 다른 리더가 항상 완전한 파일만 읽는다.
$tmpPath = STATE_PATH . '.tmp.' . getmypid() . '.' . uniqid();
$result = @file_put_contents($tmpPath, $content, LOCK_EX);
if ($result === false || $result !== strlen($content)) {
error_log("Failed to write state tmp file: " . $tmpPath);
@unlink($tmpPath);
return false;
}
@chmod($tmpPath, 0664);
if (!@rename($tmpPath, STATE_PATH)) {
error_log("Failed to rename state tmp file: " . $tmpPath . ' → ' . STATE_PATH);
@unlink($tmpPath);
return false;
}
return true;
}
@@ -285,27 +303,24 @@ function addLog(string $message): bool
* 페이지 새로고침 시 최신 로그를 즉시 표시하기 위해
* clearstatcache()를 적용합니다.
*
* @param int $offset 건너뛸 로그 줄 수 (폴링 모드 증분 조회용, 기본 0)
* @return array 로그 배열 [{timestamp, message}, ...]
*/
function getInstallationLogs(): array
function getInstallationLogs(int $offset = 0): array
{
$logFile = BASE_PATH . '/storage/logs/installation.log';
// 파일 캐시 초기화 (최신 데이터 읽기 보장)
clearstatcache(true, $logFile);
// 로그 파일이 없으면 빈 배열 반환
if (!file_exists($logFile)) {
return [];
}
// 로그 파일 읽기
$content = @file_get_contents($logFile);
if ($content === false) {
return [];
}
// 각 라인을 파싱
$lines = explode("\n", trim($content));
$logs = [];
@@ -314,14 +329,12 @@ function getInstallationLogs(): array
continue;
}
// [timestamp] message 형식 파싱
if (preg_match('/^\[(.+?)\] (.+)$/', $line, $matches)) {
$logs[] = [
'timestamp' => $matches[1],
'message' => $matches[2],
];
} else {
// 형식이 맞지 않으면 전체를 메시지로
$logs[] = [
'timestamp' => date('Y-m-d H:i:s'),
'message' => $line,
@@ -329,9 +342,46 @@ function getInstallationLogs(): array
}
}
// 증분 조회 (offset > 0이면 이전 결과 이후만 반환)
if ($offset > 0 && $offset < count($logs)) {
return array_slice($logs, $offset);
} elseif ($offset >= count($logs)) {
return [];
}
return $logs;
}
/**
* 설치 로그 전체 줄 수 조회 (폴링 모드 offset 계산용).
*
* @return int 전체 로그 줄 수
*/
function getInstallationLogCount(): int
{
$logFile = BASE_PATH . '/storage/logs/installation.log';
clearstatcache(true, $logFile);
if (!file_exists($logFile)) {
return 0;
}
$content = @file_get_contents($logFile);
if ($content === false) {
return 0;
}
$lines = explode("\n", trim($content));
$count = 0;
foreach ($lines as $line) {
if (!empty($line)) {
$count++;
}
}
return $count;
}
/**
* 마지막 완료된 단계 조회
*
@@ -0,0 +1,110 @@
<?php
/**
* 그누보드7 웹 인스톨러 - Progress Emitter 추상화
*
* SSE/폴링 듀얼 모드 지원을 위한 진행 상황 보고 인터페이스.
* - SseEmitter: 실시간 SSE 스트리밍 + addLog
* - NullEmitter: addLog만 수행 (폴링 모드, state.json 기반 조회)
*
* @package G7\Installer
*/
if (!defined('BASE_PATH')) {
define('BASE_PATH', realpath(dirname(__DIR__, 3)) ?: dirname(__DIR__, 3));
}
interface ProgressEmitter
{
/**
* 임의 이벤트 송출 (SSE 이벤트 타입과 데이터 배열).
*
* @param string $event 이벤트 타입 (connected, task_start, task_complete, log, completed, error, aborted, rollback_failed)
* @param array $data 이벤트 데이터
*/
public function emit(string $event, array $data): void;
/**
* 브라우저 연결 끊김 여부.
*
* SSE 모드: connection_aborted() 기반.
* 폴링 모드: 항상 false (응답은 이미 종료됨, 중단 감지는 state.json 기반).
*/
public function isConnectionAborted(): bool;
}
/**
* SSE 기반 진행 상황 송출.
*
* 기존 sendSSEEvent() 동작을 그대로 재현합니다.
*/
class SseEmitter implements ProgressEmitter
{
public function emit(string $event, array $data): void
{
echo "event: {$event}\n";
echo "data: " . json_encode($data, JSON_UNESCAPED_UNICODE) . "\n\n";
if (ob_get_level()) {
@ob_flush();
}
flush();
// log 이벤트는 installation.log에도 기록
if ($event === 'log' && isset($data['message'])) {
addLog($data['message']);
}
}
public function isConnectionAborted(): bool
{
return (bool) connection_aborted();
}
}
/**
* No-op 진행 상황 송출 (폴링 모드 전용).
*
* SSE 이벤트는 브라우저로 보내지 않고, log 메시지만 installation.log에 기록합니다.
* 프론트엔드는 state-management.php?action=get 폴링으로 진행 상황을 조회합니다.
*/
class NullEmitter implements ProgressEmitter
{
public function emit(string $event, array $data): void
{
if ($event === 'log' && isset($data['message'])) {
addLog($data['message']);
}
// 그 외 이벤트는 state.json 업데이트(task-runner.php 내부)로 커버됨
}
public function isConnectionAborted(): bool
{
// 폴링 모드: fastcgi_finish_request() 이후 호출되므로 connection_aborted()는 의미 없음.
// 사용자 중단은 state.json의 installation_status === 'aborted'로 감지.
return false;
}
}
/**
* 현재 등록된 ProgressEmitter 조회.
*
* task-runner.php의 sendSSEEvent() 호환 래퍼가 이 함수를 통해 delegate 합니다.
* 등록되지 않은 경우 안전한 기본값으로 SseEmitter를 반환합니다.
*/
function getProgressEmitter(): ProgressEmitter
{
if (!isset($GLOBALS['g7_progress_emitter']) || !($GLOBALS['g7_progress_emitter'] instanceof ProgressEmitter)) {
$GLOBALS['g7_progress_emitter'] = new SseEmitter();
}
return $GLOBALS['g7_progress_emitter'];
}
/**
* ProgressEmitter 등록.
*
* 모드별 진입점(install-worker.php / install-process.php 인라인 실행)에서 호출합니다.
*/
function setProgressEmitter(ProgressEmitter $emitter): void
{
$GLOBALS['g7_progress_emitter'] = $emitter;
}
@@ -163,6 +163,13 @@ function handleStep3Post(string $currentLang, array &$formData, array &$errors):
$formData['php_binary'] = $phpBinary !== '' ? $phpBinary : 'php';
$formData['composer_binary'] = trim($formData['composer_binary'] ?? '');
// Vendor 설치 모드 처리 (auto|composer|bundled)
$vendorMode = trim($formData['vendor_mode'] ?? 'auto');
if (! in_array($vendorMode, ['auto', 'composer', 'bundled'], true)) {
$vendorMode = 'auto';
}
$formData['vendor_mode'] = $vendorMode;
// 코어 업데이트 _pending 경로 검증 (입력된 경우만)
$corePendingPath = trim($formData['core_update_pending_path'] ?? '');
if ($corePendingPath !== '') {
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,346 @@
<?php
/**
* Vendor 번들 설치 헬퍼 (웹 인스톨러 전용 shim).
*
* Laravel 부트 전 단계에서 실행되므로 App\Extension\Vendor\VendorBundleInstaller
* 클래스를 사용할 수 없다. 동일한 검증/추출 로직을 순수 PHP로 구현한다.
*
* Laravel 측 클래스와의 동등성은 VendorBundleInstallerShimTest 가 보장한다.
*/
const VENDOR_BUNDLE_SCHEMA_VERSION = '1.0';
const VENDOR_BUNDLE_ZIP_FILENAME = 'vendor-bundle.zip';
const VENDOR_BUNDLE_MANIFEST_FILENAME = 'vendor-bundle.json';
/**
* vendor-bundle.zip 의 무결성을 검증합니다.
*
* @param string $sourceDir vendor-bundle.zip 이 위치한 디렉토리
* @return array{valid: bool, errors: array<string>, meta: array<string, mixed>}
*/
function verifyVendorBundle(string $sourceDir): array
{
$zipPath = $sourceDir.DIRECTORY_SEPARATOR.VENDOR_BUNDLE_ZIP_FILENAME;
$manifestPath = $sourceDir.DIRECTORY_SEPARATOR.VENDOR_BUNDLE_MANIFEST_FILENAME;
if (! file_exists($zipPath)) {
return ['valid' => false, 'errors' => ['bundle_zip_missing'], 'meta' => []];
}
if (! file_exists($manifestPath)) {
return ['valid' => false, 'errors' => ['bundle_manifest_missing'], 'meta' => []];
}
$manifestJson = @file_get_contents($manifestPath);
if ($manifestJson === false) {
return ['valid' => false, 'errors' => ['bundle_manifest_invalid'], 'meta' => []];
}
$manifest = json_decode($manifestJson, true);
if (! is_array($manifest)) {
return ['valid' => false, 'errors' => ['bundle_manifest_invalid'], 'meta' => []];
}
$schemaVersion = $manifest['schema_version'] ?? null;
if ($schemaVersion !== VENDOR_BUNDLE_SCHEMA_VERSION) {
return ['valid' => false, 'errors' => ['bundle_schema_unsupported'], 'meta' => $manifest];
}
$errors = [];
$expectedZipHash = $manifest['zip_sha256'] ?? null;
if ($expectedZipHash === null) {
$errors[] = 'bundle_manifest_invalid';
} else {
$actualZipHash = hash_file('sha256', $zipPath);
if (! hash_equals((string) $expectedZipHash, (string) $actualZipHash)) {
$errors[] = 'zip_hash_mismatch';
}
}
$composerJsonPath = $sourceDir.DIRECTORY_SEPARATOR.'composer.json';
if (file_exists($composerJsonPath)) {
$expected = $manifest['composer_json_sha256'] ?? null;
if ($expected !== null) {
$actual = hash_file('sha256', $composerJsonPath);
if (! hash_equals((string) $expected, (string) $actual)) {
$errors[] = 'composer_json_sha_mismatch';
}
}
}
if (! empty($errors)) {
return ['valid' => false, 'errors' => $errors, 'meta' => $manifest];
}
return ['valid' => true, 'errors' => [], 'meta' => $manifest];
}
/**
* vendor-bundle.zip 을 대상 디렉토리에 추출합니다.
*
* 공유 호스팅 친화적 설계:
* - targetDir 자체(프로젝트 루트)의 쓰기 권한은 요구하지 않음
* - vendor/ 디렉토리 자체는 유지하고 내부 항목만 조작
* - 기존 내용은 vendor/.bundle_backup_{ts}/ 로 이동 (vendor/ 쓰기 권한만으로 가능)
* - 추출 실패 시 백업에서 복원, 성공 시 백업 삭제
*
* @param string $sourceDir vendor-bundle.zip 위치
* @param string $targetDir vendor/ 가 배치될 위치
* @return array{success: bool, error?: string, package_count?: int}
*/
function extractVendorBundle(string $sourceDir, string $targetDir): array
{
if (! class_exists('ZipArchive')) {
return ['success' => false, 'error' => 'zip_archive_not_available'];
}
$integrity = verifyVendorBundle($sourceDir);
if (! $integrity['valid']) {
return [
'success' => false,
'error' => 'bundle_integrity_failed: '.implode(', ', $integrity['errors']),
];
}
$zipPath = $sourceDir.DIRECTORY_SEPARATOR.VENDOR_BUNDLE_ZIP_FILENAME;
$vendorDir = $targetDir.DIRECTORY_SEPARATOR.'vendor';
$backupDirName = '.bundle_backup_'.date('Ymd_His');
$backupDir = $vendorDir.DIRECTORY_SEPARATOR.$backupDirName;
// 쓰기 권한 유연 검사 — vendor/ 가 있으면 vendor/ 권한만, 없으면 targetDir 권한 필요
if (is_dir($vendorDir)) {
if (! is_writable($vendorDir)) {
return ['success' => false, 'error' => 'target_not_writable: '.$vendorDir.buildVendorBundlePermissionHint($vendorDir)];
}
} else {
if (! is_dir($targetDir) || ! is_writable($targetDir)) {
return ['success' => false, 'error' => 'target_not_writable: '.$targetDir.buildVendorBundlePermissionHint($targetDir)];
}
}
// zip slip 사전 검증
$unsafePathError = checkVendorBundleZipSafety($zipPath);
if ($unsafePathError !== null) {
return ['success' => false, 'error' => 'bundle_contains_unsafe_path: '.$unsafePathError];
}
// 기존 vendor/ 내부 항목을 vendor/.bundle_backup_{ts}/ 로 이동
// (vendor/ 디렉토리 자체는 유지 — targetDir 쓰기 권한 불필요)
$hasBackup = false;
if (is_dir($vendorDir)) {
$hasBackup = moveVendorContentsToBackup($vendorDir, $backupDir, $backupDirName);
} else {
// vendor/ 없음 — 신규 생성 (targetDir 쓰기 권한 필요, 위에서 이미 검증)
if (! @mkdir($vendorDir, 0755, true) && ! is_dir($vendorDir)) {
return ['success' => false, 'error' => 'target_not_writable: '.$vendorDir];
}
}
$zip = new ZipArchive;
$openResult = $zip->open($zipPath);
if ($openResult !== true) {
if ($hasBackup && is_dir($backupDir)) {
restoreVendorFromBackup($vendorDir, $backupDir, $backupDirName);
}
return ['success' => false, 'error' => 'extraction_failed: ZipArchive::open failed (code '.$openResult.')'];
}
$extracted = $zip->extractTo($targetDir);
$zip->close();
if (! $extracted) {
if ($hasBackup && is_dir($backupDir)) {
restoreVendorFromBackup($vendorDir, $backupDir, $backupDirName);
}
return ['success' => false, 'error' => 'extraction_failed: ZipArchive::extractTo returned false'];
}
// 성공: 백업 디렉토리 삭제 (vendor/.bundle_backup_{ts}/)
if ($hasBackup && is_dir($backupDir)) {
deleteVendorBundleDirectory($backupDir);
}
return [
'success' => true,
'package_count' => (int) ($integrity['meta']['package_count'] ?? 0),
];
}
/**
* 기존 vendor/ 내부 항목을 vendor/.bundle_backup_{ts}/ 로 이동합니다.
*
* vendor/ 디렉토리 자체는 유지하므로 targetDir 쓰기 권한이 필요하지 않습니다.
*
* @return bool 백업 성공 여부 (false 시 in-place overwrite 로 추출 진행)
*/
function moveVendorContentsToBackup(string $vendorDir, string $backupDir, string $backupDirName): bool
{
if (! @mkdir($backupDir) && ! is_dir($backupDir)) {
return false;
}
$items = @scandir($vendorDir) ?: [];
foreach ($items as $item) {
if ($item === '.' || $item === '..' || $item === $backupDirName) {
continue;
}
$src = $vendorDir.DIRECTORY_SEPARATOR.$item;
$dst = $backupDir.DIRECTORY_SEPARATOR.$item;
@rename($src, $dst);
}
return true;
}
/**
* 백업 디렉토리에서 vendor/ 로 내용을 복원합니다.
*/
function restoreVendorFromBackup(string $vendorDir, string $backupDir, string $backupDirName): void
{
// 추출로 이미 생성된 파일/디렉토리 정리 (백업 폴더 제외)
$items = @scandir($vendorDir) ?: [];
foreach ($items as $item) {
if ($item === '.' || $item === '..' || $item === $backupDirName) {
continue;
}
$path = $vendorDir.DIRECTORY_SEPARATOR.$item;
if (is_dir($path) && ! is_link($path)) {
deleteVendorBundleDirectory($path);
} elseif (file_exists($path)) {
@unlink($path);
}
}
// 백업 항목을 원위치로 이동
$backupItems = @scandir($backupDir) ?: [];
foreach ($backupItems as $item) {
if ($item === '.' || $item === '..') {
continue;
}
$src = $backupDir.DIRECTORY_SEPARATOR.$item;
$dst = $vendorDir.DIRECTORY_SEPARATOR.$item;
@rename($src, $dst);
}
@rmdir($backupDir);
}
/**
* zip 내부 파일 경로의 안전성을 검증합니다 (zip slip 방지).
*/
function checkVendorBundleZipSafety(string $zipPath): ?string
{
$zip = new ZipArchive;
if ($zip->open($zipPath) !== true) {
return 'cannot open zip';
}
for ($i = 0; $i < $zip->numFiles; $i++) {
$name = $zip->getNameIndex($i);
if ($name === false) {
continue;
}
$normalized = str_replace('\\', '/', $name);
if (
str_contains($normalized, '../')
|| str_starts_with($normalized, '/')
|| preg_match('#^[A-Za-z]:/#', $normalized)
) {
$zip->close();
return $name;
}
}
$zip->close();
return null;
}
/**
* 디렉토리 재귀 삭제 (Laravel File 파사드 의존 제거).
*/
function deleteVendorBundleDirectory(string $dir): bool
{
if (! is_dir($dir)) {
return false;
}
$items = scandir($dir);
foreach ($items as $item) {
if ($item === '.' || $item === '..') {
continue;
}
$path = $dir.DIRECTORY_SEPARATOR.$item;
if (is_dir($path)) {
deleteVendorBundleDirectory($path);
} else {
@unlink($path);
}
}
return @rmdir($dir);
}
/**
* Composer 실행이 현재 환경에서 가능한지 검사합니다.
*
* proc_open() 사용 가능 여부 + composer 바이너리 발견 여부를 종합 판단.
*/
function canExecuteComposerForInstall(?string $composerBinary, ?string $phpBinary): bool
{
// proc_open 사용 가능 여부
if (! function_exists('proc_open')) {
return false;
}
$disabled = array_map('trim', explode(',', (string) ini_get('disable_functions')));
if (in_array('proc_open', $disabled, true)) {
return false;
}
// composer 바이너리 결정
$binary = $composerBinary;
if (! $binary) {
// PATH 검색 단계는 인스톨러 환경에서 비용이 크므로 단순화
$binary = 'composer';
}
return ! empty($binary);
}
/**
* 권한 거부 시 진단 힌트를 생성합니다.
*
* 인스톨러는 Laravel __() 사용 불가하므로 순수 PHP로 메시지를 구성합니다.
* (한국어 고정 — 인스톨러는 다국어 지원 범위가 제한적)
*/
function buildVendorBundlePermissionHint(string $path): string
{
if (! function_exists('posix_geteuid') || ! function_exists('posix_getpwuid')) {
return '';
}
$currentUid = posix_geteuid();
$currentUser = posix_getpwuid($currentUid)['name'] ?? (string) $currentUid;
if (! file_exists($path)) {
return " (실행 사용자: {$currentUser})";
}
$ownerUid = fileowner($path);
if ($currentUid === $ownerUid) {
return " (실행 사용자: {$currentUser}, 소유자 동일)";
}
$ownerUser = posix_getpwuid($ownerUid)['name'] ?? (string) $ownerUid;
return " — 실행 사용자({$currentUser})와 디렉토리 소유자({$ownerUser})가 다릅니다. ".
"FTP/SSH로 'chown -R {$currentUser} {$path}' 실행 후 재시도하세요.";
}
+1
View File
@@ -163,6 +163,7 @@ $stepFile = __DIR__ . '/views/' . $currentStep . '-' . (STEP_FILE_MAP[$currentSt
window.INSTALLER_LANG = <?= json_encode($translations ?? [], JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT) ?>;
window.INSTALLER_STATE_LOCALE = <?= json_encode($state['g7_locale'] ?? null) ?>;
</script>
<script src="<?= INSTALLER_BASE_URL ?>/assets/js/installation-monitor.js?v=<?= time() ?>"></script>
<script src="<?= INSTALLER_BASE_URL ?>/assets/js/installer.js?v=<?= time() ?>"></script>
</body>
</html>
+68 -9
View File
@@ -25,9 +25,11 @@ return [
'storage_not_exists_message' => 'The storage folder does not exist. Please create a storage folder in the project root.',
'storage_not_writable' => 'Storage Folder Not Writable',
'storage_not_writable_message' => 'The storage folder is not writable. Please check the folder owner or group permissions.',
'storage_permission_guide' => 'Please grant <strong>:permissions</strong> permission to the Storage folder.',
'storage_ownership_mismatch' => 'Storage Folder Ownership Mismatch',
'storage_ownership_mismatch_message' => 'The storage folder owner (:owner) does not match the web server user (:web_user). Current permissions (:permissions) allow only the owner to write, so the web server cannot write. Please apply one of the options below.',
'storage_permission_guide' => 'Please grant <strong>755</strong> permission to the Storage folder.',
'storage_permission_guide_detail' => 'Run the command below or change permissions via FTP:',
'storage_permission_command_linux' => 'chmod -R :permissions :path',
'storage_permission_command_linux' => 'chmod -R 755 :path',
'current_owner' => 'Owner',
'current_group' => 'Group',
'current_permissions' => 'Permissions',
@@ -71,6 +73,10 @@ return [
'error_disk_space' => 'Disk Space',
'error_directory_permissions' => 'Insufficient directory write permissions',
'error_required_files' => 'Required files missing',
'error_required_files_missing_label' => 'Required files missing',
'error_required_files_not_writable_label' => 'Required files not writable',
'error_required_files_ownership_mismatch_label' => 'Required files ownership mismatch',
'ownership_mismatch_option_666' => '[Alternative 2] Last resort — grant write permission to the file for everyone (reduced security, not recommended):',
'required_files' => 'Required Files',
'file_exists' => 'Exists',
'file_missing' => 'Missing',
@@ -129,7 +135,7 @@ return [
'show_progress' => 'Show Installation List',
'installation_completed' => 'Installation Complete!',
'recommendations' => 'Post-Installation Recommendations',
'recommendation_env_permission' => 'Set .env file permissions to 600 or 644',
'recommendation_env_permission' => 'Set .env file permissions to 644 (chmod 644 .env)',
'recommendation_https' => 'Use HTTPS in production environment',
// Step 5: Complete
@@ -191,7 +197,7 @@ return [
// Error Messages - System (Requirements) (detailed)
'error_php_version_insufficient_detail' => 'PHP version does not meet requirements (current: :current, required: :min+)',
'error_disk_space_insufficient_detail' => 'Insufficient disk space (current: :current MB, required: :min MB)',
'error_directory_not_writable_detail' => 'Some directories are not writable. Please set permissions to :permissions.',
'error_directory_not_writable_detail' => 'Some directories are not writable. Run the command below to grant the permissions.',
'error_required_files_missing' => 'Required files are missing.',
'error_step_file_not_found' => 'Step file not found. Installation files may be corrupted.',
@@ -240,6 +246,8 @@ return [
'task_env_create' => 'Creating Configuration File',
'task_env_update' => 'Updating Configuration File',
'task_key_generate' => 'Generating Security Key',
'task_dependency_precheck' => 'Extension Dependency Precheck',
'task_db_cleanup' => 'Cleaning Up Existing Database Tables',
'task_db_migrate' => 'Creating Database Tables',
'task_db_seed' => 'Initializing Default Data',
'task_template_install' => 'Installing Admin Template',
@@ -277,6 +285,8 @@ return [
// Log Messages - Worker (Composer)
'log_composer_check_success' => 'Composer check completed',
'log_composer_check_skipped_bundled' => 'Composer check skipped — bundled vendor mode',
'log_composer_check_auto_fallback' => 'Composer not installed — will auto-fallback to bundled vendor mode',
'log_composer_already_installed' => 'Composer dependencies are already installed',
'log_composer_install_success' => 'Composer dependency installation completed',
'log_composer_vendor_without_lock' => 'vendor directory exists but composer.lock is missing (incomplete state)',
@@ -544,7 +554,7 @@ location /install/api/ {
</Location>
[PHP Configuration]
// Add to the top of install-worker-sse.php
// Add to the top of install-worker.php
ini_set(\'output_buffering\', \'off\');
ini_set(\'zlib.output_compression\', \'off\');
@apache_setenv(\'no-gzip\', 1);
@@ -553,6 +563,47 @@ ini_set(\'zlib.output_compression\', \'off\');
Contact your hosting provider about SSE (Server-Sent Events) support.
Firewalls or proxies may be blocking long-lived HTTP connections.',
// Installation mode (SSE / polling)
'installation_mode_label' => 'Installation Mode',
'installation_mode_sse_title' => 'Real-time Streaming (SSE) — Recommended',
'installation_mode_sse_desc' => 'The server streams progress in real time. Fastest and most reliable in standard environments.',
'installation_mode_polling_title' => 'Compatibility Mode (Polling)',
'installation_mode_polling_desc' => 'Use this when SSE connection errors occur behind an Nginx proxy, shared hosting, etc. Status is polled every second.',
'sse_fallback_confirm' => 'SSE connection failed.\n\nWould you like to retry in compatibility mode (polling)?',
'start_installation_button' => 'Start Installation',
// Step 4 dependency warnings
'dependency_warning_title' => 'Missing Dependencies Detected',
'dependency_warning_description' => 'The following extensions are required. Click "Auto-select required items" to resolve them in one click.',
'dependency_auto_select' => 'Auto-select required items',
'dependency_missing_tooltip' => 'Please resolve dependencies first',
'dependency_precheck_failed' => 'Dependency precheck failed — return to Step 4 and select the missing modules/plugins',
// Step 3 existing database detection (issue #244)
'db_existing_g7_badge' => 'Existing G7 installation detected',
'db_existing_foreign_badge' => 'Foreign data detected',
'db_existing_mixed_badge' => 'Mixed G7 + foreign tables',
'db_existing_g7_title' => 'Existing G7 Installation Detected',
'db_existing_foreign_title' => 'Foreign Data Detected',
'db_existing_mixed_title' => 'Mixed Data Detected',
'db_existing_generic_title' => 'Existing Tables Detected',
'db_existing_g7_desc' => 'The selected database already contains a G7 installation. Forcing the install will delete all existing data. Back up first.',
'db_existing_foreign_desc' => 'The selected database contains unknown tables. Forcing the install will drop all of them. Consider using another database or back up first.',
'db_existing_mixed_desc' => 'The selected database contains a mix of G7 and other tables. Forcing the install will drop all of them.',
'db_existing_generic_desc' => 'The selected database contains existing tables. Forcing the install will drop all of them.',
'db_existing_tables_list' => 'Detected tables (up to 20):',
'db_backup_guide' => 'Backup command example (verify host/user/database before running):',
'db_backup_confirmed' => 'I have backed up and agree that all existing tables will be dropped',
'error_db_cleanup_consent_required' => 'You must consent to dropping existing tables before proceeding to the next step.',
'db_force_proceed_drop' => 'Drop all existing tables and install',
'db_force_proceed_confirmed' => 'Force install mode (existing tables will be dropped)',
'cancel' => 'Cancel',
'log_db_cleanup_skipped' => 'Skipping existing table cleanup (no action)',
'log_db_cleanup_empty' => 'No existing tables. Skipping cleanup.',
'log_db_cleanup_dropping' => 'Dropping {count} existing tables...',
'log_db_cleanup_done' => 'Dropped {count} existing tables.',
'error_db_cleanup_failed' => 'Failed to clean up existing database tables',
// Dark Mode
'toggle_theme' => 'Toggle Theme',
'dark_mode' => 'Dark Mode',
@@ -589,6 +640,10 @@ Firewalls or proxies may be blocking long-lived HTTP connections.',
'dependency_type_admin_template' => 'Admin Template',
'dependency_type_user_template' => 'User Template',
'dependency_type_other' => 'Other',
'dep_auto_badge_label' => 'Required dependency',
'dep_lock_message' => ':names requires this item. Please deselect that extension first.',
'dep_version_required' => 'Required',
'dep_version_available' => 'Available',
'author' => 'Author',
'retry' => 'Retry',
'select_all' => 'Select All',
@@ -682,10 +737,13 @@ Firewalls or proxies may be blocking long-lived HTTP connections.',
'copied' => 'Copied!',
// Step 2 permission guidance
'permission_fix_guide' => 'Run the following command in your terminal to fix permissions:',
'ownership_fix_guide' => 'Change the ownership to the web server user:',
'ownership_fix_hint' => '※ www-data is the web server user/group. Change it to nginx, apache, etc. depending on your environment.',
'ownership_detected_hint' => '※ Current web server user: :user (auto-detected)',
'permission_fix_guide' => 'Run the following command in your terminal or SSH to grant permissions:',
'ownership_mismatch_option_group' => '[Recommended] Group sharing — change group to the web server user and grant write permission:',
'ownership_mismatch_option_chown' => '[Alternative 1] Change owner — transfer ownership to the web server user:',
'ownership_mismatch_option_777' => '[Alternative 2] Last resort — grant write permission to everyone (reduced security, not recommended):',
'ownership_mismatch_hint' => '※ Current owner: :owner / Web server user: :web_user. Choose the option that matches your environment.',
'permission_fallback_title' => 'If the command above does not resolve the issue',
'permission_fallback_detail' => 'Some environments (e.g. dedicated servers) may require: chmod -R 775 :path',
'permission_windows_hint' => '※ On Windows, open Command Prompt (cmd) as Administrator and run the command. Alternatively, you can set permissions via folder Properties → Security tab.',
'directory_create_guide' => 'Run the following command to create the missing directories:',
@@ -761,6 +819,7 @@ Firewalls or proxies may be blocking long-lived HTTP connections.',
'cli_status_checking' => 'Checking...',
'cli_status_verified' => '✓ Verified',
'cli_status_not_verified' => '✗ Not verified',
'cli_status_optional_bundled' => '— Optional (bundled mode)',
// Environment Check Enhancements
'required_functions' => 'Required Functions',
+68 -9
View File
@@ -25,9 +25,11 @@ return [
'storage_not_exists_message' => 'Storage 폴더가 존재하지 않습니다. 프로젝트 루트에 storage 폴더를 생성해주세요.',
'storage_not_writable' => 'Storage 폴더 쓰기 권한 없음',
'storage_not_writable_message' => 'Storage 폴더에 쓰기 권한이 없습니다. 폴더 소유자 또는 그룹 권한을 확인해주세요.',
'storage_permission_guide' => 'Storage 폴더에 <strong>:permissions</strong> 권한을 부여해주세요.',
'storage_ownership_mismatch' => 'Storage 폴더 소유자 불일치',
'storage_ownership_mismatch_message' => 'Storage 폴더의 소유자(:owner)가 웹서버 실행 사용자(:web_user)와 다릅니다. 현재 권한(:permissions)은 소유자만 쓰기 가능하므로 웹서버가 쓸 수 없습니다. 아래 방법 중 하나를 적용해주세요.',
'storage_permission_guide' => 'Storage 폴더에 <strong>755</strong> 권한을 부여해주세요.',
'storage_permission_guide_detail' => '아래 명령어를 실행하거나 FTP를 통해 권한을 변경하세요:',
'storage_permission_command_linux' => 'chmod -R :permissions :path',
'storage_permission_command_linux' => 'chmod -R 755 :path',
'current_owner' => '현재 소유자',
'current_group' => '현재 소유그룹',
'current_permissions' => '현재 권한',
@@ -71,6 +73,10 @@ return [
'error_disk_space' => '디스크 공간',
'error_directory_permissions' => '디렉토리 쓰기 권한 부족',
'error_required_files' => '필수 파일 누락',
'error_required_files_missing_label' => '필수 파일 누락',
'error_required_files_not_writable_label' => '필수 파일 쓰기 권한 없음',
'error_required_files_ownership_mismatch_label' => '필수 파일 소유자 불일치',
'ownership_mismatch_option_666' => '[대안 2] 최후 수단 — 파일에 모든 사용자 쓰기 허용 (보안 약화, 비권장):',
'required_files' => '필수 파일',
'file_exists' => '존재',
'file_missing' => '누락',
@@ -129,7 +135,7 @@ return [
'show_progress' => '설치 목록 보기',
'installation_completed' => '설치가 완료되었습니다!',
'recommendations' => '설치 후 권장사항',
'recommendation_env_permission' => '.env 파일 권한을 600 또는 644로 설정하세요',
'recommendation_env_permission' => '.env 파일 권한을 644로 설정하세요 (chmod 644 .env)',
'recommendation_https' => '프로덕션 환경에서는 반드시 HTTPS를 사용하세요',
// Step 5: 완료
@@ -191,7 +197,7 @@ return [
// 에러 메시지 - 시스템 (요구사항) (상세)
'error_php_version_insufficient_detail' => 'PHP 버전이 요구사항을 충족하지 않습니다. (현재: :current, 요구: :min+)',
'error_disk_space_insufficient_detail' => '디스크 공간이 부족합니다. (현재: :current MB, 요구: :min MB)',
'error_directory_not_writable_detail' => '일부 디렉토리에 쓰기 권한이 없습니다. 권한을 :permissions로 설정해주세요.',
'error_directory_not_writable_detail' => '일부 디렉토리에 쓰기 권한이 없습니다. 아래 명령어를 실행하여 권한을 부여해주세요.',
'error_required_files_missing' => '필수 파일이 누락되었습니다.',
'error_step_file_not_found' => '단계 파일을 찾을 수 없습니다. 설치 파일이 손상되었을 수 있습니다.',
@@ -240,6 +246,8 @@ return [
'task_env_create' => '환경 설정 파일 생성',
'task_env_update' => '환경 설정 파일 업데이트',
'task_key_generate' => '보안 키 생성',
'task_dependency_precheck' => '확장 의존성 사전 검증',
'task_db_cleanup' => '기존 DB 테이블 정리',
'task_db_migrate' => '데이터베이스 테이블 생성',
'task_db_seed' => '기본 데이터 생성',
'task_template_install' => '관리자 템플릿 설치',
@@ -277,6 +285,8 @@ return [
// 로그 메시지 - Worker (Composer)
'log_composer_check_success' => 'Composer 확인 완료',
'log_composer_check_skipped_bundled' => 'Composer 확인 스킵 — 번들 vendor 모드',
'log_composer_check_auto_fallback' => 'Composer 미설치 — 번들 vendor 모드로 자동 폴백 예정',
'log_composer_already_installed' => 'Composer 의존성이 이미 설치되어 있습니다',
'log_composer_install_success' => 'Composer 의존성 설치 완료',
'log_composer_vendor_without_lock' => 'vendor 디렉토리는 있지만 composer.lock 파일이 없습니다 (불완전 상태)',
@@ -544,7 +554,7 @@ location /install/api/ {
</Location>
[PHP 설정]
// install-worker-sse.php 최상단에 추가
// install-worker.php 최상단에 추가
ini_set(\'output_buffering\', \'off\');
ini_set(\'zlib.output_compression\', \'off\');
@apache_setenv(\'no-gzip\', 1);
@@ -553,6 +563,47 @@ ini_set(\'zlib.output_compression\', \'off\');
호스팅 제공업체에 SSE(Server-Sent Events) 지원 여부를 문의해주세요.
방화벽이나 프록시에서 long-lived HTTP 연결을 차단하고 있을 수 있습니다.',
// 설치 진행 방식 (SSE / 폴링)
'installation_mode_label' => '설치 진행 방식',
'installation_mode_sse_title' => '실시간 스트리밍 (SSE) — 권장',
'installation_mode_sse_desc' => '서버가 진행 상황을 즉시 전송합니다. 일반 환경에서 가장 빠르고 안정적입니다.',
'installation_mode_polling_title' => '호환성 모드 (폴링)',
'installation_mode_polling_desc' => 'Nginx 프록시, 공유 호스팅 등 SSE 연결 오류가 발생하는 환경에서 사용하세요. 1초마다 상태를 확인합니다.',
'sse_fallback_confirm' => 'SSE 연결에 실패했습니다.\n\n호환성 모드(폴링)로 다시 시도하시겠습니까?',
'start_installation_button' => '설치 시작',
// Step 4 의존성 경고
'dependency_warning_title' => '의존성 누락 감지',
'dependency_warning_description' => '다음 확장이 필요합니다. "필요한 항목 자동 선택" 버튼을 눌러 한 번에 해결할 수 있습니다.',
'dependency_auto_select' => '필요한 항목 자동 선택',
'dependency_missing_tooltip' => '의존성을 먼저 해결해주세요',
'dependency_precheck_failed' => '의존성 사전 검증 실패 — Step 4로 돌아가 누락된 모듈/플러그인을 선택해주세요',
// Step 3 기존 DB 감지 (이슈 #244)
'db_existing_g7_badge' => '기존 그누보드7 설치 감지',
'db_existing_foreign_badge' => '다른 데이터 감지',
'db_existing_mixed_badge' => 'G7 일부 + 다른 테이블 혼재',
'db_existing_g7_title' => '그누보드7 기존 설치 감지',
'db_existing_foreign_title' => '다른 데이터 감지',
'db_existing_mixed_title' => '데이터 혼재 감지',
'db_existing_generic_title' => '기존 테이블 감지',
'db_existing_g7_desc' => '선택한 DB에 이미 그누보드7이 설치되어 있습니다. 강제 진행 시 기존 데이터가 모두 삭제됩니다. 반드시 백업 후 진행하세요.',
'db_existing_foreign_desc' => '선택한 DB에 알 수 없는 테이블이 존재합니다. 강제 진행 시 모든 테이블이 삭제됩니다. 다른 DB를 사용하거나 반드시 백업 후 진행하세요.',
'db_existing_mixed_desc' => '선택한 DB에 G7 일부 테이블과 다른 테이블이 혼재합니다. 강제 진행 시 모든 테이블이 삭제됩니다.',
'db_existing_generic_desc' => '선택한 DB에 기존 테이블이 존재합니다. 강제 진행 시 모든 테이블이 삭제됩니다.',
'db_existing_tables_list' => '감지된 테이블 (최대 20개):',
'db_backup_guide' => '백업 명령어 예시 (호스트/사용자/데이터베이스명 확인 후 실행하세요):',
'db_backup_confirmed' => '백업을 완료했으며, 기존 테이블이 모두 삭제되는 것에 동의합니다',
'error_db_cleanup_consent_required' => '기존 테이블 삭제에 동의하셔야 다음 단계로 진행할 수 있습니다.',
'db_force_proceed_drop' => '기존 테이블 모두 삭제 후 설치',
'db_force_proceed_confirmed' => '강제 진행 모드 (설치 시 기존 테이블 삭제)',
'cancel' => '취소',
'log_db_cleanup_skipped' => '기존 테이블 정리 건너뛰기 (액션 없음)',
'log_db_cleanup_empty' => '기존 테이블이 없습니다. 정리 건너뛰기',
'log_db_cleanup_dropping' => '기존 테이블 {count}개 삭제 시작...',
'log_db_cleanup_done' => '기존 테이블 {count}개 삭제 완료',
'error_db_cleanup_failed' => '기존 DB 테이블 정리 실패',
// 다크모드
'toggle_theme' => '테마 전환',
'dark_mode' => '다크 모드',
@@ -589,6 +640,10 @@ ini_set(\'zlib.output_compression\', \'off\');
'dependency_type_admin_template' => '관리자 템플릿',
'dependency_type_user_template' => '사용자 템플릿',
'dependency_type_other' => '기타',
'dep_auto_badge_label' => '필수 의존성',
'dep_lock_message' => ':names 이(가) 이 항목을 필요로 합니다. 먼저 해당 확장을 해제해주세요.',
'dep_version_required' => '필요 버전',
'dep_version_available' => '설치 가능 버전',
'author' => '제작자',
'retry' => '재시도',
'select_all' => '전체 선택',
@@ -682,10 +737,13 @@ ini_set(\'zlib.output_compression\', \'off\');
'copied' => '복사됨!',
// Step 2 권한 안내
'permission_fix_guide' => '아래 명령어를 터미널에서 실행하여 권한을 수정하세요:',
'ownership_fix_guide' => '소유자와 그룹을 웹 서버 사용자로 변경하세요:',
'ownership_fix_hint' => '※ www-data는 웹 서버 사용자/그룹입니다. 사용 환경에 따라 nginx, apache 등으로 변경하세요.',
'ownership_detected_hint' => '※ 현재 웹 서버 사용자: :user (자동 감지)',
'permission_fix_guide' => '아래 명령어를 터미널 또는 SSH에서 실행하여 권한을 부여하세요:',
'ownership_mismatch_option_group' => '[권장] 그룹 공유 방식 — 웹서버 그룹으로 변경하여 쓰기 권한 부여:',
'ownership_mismatch_option_chown' => '[대안 1] 소유자 변경 — 소유자를 웹서버 사용자로 변경:',
'ownership_mismatch_option_777' => '[대안 2] 최후 수단 — 모든 사용자에게 쓰기 허용 (보안 약화, 비권장):',
'ownership_mismatch_hint' => '※ 현재 소유자: :owner / 웹서버 실행 사용자: :web_user. 위 3가지 중 환경에 맞는 방법을 선택하세요.',
'permission_fallback_title' => '위 명령어로 해결되지 않는 경우',
'permission_fallback_detail' => '전용 서버 등 일부 환경에서는 다음 명령어가 필요할 수 있습니다: chmod -R 775 :path',
'permission_windows_hint' => '※ Windows 환경에서는 관리자 권한으로 명령 프롬프트(cmd)를 열고 실행하세요. 또는 폴더 속성 → 보안 탭에서 권한을 설정할 수 있습니다.',
'directory_create_guide' => '아래 명령어를 실행하여 누락된 디렉토리를 생성하세요:',
@@ -761,6 +819,7 @@ ini_set(\'zlib.output_compression\', \'off\');
'cli_status_checking' => '확인 중...',
'cli_status_verified' => '✓ 확인됨',
'cli_status_not_verified' => '✗ 미확인',
'cli_status_optional_bundled' => '— 선택사항 (번들 모드)',
// 환경 체크 강화
'required_functions' => '필수 함수',
+49 -39
View File
@@ -48,6 +48,8 @@ $storageResult = $storageCheck['results']['storage'] ?? null;
// 에러 타입에 따른 제목 표시
if ($storageResult['error_type'] === 'not_exists') {
echo lang('storage_not_exists');
} elseif ($storageResult['error_type'] === 'ownership_mismatch') {
echo lang('storage_ownership_mismatch');
} elseif ($storageResult['error_type'] === 'not_writable') {
echo lang('storage_not_writable');
} else {
@@ -61,6 +63,12 @@ $storageResult = $storageCheck['results']['storage'] ?? null;
// 에러 타입에 따른 메시지 표시
if ($storageResult['error_type'] === 'not_exists') {
echo lang('storage_not_exists_message');
} elseif ($storageResult['error_type'] === 'ownership_mismatch') {
echo lang('storage_ownership_mismatch_message', [
'owner' => $storageResult['owner'] ?? '?',
'web_user' => $storageResult['web_server_user'] ?? 'www-data',
'permissions' => $storageResult['permissions'] ?? '?',
]);
} elseif ($storageResult['error_type'] === 'not_writable') {
echo lang('storage_not_writable_message');
} else {
@@ -70,11 +78,9 @@ $storageResult = $storageCheck['results']['storage'] ?? null;
</p>
<div class="alert-details">
<?php
$detectedUser = getWebServerUser();
$webGroup = getWebServerGroup() ?? getWebServerUser() ?? 'www-data';
$storagePath = BASE_PATH . '/storage';
$relativeStorage = './storage';
?>
<?php $relativeStorage = './storage'; ?>
<?php if ($storageResult['error_type'] === 'not_exists'): ?>
<!-- 디렉토리 미존재: mkdir 명령어 안내 -->
<p class="fix-guide-label"><?= lang('directory_create_guide') ?></p>
@@ -95,7 +101,35 @@ $storageResult = $storageCheck['results']['storage'] ?? null;
<?php endif; ?>
<button class="btn-copy" onclick="copyWelcomeCommand(this)"><?= lang('copy_command') ?></button>
</div>
<?php elseif (in_array($storageResult['error_type'], ['not_writable', 'permission_too_low', 'permission_low_but_writable', 'subdirectory_issues'])): ?>
<?php elseif ($storageResult['error_type'] === 'ownership_mismatch'): ?>
<?php
$webUser = $storageResult['web_server_user'] ?? 'www-data';
$owner = $storageResult['owner'] ?? 'unknown';
// 그룹 쓰기 비트(020) 이미 설정되어 있으면 chmod 생략 (예: 775 → chgrp만)
$storagePermsOctal = octdec($storageResult['permissions'] ?? '755');
$storageGroupWritable = ($storagePermsOctal & 0020) !== 0;
$groupCommand = $storageGroupWritable
? "sudo chgrp -R {$webUser} {$storagePath}"
: "sudo chgrp -R {$webUser} {$storagePath} && sudo chmod -R 775 {$storagePath}";
?>
<!-- 소유권 불일치: 3가지 해결 옵션 제시 (공유 그룹 권장 > 소유자 변경 > 777) -->
<p class="fix-guide-label"><?= lang('ownership_mismatch_option_group') ?></p>
<div class="code-box">
<pre class="fix-command"><?= htmlspecialchars($groupCommand) ?></pre>
<button class="btn-copy" onclick="copyWelcomeCommand(this)"><?= lang('copy_command') ?></button>
</div>
<p class="fix-guide-label" style="margin-top: 1rem;"><?= lang('ownership_mismatch_option_chown') ?></p>
<div class="code-box">
<pre class="fix-command"><?= htmlspecialchars("sudo chown -R {$webUser}:{$webUser} {$storagePath}") ?></pre>
<button class="btn-copy" onclick="copyWelcomeCommand(this)"><?= lang('copy_command') ?></button>
</div>
<p class="fix-guide-label" style="margin-top: 1rem;"><?= lang('ownership_mismatch_option_777') ?></p>
<div class="code-box">
<pre class="fix-command"><?= htmlspecialchars("chmod -R 777 {$storagePath}") ?></pre>
<button class="btn-copy" onclick="copyWelcomeCommand(this)"><?= lang('copy_command') ?></button>
</div>
<p class="fix-guide-hint" style="margin-top: 0.75rem;"><?= lang('ownership_mismatch_hint', ['owner' => htmlspecialchars($owner), 'web_user' => htmlspecialchars($webUser)]) ?></p>
<?php elseif (in_array($storageResult['error_type'], ['not_writable', 'not_readable', 'subdirectory_issues'])): ?>
<?php if (isWindows()): ?>
<!-- Windows: icacls 명령어 안내 -->
<p class="fix-guide-label"><?= lang('permission_fix_guide') ?></p>
@@ -110,36 +144,17 @@ $storageResult = $storageCheck['results']['storage'] ?? null;
</div>
<p class="fix-guide-hint"><?= lang('permission_windows_hint') ?></p>
<?php else: ?>
<!-- Linux/Mac: chmod (+ chown if owner ≠ web user) 명령어 안내 -->
<?php $ownerIsWebUser = $detectedUser && ($storageResult['owner'] ?? null) === $detectedUser; ?>
<?php if ($ownerIsWebUser): ?>
<p class="fix-guide-label"><?= lang('permission_fix_guide') ?></p>
<div class="code-box">
<pre class="fix-command"><?= htmlspecialchars('chmod -R 2770 ' . $storagePath) ?></pre>
<button class="btn-copy" onclick="copyWelcomeCommand(this)"><?= lang('copy_command') ?></button>
</div>
<p class="fix-guide-hint"><?= lang('or_relative_path') ?></p>
<div class="code-box">
<pre class="fix-command"><?= htmlspecialchars('chmod -R 2770 ' . $relativeStorage) ?></pre>
<button class="btn-copy" onclick="copyWelcomeCommand(this)"><?= lang('copy_command') ?></button>
</div>
<?php else: ?>
<p class="fix-guide-label"><?= lang('ownership_fix_guide') ?></p>
<div class="code-box">
<pre class="fix-command"><?= htmlspecialchars('sudo chown -R ' . $webGroup . ':' . $webGroup . ' ' . $storagePath . ' && sudo chmod -R 2770 ' . $storagePath) ?></pre>
<button class="btn-copy" onclick="copyWelcomeCommand(this)"><?= lang('copy_command') ?></button>
</div>
<p class="fix-guide-hint"><?= lang('or_relative_path') ?></p>
<div class="code-box">
<pre class="fix-command"><?= htmlspecialchars('sudo chown -R ' . $webGroup . ':' . $webGroup . ' ' . $relativeStorage . ' && sudo chmod -R 2770 ' . $relativeStorage) ?></pre>
<button class="btn-copy" onclick="copyWelcomeCommand(this)"><?= lang('copy_command') ?></button>
</div>
<?php if ($detectedUser): ?>
<p class="fix-guide-hint"><?= lang('ownership_detected_hint', ['user' => htmlspecialchars($detectedUser)]) ?></p>
<?php else: ?>
<p class="fix-guide-hint"><?= lang('ownership_fix_hint') ?></p>
<?php endif; ?>
<?php endif; ?>
<!-- Linux/Mac: chmod 755 단일 명령어 (chown 의존성 제거) -->
<p class="fix-guide-label"><?= lang('permission_fix_guide') ?></p>
<div class="code-box">
<pre class="fix-command"><?= htmlspecialchars('chmod -R 755 ' . $storagePath) ?></pre>
<button class="btn-copy" onclick="copyWelcomeCommand(this)"><?= lang('copy_command') ?></button>
</div>
<p class="fix-guide-hint"><?= lang('or_relative_path') ?></p>
<div class="code-box">
<pre class="fix-command"><?= htmlspecialchars('chmod -R 755 ' . $relativeStorage) ?></pre>
<button class="btn-copy" onclick="copyWelcomeCommand(this)"><?= lang('copy_command') ?></button>
</div>
<?php endif; ?>
<?php endif; ?>
<div class="permission-details">
@@ -149,11 +164,6 @@ $storageResult = $storageCheck['results']['storage'] ?? null;
<span class="permission-badge badge-current"><?= htmlspecialchars($storageResult['group'] ?? lang('unknown')) ?></span>
<span class="permission-label"><?= lang('current_permissions') ?>:</span>
<span class="permission-badge badge-current"><?= $storageResult['permissions'] ?></span>
<?php if (in_array($storageResult['error_type'], ['permission_too_low', 'permission_low_but_writable'])): ?>
<span class="permission-arrow">→</span>
<span class="permission-label"><?= lang('required_permissions') ?>:</span>
<span class="permission-badge badge-required"><?= $storageResult['required_permissions'] ?></span>
<?php endif; ?>
</div>
</div>
</div>
+175 -6
View File
@@ -373,6 +373,125 @@ $dbReadHash = getDatabaseFieldHash($formData, 'db_read');
</div>
</div>
<!-- ========== Vendor 설치 방식 ========== -->
<?php
$bundleZipExists = file_exists(BASE_PATH . '/vendor-bundle.zip');
$zipArchiveAvailable = class_exists('ZipArchive');
$procOpenAvailable = function_exists('proc_open')
&& !in_array('proc_open', array_map('trim', explode(',', (string) ini_get('disable_functions'))), true);
$bundleAvailable = $bundleZipExists && $zipArchiveAvailable;
$composerAvailable = $procOpenAvailable;
$currentVendorMode = $formData['vendor_mode'] ?? 'auto';
?>
<div class="requirement-card">
<div class="requirement-card-header">
<h2 class="card-title">Vendor 설치 방식</h2>
<p class="card-description">
PHP 패키지 의존성(vendor/) 을 어떤 방식으로 설치할지 선택합니다.
</p>
</div>
<div class="requirement-card-body">
<div class="vendor-mode-cards">
<!-- 자동 (권장) -->
<label class="vendor-mode-card <?= $currentVendorMode === 'auto' ? 'selected' : '' ?>">
<input type="radio" name="vendor_mode" value="auto" class="vendor-mode-card-input"
<?= $currentVendorMode === 'auto' ? 'checked' : '' ?>>
<div class="vendor-mode-card-header">
<div class="vendor-mode-card-icon"><?= getSvgIcon('magic') ?: '✨' ?></div>
<div class="vendor-mode-card-title-wrapper">
<h3 class="vendor-mode-card-title">자동</h3>
<span class="vendor-mode-card-badge vendor-mode-card-badge-recommended">권장</span>
</div>
<div class="vendor-mode-card-check"><?= getSvgIcon('check-circle') ?: '◉' ?></div>
</div>
<p class="vendor-mode-card-description">
Composer 사용 가능 시 Composer, 불가 시 번들 vendor 사용
</p>
<p class="vendor-mode-card-status vendor-mode-card-status-ok">
<?= getSvgIcon('check') ?: '✓' ?> 환경 자동 감지
</p>
</label>
<!-- Composer 실행 -->
<label class="vendor-mode-card <?= $currentVendorMode === 'composer' ? 'selected' : '' ?> <?= $composerAvailable ? '' : 'disabled' ?>">
<input type="radio" name="vendor_mode" value="composer" class="vendor-mode-card-input"
<?= $currentVendorMode === 'composer' ? 'checked' : '' ?>
<?= $composerAvailable ? '' : 'disabled' ?>>
<div class="vendor-mode-card-header">
<div class="vendor-mode-card-icon"><?= getSvgIcon('terminal') ?: '⚙' ?></div>
<div class="vendor-mode-card-title-wrapper">
<h3 class="vendor-mode-card-title">Composer 실행</h3>
<span class="vendor-mode-card-badge vendor-mode-card-badge-dev">개발 환경</span>
</div>
<div class="vendor-mode-card-check"><?= getSvgIcon('check-circle') ?: '◉' ?></div>
</div>
<p class="vendor-mode-card-description">
composer install 명령으로 최신 버전 설치 (인터넷 + proc_open 필수)
</p>
<?php if (!$composerAvailable): ?>
<p class="vendor-mode-card-status vendor-mode-card-status-error">
<?= getSvgIcon('warning') ?: '⚠' ?> proc_open() 차단됨 — 사용 불가
</p>
<?php else: ?>
<p class="vendor-mode-card-status vendor-mode-card-status-ok">
<?= getSvgIcon('check') ?: '✓' ?> proc_open 사용 가능
</p>
<?php endif; ?>
</label>
<!-- 번들 Vendor 사용 -->
<label class="vendor-mode-card <?= $currentVendorMode === 'bundled' ? 'selected' : '' ?> <?= $bundleAvailable ? '' : 'disabled' ?>">
<input type="radio" name="vendor_mode" value="bundled" class="vendor-mode-card-input"
<?= $currentVendorMode === 'bundled' ? 'checked' : '' ?>
<?= $bundleAvailable ? '' : 'disabled' ?>>
<div class="vendor-mode-card-header">
<div class="vendor-mode-card-icon"><?= getSvgIcon('package') ?: '📦' ?></div>
<div class="vendor-mode-card-title-wrapper">
<h3 class="vendor-mode-card-title">번들 Vendor 사용</h3>
<span class="vendor-mode-card-badge vendor-mode-card-badge-shared">공유 호스팅</span>
</div>
<div class="vendor-mode-card-check"><?= getSvgIcon('check-circle') ?: '◉' ?></div>
</div>
<p class="vendor-mode-card-description">
vendor-bundle.zip 을 추출 (오프라인 설치, composer 불필요)
</p>
<?php if (!$zipArchiveAvailable): ?>
<p class="vendor-mode-card-status vendor-mode-card-status-error">
<?= getSvgIcon('warning') ?: '⚠' ?> ZipArchive 확장 미설치 — 사용 불가
</p>
<?php elseif (!$bundleZipExists): ?>
<p class="vendor-mode-card-status vendor-mode-card-status-error">
<?= getSvgIcon('warning') ?: '⚠' ?> vendor-bundle.zip 파일 없음 — 사용 불가
</p>
<?php else: ?>
<p class="vendor-mode-card-status vendor-mode-card-status-ok">
<?= getSvgIcon('check') ?: '✓' ?> vendor-bundle.zip 발견
</p>
<?php endif; ?>
</label>
</div>
<p class="form-help" style="margin-top: var(--spacing-md);">
이 설정은 추후 <code>php artisan core:update --vendor-mode=...</code> 옵션으로 변경할 수 있습니다.
</p>
<script>
// Vendor 모드 카드 — 라디오 변경 시 .selected 클래스 동기화
(function () {
const cards = document.querySelectorAll('.vendor-mode-card');
cards.forEach(function (card) {
const input = card.querySelector('.vendor-mode-card-input');
if (!input) return;
input.addEventListener('change', function () {
if (input.checked) {
cards.forEach(function (c) { c.classList.remove('selected'); });
card.classList.add('selected');
}
});
});
})();
</script>
</div>
</div>
<!-- 네비게이션 -->
<div class="btn-group btn-group-spread">
<button type="button" onclick="goToStep(2)" class="btn btn-secondary">
@@ -407,6 +526,22 @@ window.CliValidator = {
composerVerified: false,
cliRequired: false, // 기본 php 사용 불가 시 true
/**
* Composer 검증이 필수인지 여부 — vendor_mode='bundled' 에서는 선택사항.
*/
isComposerRequired() {
const mode = this.getSelectedVendorMode();
return mode !== 'bundled';
},
/**
* 현재 선택된 vendor_mode 값 (auto/composer/bundled).
*/
getSelectedVendorMode() {
const input = document.querySelector('input[name="vendor_mode"]:checked');
return input ? input.value : 'auto';
},
setPhpVerified(verified) {
this.phpVerified = verified;
this.updateStatusDisplay();
@@ -426,7 +561,13 @@ window.CliValidator = {
// 섹션이 닫혀 있고 필수가 아니면 검증 불필요
if (!this.cliRequired) return true;
}
return this.phpVerified && this.composerVerified;
if (!this.phpVerified) return false;
// Composer 는 vendor_mode='bundled' 에서는 검증 불필요
if (this.isComposerRequired() && !this.composerVerified) return false;
return true;
},
updateStatusDisplay() {
@@ -442,10 +583,16 @@ window.CliValidator = {
: '<?= lang("cli_status_not_verified") ?>';
phpStatus.style.color = this.phpVerified ? 'var(--success-color)' : 'var(--error-color)';
composerStatus.textContent = this.composerVerified
? '<?= lang("cli_status_verified") ?>'
: '<?= lang("cli_status_not_verified") ?>';
composerStatus.style.color = this.composerVerified ? 'var(--success-color)' : 'var(--error-color)';
const composerOptional = !this.isComposerRequired();
if (composerOptional) {
composerStatus.textContent = '<?= lang("cli_status_optional_bundled") ?>';
composerStatus.style.color = 'var(--text-muted-color, #888)';
} else {
composerStatus.textContent = this.composerVerified
? '<?= lang("cli_status_verified") ?>'
: '<?= lang("cli_status_not_verified") ?>';
composerStatus.style.color = this.composerVerified ? 'var(--success-color)' : 'var(--error-color)';
}
},
updateSubmitButton() {
@@ -453,6 +600,19 @@ window.CliValidator = {
}
};
// vendor_mode 라디오 변경 시 CLI 검증 상태 표시 갱신 (Composer 검증 필수/선택 전환)
document.addEventListener('change', function (e) {
if (e.target && e.target.name === 'vendor_mode') {
window.CliValidator.updateStatusDisplay();
// bundled 모드 전환 시 Composer 설치 안내 숨김
if (e.target.value === 'bundled') {
const guide = document.getElementById('composer-install-guide');
if (guide) guide.style.display = 'none';
}
}
});
// PHP CLI 설정 토글
document.getElementById('show-php-cli-settings')?.addEventListener('change', function() {
const section = document.getElementById('php-cli-section');
@@ -656,9 +816,18 @@ async function testComposer() {
}
/**
* Composer 설치 안내를 PHP 경로 반영하여 동적 생성
* Composer 설치 안내를 PHP 경로 반영하여 동적 생성.
*
* vendor_mode='bundled' 에서는 Composer 가 불필요하므로 안내를 띄우지 않는다.
*/
function showComposerInstallGuide() {
// 번들 모드에서는 Composer 가 불필요 → 안내 생략
if (window.CliValidator && !window.CliValidator.isComposerRequired()) {
const g = document.getElementById('composer-install-guide');
if (g) g.style.display = 'none';
return;
}
const guide = document.getElementById('composer-install-guide');
if (!guide) return;
+18 -1
View File
@@ -137,6 +137,19 @@
</div>
</div>
<!-- 의존성 경고 (누락 의존성 존재 시 표시) -->
<div id="dependency-warning" class="alert alert-warning hidden">
<h4 class="alert-title">
<i class="fas fa-exclamation-triangle"></i>
<?= htmlspecialchars(lang('dependency_warning_title')) ?>
</h4>
<p><?= htmlspecialchars(lang('dependency_warning_description')) ?></p>
<ul id="dependency-warning-list" class="dependency-warning-list"></ul>
<button type="button" onclick="autoSelectMissingDependencies()" class="btn btn-sm btn-primary">
<?= htmlspecialchars(lang('dependency_auto_select')) ?>
</button>
</div>
<!-- 네비게이션 -->
<div class="btn-group btn-group-spread">
<button type="button" onclick="goToStep(3)" class="btn btn-secondary">
@@ -161,6 +174,10 @@ window.EXTENSION_LABELS = {
saving: <?= json_encode(lang('saving')) ?>,
save_failed: <?= json_encode(lang('save_failed')) ?>,
next: <?= json_encode(lang('next')) ?>,
extension_load_failed: <?= json_encode(lang('extension_load_failed')) ?>
extension_load_failed: <?= json_encode(lang('extension_load_failed')) ?>,
dep_auto_badge_label: <?= json_encode(lang('dep_auto_badge_label')) ?>,
dep_lock_message: <?= json_encode(lang('dep_lock_message')) ?>,
dep_version_required: <?= json_encode(lang('dep_version_required')) ?>,
dep_version_available: <?= json_encode(lang('dep_version_available')) ?>
};
</script>
+34 -2
View File
@@ -77,12 +77,44 @@ $config = $state['config'] ?? $_SESSION['install_config'] ?? [];
echo renderInstallResultSection('failure', 'error', 'installation_failed', '', $failureButtons);
?>
<div class="alert alert-warning" id="install-warning">
<!-- 설치 진행 방식 선택 (SSE / 폴링) -->
<div class="requirement-card installation-mode-card" id="installation-mode-card">
<div class="requirement-card-header">
<h3 class="requirement-card-title"><?= htmlspecialchars(lang('installation_mode_label')) ?></h3>
</div>
<div class="requirement-card-body">
<div class="installation-mode-options">
<label class="installation-mode-option">
<input type="radio" name="installation_mode" value="sse" checked>
<div class="installation-mode-text">
<strong><?= htmlspecialchars(lang('installation_mode_sse_title')) ?></strong>
<span class="installation-mode-desc"><?= htmlspecialchars(lang('installation_mode_sse_desc')) ?></span>
</div>
</label>
<label class="installation-mode-option">
<input type="radio" name="installation_mode" value="polling">
<div class="installation-mode-text">
<strong><?= htmlspecialchars(lang('installation_mode_polling_title')) ?></strong>
<span class="installation-mode-desc"><?= htmlspecialchars(lang('installation_mode_polling_desc')) ?></span>
</div>
</label>
</div>
</div>
</div>
<!-- 설치 시작 버튼 (초기 상태, 설치 시작 후 숨김) -->
<div id="installation-start-section" class="installation-start-section" style="display: none;">
<button id="start-installation-btn" class="btn btn-primary btn-lg" type="button" onclick="onStartInstallationClick()">
<?= htmlspecialchars(lang('start_installation_button')) ?>
</button>
</div>
<div class="alert alert-warning" id="install-warning" style="display: none;">
⚠ <?= htmlspecialchars(lang('do_not_close_page')) ?>
</div>
<!-- 설치 진행 상황 카드 -->
<div class="requirement-card">
<div class="requirement-card" id="installation-progress-card" style="display: none;">
<div class="requirement-card-header" id="installation-card-header" onclick="toggleInstallationCard()">
<h3 class="requirement-card-title">
<?= htmlspecialchars(lang('progress_status')) ?>