Merge branch 'develop' of github-gnuboard:gnuboard/dev-g7 into thisgun/pay_develop

This commit is contained in:
thisgun committed 2026-07-02 20:11:44 +09:00
commit 479d537dfb
133 files changed
+955 -268

No files matched your search

@@ -806,6 +806,7 @@ class CoreUpdateCommand extends Command
// 페이로드만 보관한다 (각각 UpgradeHandoffException 재구성 / silent skip 가드용).
$handoffPayload = null;
$stepsExecuted = null;
$stepsDiscovered = null;
while (! feof($pipes[1])) {
$line = fgets($pipes[1]);
if ($line !== false) {
@@ -837,7 +838,13 @@ class CoreUpdateCommand extends Command
$decoded = json_decode($json, true);
if (is_array($decoded) && isset($decoded['count']) && is_int($decoded['count']) && $decoded['count'] >= 0) {
$stepsExecuted = $decoded['count'];
$log('[spawn] 실행된 step 수: '.$stepsExecuted);
// discovered 는 신버전 자식만 발행하는 필드. 구버전 자식(필드 부재)은
// null 로 남아 handleSpawnExit 가 기존(레거시) 판정 경로를 탄다.
if (isset($decoded['discovered']) && is_int($decoded['discovered']) && $decoded['discovered'] >= 0) {
$stepsDiscovered = $decoded['discovered'];
}
$log('[spawn] 실행된 step 수: '.$stepsExecuted
.($stepsDiscovered !== null ? " (발견 {$stepsDiscovered})" : ''));
continue;
}
@@ -852,6 +859,50 @@ class CoreUpdateCommand extends Command
fclose($pipes[2]);
$exitCode = proc_close($process);
return $this->handleSpawnExit(
$exitCode,
$handoffPayload,
$stepsExecuted,
$stepsDiscovered,
$fromVersion,
$toVersion,
$log,
);
}
/**
* spawn 자식 종료 후 exit code · 신호를 해석해 성공/실패/핸드오프를 판정합니다.
*
* 판정 규칙 (exit=0 경우):
* - `[STEPS_EXECUTED]` 신호 미수신 (`$stepsExecuted === null`) → fail-fast.
* 이전 버전 자식 (신호 미발행) 또는 silent skip 의심.
* - executed=0 인데 **discovered>0** → fail-fast. 범위 내에 스텝 파일이 실제로
* 존재하는데 자식이 하나도 실행하지 못함 (gnuboard/g7#28 silent skip — 케이스 A).
* - executed=0 이고 **discovered=0** → 정상 통과. 해당 from~to 범위에 스텝 파일이
* 애초에 없는 릴리즈 (예: 데이터/설정 변경 없는 패치). from<to 여도 실패 아님 (케이스 B).
* - discovered 신호 부재 (`null`, 구버전 자식) + executed=0 + from<to → 레거시 판정 유지
* (fail-fast). 신버전 자식은 항상 discovered 를 발행하므로 이 경로는 구버전 자식 한정.
*
* @param int $exitCode 자식 프로세스 종료 코드
* @param array|null $handoffPayload 파싱된 [HANDOFF] 페이로드 (없으면 null)
* @param int|null $stepsExecuted 실행된 스텝 수 ([STEPS_EXECUTED] 미수신 시 null)
* @param int|null $stepsDiscovered 범위 내 발견된 스텝 파일 수 (구버전 자식은 null)
* @param string $fromVersion 업그레이드 시작 버전
* @param string $toVersion 업그레이드 대상 버전
* @param \Closure $log 로그 수집 콜백
* @return bool spawn 성공 여부 (mode=fallback 실패 시 false — 호출자 in-process fallback)
*
* @throws UpgradeHandoffException 핸드오프 수신 또는 mode=abort 실패 시
*/
private function handleSpawnExit(
int $exitCode,
?array $handoffPayload,
?int $stepsExecuted,
?int $stepsDiscovered,
string $fromVersion,
string $toVersion,
\Closure $log,
): bool {
if ($exitCode === UpgradeHandoffException::EXIT_CODE && $handoffPayload !== null) {
$log("spawn 핸드오프 종료 (exit={$exitCode})");
@@ -866,9 +917,7 @@ class CoreUpdateCommand extends Command
}
if ($exitCode === 0) {
// silent skip 가드 — 자식이 [STEPS_EXECUTED] 신호를 발행하지 않거나, step 0건
// 실행한 채 exit=0 으로 종료한 경우. 이전 버전 자식 (beta.5 이전 디스크) 또는
// 자식이 비정상 종료 직전 silent skip 한 상태로 추정. fail-fast 모드 가드 적용.
// 신호 미수신 — 이전 버전 자식 (신호 미발행) 또는 silent skip 의심. fail-fast.
if ($stepsExecuted === null) {
return $this->failSpawnWithMode(
'spawn 자식이 [STEPS_EXECUTED] 신호 미발행 — 이전 버전 자식 또는 silent skip 의심',
@@ -878,9 +927,27 @@ class CoreUpdateCommand extends Command
);
}
if ($stepsExecuted === 0 && version_compare($fromVersion, $toVersion, '<')) {
// executed=0 + discovered=0 → 범위 내 스텝 파일 부재. 정상 통과 (케이스 B).
// 스텝이 필요 없는 릴리즈(데이터/설정 변경 없음)를 실패로 오판하지 않는다.
if ($stepsExecuted === 0 && $stepsDiscovered === 0) {
$log("spawn 완료 (exit=0, 실행할 스텝 없음 — 범위 내 스텝 파일 부재, from={$fromVersion} to={$toVersion})");
return true;
}
// executed=0 + (discovered>0 또는 discovered 신호 부재) + from<to → fail-fast.
// discovered>0: 스텝 파일이 있는데 자식이 실행 못함 (gnuboard/g7#28 케이스 A).
// discovered=null: 구버전 자식 (discovered 미발행) — 레거시 판정 유지.
if ($stepsExecuted === 0
&& $stepsDiscovered !== 0
&& version_compare($fromVersion, $toVersion, '<')) {
return $this->failSpawnWithMode(
sprintf('spawn 자식 exit=0 이지만 step 0건 실행 — 의도된 동작이 아님 (from=%s to=%s)', $fromVersion, $toVersion),
sprintf(
'spawn 자식 exit=0 이지만 step 0건 실행 — 의도된 동작이 아님 (from=%s to=%s%s)',
$fromVersion,
$toVersion,
$stepsDiscovered !== null ? ", 발견 {$stepsDiscovered}건" : '',
),
$log,
$fromVersion,
$toVersion,
@@ -164,6 +164,7 @@ class ExecuteUpgradeStepsCommand extends Command
}
$stepsExecuted = 0;
$stepsDiscovered = 0;
try {
$service->runUpgradeSteps(
@@ -174,6 +175,9 @@ class ExecuteUpgradeStepsCommand extends Command
$stepsExecuted++;
},
$force,
function (int $discovered) use (&$stepsDiscovered): void {
$stepsDiscovered = $discovered;
},
);
} catch (UpgradeHandoffException $e) {
// 업그레이드 스텝이 새 PHP 프로세스 재진입을 요청했다.
@@ -221,6 +225,7 @@ class ExecuteUpgradeStepsCommand extends Command
// mode=fallback 시 in-process 진행 (`spawn_failure_mode`).
$this->line('[STEPS_EXECUTED] '.json_encode([
'count' => $stepsExecuted,
'discovered' => $stepsDiscovered,
'fromVersion' => $from,
'toVersion' => $to,
], JSON_UNESCAPED_UNICODE));
+96 -28
View File
@@ -53,15 +53,25 @@ class FilePermissionHelper
$destPath = $destination.DIRECTORY_SEPARATOR.$itemName;
// symlink 자체 보존: target 추적 없이 동일 symlink 재생성.
// symlink / Windows junction 자체 보존: target 추적 없이 동일 링크 재생성.
// SplFileInfo::isDir() 가 symlink 를 추적하므로 검사 순서가 isDir() 보다 먼저여야 한다.
// 미적용 시 `public/storage` 등 symlink 가 target 디렉토리 내용으로 복사되어 백업/복원 양쪽에서 손상.
if ($item->isLink()) {
if (static::copySymlink($item->getPathname(), $destPath)) {
// 미적용 시 `public/storage` 등 링크가 target 디렉토리 내용으로 복사되어 백업/복원 양쪽에서 손상.
//
// Windows JUNCTION(`mklink /J`)은 reparse point 지만 PHP `isLink()`/`isDir()` 이 모두
// false 를 반환한다(`storage:link` 가 Windows 에서 생성하는 형태). isLink() 만 검사하면
// junction 이 파일로 오판되어 copyFile → `copy(디렉토리)` 로 코어 업데이트가 실패한다.
// isReparsePoint() 로 junction 도 이 분기에 포함시킨다.
if ($item->isLink() || static::isReparsePoint($item->getPathname())) {
if (static::copyLink($item->getPathname(), $destPath)) {
continue;
}
// 복원 실패 (Windows SeCreateSymbolicLink 권한 부족 등) — 일반 복사로 fall-through.
// 단, junction 은 isDir() 이 false 라 아래 else 분기의 copyFile 로 새어 파일 복사가
// 다시 실패하므로, fall-through 대신 skip 하여 손상 없이 넘어간다.
// 운영자가 추후 `php artisan storage:link` 수동 실행으로 회복 가능.
if (! $item->isLink()) {
continue;
}
}
if ($item->isDir()) {
@@ -79,25 +89,63 @@ class FilePermissionHelper
}
/**
* symlink 자체를 보존 복사합니다 (target 미추적).
* 경로가 Windows JUNCTION 등 PHP `isLink()` 가 인식하지 못하는 reparse point 인지 판정합니다.
*
* 기존 dest 가 symlink 또는 파일이면 unlink, 디렉토리면 deleteDirectory 후 symlink 재생성.
* readlink / symlink 실패 시 false 반환 — 호출자가 일반 복사로 fall-through.
* Windows JUNCTION(`mklink /J`)은 디렉토리 reparse point 로, `is_link()` / `is_file()` /
* `is_dir()` 이 **모두** false 를 반환한다(그러나 경로 항목으로는 존재하며 `readlink()` 로
* target 을 얻을 수 있다). `php artisan storage:link` 가 Windows 에서 생성하는
* `public/storage` 가 이 형태다.
*
* Windows 환경에서 PHP `symlink()` 는 `SeCreateSymbolicLink` 권한이 필요하며 일반 사용자는
* 권한이 없을 가능성이 높다. 실패 시 warning 로그 후 false 반환하여 호출자가 일반 복사로
* fall-through 하도록 한다. 운영자는 업그레이드 후 `php artisan storage:link` 등 수동
* 명령으로 symlink 를 회복할 수 있다.
* 주의: Windows 의 `readlink()` 는 일반 파일/디렉토리에도 자기 경로를 반환하므로 junction
* 판별 기준이 될 수 없다. 따라서 "존재하는 경로인데 link/file/dir 어디에도 해당하지 않음"
* 을 판정 기준으로 삼는다. 여기에 추가로 `readlink()` 성공(!== false)을 요구해 존재하지
* 않는 경로를 배제한다.
*
* @param string $source 소스 symlink 경로
* @param string $destination 대상 symlink 경로
* @return bool symlink 복원 성공 여부 (false 면 호출자가 일반 복사로 폴백)
* 일반 symlink(`is_link()` true)는 호출부가 별도로 처리하므로 여기서는 false 를 반환한다.
* junction 은 Windows 전용이므로 비-Windows 에서는 항상 false.
*
* @param string $path 검사할 경로
* @return bool junction 등 isLink() 미인식 reparse point 여부
*/
protected static function copySymlink(string $source, string $destination): bool
protected static function isReparsePoint(string $path): bool
{
if (PHP_OS_FAMILY !== 'Windows') {
return false;
}
// 일반 symlink / 파일 / 디렉토리는 각 검사가 true → junction 아님.
if (is_link($path) || is_file($path) || is_dir($path)) {
return false;
}
// 위 셋에 모두 해당하지 않으면서 readlink 가 target 을 반환하면 junction(reparse point).
return @readlink($path) !== false;
}
/**
* symlink 또는 Windows junction 자체를 보존 복사합니다 (target 미추적).
*
* 기존 dest 가 symlink 또는 파일이면 unlink, 디렉토리면 deleteDirectory 후 링크 재생성.
* readlink 실패 시 false 반환 — 호출자가 일반 복사로 fall-through.
*
* 재생성 전략:
* - 일반 symlink: `symlink()`
* - target 이 디렉토리인 경우(Windows junction 포함): `symlink()` 실패 시 `mklink /J` 로 폴백.
* Windows 에서 PHP `symlink()` 는 `SeCreateSymbolicLink` 권한이 필요하지만 junction 은
* 권한 없이 생성 가능하므로, junction 복원의 실질 경로가 된다.
*
* 모든 재생성 시도 실패 시 warning 로그 후 false 반환. 운영자는 업그레이드 후
* `php artisan storage:link` 등 수동 명령으로 링크를 회복할 수 있다.
*
* @param string $source 소스 링크(symlink/junction) 경로
* @param string $destination 대상 링크 경로
* @return bool 링크 복원 성공 여부 (false 면 호출자가 일반 복사로 폴백)
*/
protected static function copyLink(string $source, string $destination): bool
{
$target = @readlink($source);
if ($target === false) {
Log::warning('copySymlink: readlink 실패 — 일반 복사로 폴백', ['source' => $source]);
Log::warning('copyLink: readlink 실패 — 일반 복사로 폴백', ['source' => $source]);
return false;
}
@@ -109,17 +157,29 @@ class FilePermissionHelper
File::deleteDirectory($destination);
}
if (! @symlink($target, $destination)) {
Log::warning('copySymlink: symlink 생성 실패 — 일반 복사로 폴백', [
'source' => $source,
'destination' => $destination,
'target' => $target,
]);
return false;
if (@symlink($target, $destination)) {
return true;
}
return true;
// symlink 실패 + target 이 디렉토리 → Windows junction 으로 폴백 재생성.
if (PHP_OS_FAMILY === 'Windows' && is_dir($target)) {
exec(
'cmd /c mklink /J '.escapeshellarg($destination).' '.escapeshellarg($target).' 2>&1',
$out,
$code
);
if ($code === 0 && is_dir($destination)) {
return true;
}
}
Log::warning('copyLink: 링크 생성 실패 — 일반 복사로 폴백', [
'source' => $source,
'destination' => $destination,
'target' => $target,
]);
return false;
}
/**
@@ -157,11 +217,19 @@ class FilePermissionHelper
// 소스에 존재하지 않는 항목만 삭제
if (! File::exists($srcPath) && ! File::isDirectory($srcPath)) {
// symlink 는 항상 unlink — File::deleteDirectory 는 is_dir() 추적 검사 후
// 재귀 삭제하므로 symlink-to-dir 인 경우 target 의 모든 파일을 삭제하는 사고
// 발생 가능. is_link() 가 isDir() 보다 먼저 평가되어야 한다.
// symlink / Windows junction 은 링크 자체만 제거 — File::deleteDirectory 는 is_dir()
// 추적 검사 후 재귀 삭제하므로 link-to-dir 인 경우 target 의 모든 파일을 삭제하는
// 사고 발생 가능. 링크 검사가 isDir() 보다 먼저 평가되어야 한다.
//
// junction 은 is_link() 가 false 지만 isReparsePoint() 가 감지한다. junction 링크
// 제거는 파일 대상 unlink 가 아닌 rmdir() 로 수행해야 target 내용을 보존한다.
if (is_link($destItem->getPathname())) {
@unlink($destItem->getPathname());
} elseif (static::isReparsePoint($destItem->getPathname())) {
// junction: rmdir 로 링크만 제거 (target 미추적). 폴백으로 unlink 시도.
if (! @rmdir($destItem->getPathname())) {
@unlink($destItem->getPathname());
}
} elseif ($destItem->isDir()) {
File::deleteDirectory($destItem->getPathname());
} else {
@@ -187,7 +187,7 @@ class AdminTemplateAssetController extends AdminBaseController
/**
* 편집기 프리뷰 전용 CSS 서빙 — 다크 셀렉터를 프리뷰 마커로 치환.
*
* PO admin 환경이 다크 테마면 `<html class="dark">` 가 조상으로 남아, 프리뷰
* 관리자 admin 환경이 다크 테마면 `<html class="dark">` 가 조상으로 남아, 프리뷰
* 프레임에서 `.dark` 를 빼도(라이트 토글) Tailwind `.dark &` 가 활성돼 프리뷰가
* 라이트로 격리되지 않는다. 이를 해소하기 위해, 편집기 진입 시에만 components.css 의
* 다크 조상 셀렉터(`.dark`)를 프리뷰 전용 마커(`.g7le-preview-dark`)로 치환해 서빙한다.
@@ -4,6 +4,7 @@ namespace App\Http\Controllers\Api\Admin;
use App\Http\Controllers\Api\Base\AdminBaseController;
use App\Http\Requests\Settings\RegenerateAppKeyRequest;
use App\Http\Requests\Settings\RestoreSettingsRequest;
use App\Http\Requests\Settings\SaveSettingsRequest;
use App\Http\Requests\Settings\TestDriverConnectionRequest;
use App\Http\Requests\Settings\TestMailRequest;
@@ -13,7 +14,7 @@ use App\Services\DriverConnectionTester;
use App\Services\DriverRegistryService;
use App\Services\SettingsService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Validation\ValidationException;
/**
@@ -137,7 +138,9 @@ class SettingsController extends AdminBaseController
$systemInfo = $this->settingsService->getSystemInfo();
return $this->success('common.success', $systemInfo);
} catch (\Exception $e) {
} catch (\Throwable $e) {
Log::error('시스템 정보 조회 실패', ['error' => $e->getMessage()]);
return $this->error('common.error_occurred', 500, $e->getMessage());
}
}
@@ -264,16 +267,13 @@ class SettingsController extends AdminBaseController
/**
* 백업에서 설정을 복원합니다.
*
* @param RestoreSettingsRequest $request 복원 요청 데이터 (백업 경로)
* @return JsonResponse 복원 결과 JSON 응답
*/
public function restore(Request $request): JsonResponse
public function restore(RestoreSettingsRequest $request): JsonResponse
{
try {
$backupPath = $request->input('backup_path');
if (empty($backupPath)) {
return $this->error('settings.backup_path_required', 422);
}
$backupPath = $request->validated('backup_path');
$result = $this->settingsService->restoreSettings($backupPath);
@@ -0,0 +1,55 @@
<?php
namespace App\Http\Requests\Settings;
use App\Extension\HookManager;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Foundation\Http\FormRequest;
/**
* 설정 복원 요청 FormRequest
*
* 백업에서 설정을 복원할 때 백업 경로를 검증합니다.
* 권한은 라우트의 permission 미들웨어(core.settings.update)가 담당합니다.
*/
class RestoreSettingsRequest extends FormRequest
{
/**
* 요청 권한을 확인합니다.
*
* 권한 검사는 permission 미들웨어 체인에 위임하므로 항상 true 를 반환합니다.
*
* @return bool 항상 true
*/
public function authorize(): bool
{
return true;
}
/**
* 검증 규칙을 반환합니다.
*
* @return array<string, ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
$rules = [
'backup_path' => 'required|string',
];
// 모듈/플러그인이 validation rules를 동적으로 추가할 수 있도록 훅 제공
return HookManager::applyFilters('core.settings.restore_validation_rules', $rules, $this);
}
/**
* 검증 오류 메시지를 반환합니다.
*
* @return array<string, string>
*/
public function messages(): array
{
return [
'backup_path.required' => __('settings.backup_path_required'),
];
}
}
+1 -1
View File
@@ -12,7 +12,7 @@ use Illuminate\Database\Eloquent\Relations\BelongsTo;
* 레이아웃 편집 중 업로드되는 파일(배경 이미지 등)을 표현한다. 파일 자체는
* 코어 StorageInterface 로 저장되고 본 모델은 저장 위치(disk/path)와 메타데이터를
* 보관한다. 템플릿 삭제 시 행은 cascadeOnDelete 로 삭제되나, 스토리지 파일
* 실삭제는 Service 가 명시적으로 수행한다(CLAUDE.md "DB CASCADE 의존 삭제 금지").
* 실삭제는 Service 가 명시적으로 수행한다(코어 규정: DB CASCADE 의존 삭제 금지).
*
* @property int $id 첨부 파일 ID
* @property int $template_id 소속 템플릿 ID
+1 -1
View File
@@ -11,7 +11,7 @@ use App\Contracts\Extension\PluginManagerInterface;
* 데이터소스 종류=websocket 편집 시 채널을 "구독 가능한 목록 기준 검색 드롭다운"으로
* 제시하기 위해, "지금 이 설치본에서 구독 가능한 채널"을 런타임 수집한다. 코어/확장이
* `getChannels()` 오버라이드로 등록한 채널명을 출처(core/module/plugin)와 함께 모은다
* (CLAUDE.md 채널 프리픽스 규약 — 코어 `core.*`, 모듈 `module.{id}.*`, 플러그인
* (코어 채널 프리픽스 규약 — 코어 `core.*`, 모듈 `module.{id}.*`, 플러그인
* `plugin.{id}.*`).
*
* 이벤트는 `HookManager::broadcast($channel, $eventName, $payload)` 호출 시점에 이름이
+11 -1
View File
@@ -1558,8 +1558,9 @@ class CoreUpdateService
* @param string $toVersion 종료 버전
* @param \Closure|null $onStep 각 스텝 실행 시 콜백 (버전 문자열 전달)
* @param bool $force true 시 fromVersion == toVersion이면 해당 버전 스텝도 포함
* @param \Closure|null $onDiscovered 범위 내 발견된 스텝 파일 수를 실행 전 1회 통지 (int 전달)
*/
public function runUpgradeSteps(string $fromVersion, string $toVersion, ?\Closure $onStep = null, bool $force = false): void
public function runUpgradeSteps(string $fromVersion, string $toVersion, ?\Closure $onStep = null, bool $force = false, ?\Closure $onDiscovered = null): void
{
// 부모 in-process fallback 진입 시 stale 메모리 가드.
//
@@ -1597,6 +1598,9 @@ class CoreUpdateService
$upgradesPath = base_path('upgrades');
if (! File::isDirectory($upgradesPath)) {
// upgrades 디렉토리 자체가 없으면 발견된 스텝 0건 — 정상 통지 후 종료.
$onDiscovered?->__invoke(0);
return;
}
@@ -1656,6 +1660,12 @@ class CoreUpdateService
uksort($steps, 'version_compare');
// 범위 내에서 발견된 스텝 파일 수(discovered)를 먼저 통지한다.
// 호출자(spawn 자식)는 이 값으로 "스텝 파일이 애초에 없어 0건(정상)" 과 "스텝 파일은
// 있는데 실행이 0건(비정상 — gnuboard/g7#28 silent skip)" 을 구분한다. onStep 은 실제 실행
// 건마다 호출되므로 executed 수만 세며, discovered 는 실행 전에 1회 통지한다.
$onDiscovered?->__invoke(count($steps));
$context = new UpgradeContext($fromVersion, $toVersion);
foreach ($steps as $version => $step) {
+65 -26
View File
@@ -822,30 +822,74 @@ class SettingsService
private function buildSystemInfo(): array
{
return [
'os_info' => php_uname('s').' '.php_uname('r'),
// php_uname / ini_get 은 disable_functions 로 차단될 수 있어 개별 격리한다.
'os_info' => $this->safeSystemProbe('os_info', fn () => php_uname('s').' '.php_uname('r'), __('common.unknown')),
'web_server' => $_SERVER['SERVER_SOFTWARE'] ?? __('common.unknown'),
'php_version' => PHP_VERSION,
'mysql_version' => $this->getDatabaseInfo(),
'mysql_version' => $this->safeSystemProbe('mysql_version', fn () => $this->getDatabaseInfo(), __('common.unknown')),
'g7_version' => config('app.version', '1.0.0'),
'g7_release_year' => config('app.release_year', '2026'),
'laravel_version' => app()->version(),
'environment' => app()->environment(),
'cpu_info' => $this->getCpuInfo(),
'memory_usage' => $this->getMemoryUsage(),
'disk_usage' => $this->getDiskUsage(),
'php_memory_limit' => ini_get('memory_limit'),
'max_execution_time' => ini_get('max_execution_time').__('settings.seconds'),
'upload_max_filesize' => ini_get('upload_max_filesize'),
'cpu_info' => $this->safeSystemProbe('cpu_info', fn () => $this->getCpuInfo(), __('common.unknown')),
'memory_usage' => $this->safeSystemProbe('memory_usage', fn () => $this->getMemoryUsage(), $this->unknownUsage()),
'disk_usage' => $this->safeSystemProbe('disk_usage', fn () => $this->getDiskUsage(), $this->unknownUsage()),
'php_memory_limit' => $this->safeSystemProbe('php_memory_limit', fn () => ini_get('memory_limit'), __('common.unknown')),
'max_execution_time' => $this->safeSystemProbe('max_execution_time', fn () => ini_get('max_execution_time').__('settings.seconds'), __('common.unknown')),
'upload_max_filesize' => $this->safeSystemProbe('upload_max_filesize', fn () => ini_get('upload_max_filesize'), __('common.unknown')),
'install_path' => base_path(),
'config_path' => storage_path('app/settings'),
'log_path' => storage_path('logs'),
'upload_path' => storage_path('app/public'),
'php_extensions' => $this->getPhpExtensions(),
'database_config' => $this->getDatabaseConfig(),
'php_extensions' => $this->safeSystemProbe('php_extensions', fn () => $this->getPhpExtensions(), ['required' => [], 'optional' => []]),
'database_config' => $this->safeSystemProbe('database_config', fn () => $this->getDatabaseConfig(), ['has_read_write_split' => false, 'write' => [], 'read' => []]),
'timezone' => config('app.timezone'),
];
}
/**
* 시스템 정보 probe 를 안전하게 실행합니다.
*
* probe 가 예외(ErrorException·Error·disable_functions 로 인한 Error 포함)를
* 던지면 전파하지 않고 폴백값을 반환하고 경고 로그를 남깁니다. 개별 항목 수집
* 실패가 system-info API 전체를 500 으로 만들지 않도록 격리합니다.
*
* @param string $label 실패 로그 식별용 항목명 (예: 'cpu_info')
* @param callable $cb 실행할 probe 콜백
* @param mixed $fallback 실패 시 반환할 폴백 값
* @return mixed probe 결과 또는 폴백
*/
private function safeSystemProbe(string $label, callable $cb, mixed $fallback): mixed
{
try {
return $cb();
} catch (\Throwable $e) {
Log::warning('시스템 정보 수집 실패', [
'item' => $label,
'error' => $e->getMessage(),
]);
return $fallback;
}
}
/**
* 메모리/디스크 사용량 조회 실패 시 사용할 폴백 배열을 반환합니다.
*
* total/used/free/percentage 형식을 memory_usage·disk_usage 와 동일하게 유지합니다.
*
* @return array 사용량 폴백 배열
*/
private function unknownUsage(): array
{
return [
'total' => __('common.unknown'),
'used' => __('common.unknown'),
'free' => __('common.unknown'),
'percentage' => 0,
];
}
/**
* 시스템 캐시를 정리합니다.
*
@@ -949,11 +993,16 @@ class SettingsService
try {
$connection = DB::connection();
$driver = $connection->getDriverName();
$version = $connection->select('SELECT VERSION() as version')[0]->version ?? 'Unknown';
$version = $connection->select('SELECT VERSION() as version')[0]->version ?? __('common.unknown');
return ucfirst($driver).' '.$version;
} catch (\Exception $e) {
return 'Unknown';
} catch (\Throwable $e) {
Log::warning('시스템 정보 수집 실패', [
'item' => 'mysql_version',
'error' => $e->getMessage(),
]);
return __('common.unknown');
}
}
@@ -999,12 +1048,7 @@ class SettingsService
}
if ($total <= 0) {
return [
'total' => __('common.unknown'),
'used' => __('common.unknown'),
'free' => __('common.unknown'),
'percentage' => 0,
];
return $this->unknownUsage();
}
$used = max(0, $total - $free);
@@ -1034,12 +1078,7 @@ class SettingsService
$free = is_numeric($freeRaw) ? (int) $freeRaw : 0;
if ($total <= 0) {
return [
'total' => __('common.unknown'),
'used' => __('common.unknown'),
'free' => __('common.unknown'),
'percentage' => 0,
];
return $this->unknownUsage();
}
$used = max(0, $total - $free);
@@ -1077,7 +1116,7 @@ class SettingsService
*
* @return string CPU 정보 문자열
*/
private function getCpuInfo(): string
protected function getCpuInfo(): string
{
if (PHP_OS_FAMILY === 'Windows') {
$output = @shell_exec('powershell -NoProfile -NonInteractive -Command "(Get-CimInstance Win32_Processor | Select-Object -First 1).Name" 2>&1');
@@ -18,7 +18,7 @@ use Illuminate\Support\Str;
* 레이아웃 편집 중 업로드되는 파일(배경 이미지 등)의 업로드·조회·삭제를 처리한다.
* 파일 저장은 코어 StorageInterface(CoreStorageDriver)를 통해서만 수행하고,
* 저장 위치(disk/path)와 메타데이터를 template_layout_attachments 에 기록한다.
* (Storage::disk() 직접 호출 금지 — CLAUDE.md 스토리지 규칙)
* (Storage::disk() 직접 호출 금지 — 코어 스토리지 규칙)
*/
class TemplateLayoutAttachmentService
{
@@ -114,7 +114,7 @@ class TemplateLayoutAttachmentService
* 첨부 파일을 삭제합니다 — 스토리지 파일 실삭제 후 DB 행 삭제.
*
* DB CASCADE 에 의존하지 않고 스토리지 파일을 명시적으로 삭제한다
* (CLAUDE.md "DB CASCADE 의존 삭제 금지" — 파일 정리 보장).
* (코어 규정: DB CASCADE 의존 삭제 금지 — 파일 정리 보장).
*
* @param TemplateLayoutAttachment $attachment 삭제할 첨부 파일
* @return bool 삭제 성공 여부