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

+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}' 실행 후 재시도하세요.";
}