feat(core,extensions): 구동 에셋 자체 제공 · 자산 실패 폴백 · 운영자 추가 에셋(custom/)
공개 저장소 이슈 gnuboard/g7 (@bigmsg) 제보에서 출발한 작업이다. 브라우저가 화면을 그리려고 제3자 CDN 에 도달해야 하면, 그 도달 실패는 예외도 로그도 남기지 않고 화면 기능만 조용히 사라진다. 폐쇄망·방화벽·광고차단기에서 재현되는데 자체 서버 로그에는 흔적이 없어 운영자가 원인을 특정할 수 없다. 제보된 것은 편집기 하나였지만 같은 구조가 아이콘·글꼴·코드편집기·압축 라이브러리·설치 마법사·개발 대시보드에 똑같이 있었으므로, 번들 확장과 템플릿 전체를 자체 제공으로 옮겼다. 런타임에 외부로 나가는 것은 주소 검색 서비스 하나만 남았다. 자체 제공만으로는 부족하다 — 자기 서버에서 받는 파일도 실패할 수 있고, 종전에는 그 실패가 무음이었다. CSS 경로에 재시도 계층을 세우고(스크립트 경로와 동형), 서버가 HTML 에 직접 심는 externals 까지 실패를 붙잡아 안내 배너와 [다시 시도]로 표면화했다. 편집기·코드편집기는 확보 실패 시 평문 입력으로 내려앉되 저장 계약을 유지한다. 두 번째 축은 운영자가 CSS 를 덧붙일 자리가 없던 문제다(sir.kr 문의). 확장 디렉토리의 custom/ 을 운영자 소유로 정해, 확장 교체가 그 디렉토리만은 보존하게 했다. 출처에 의존하지 않는 서술자로 해석하므로 나중에 다른 출처가 붙어도 소비자는 바뀌지 않는다. 확장 자산과 같은 메커니즘으로 정적 게시되어 CSS 내부 상대 url 도 해석되고, 파일을 고치면 그 변경을 감지해 재게시까지 예약된다. FTP 접근이 없는 운영자에게는 그 자리도 없는 것과 같으므로 레이아웃 편집기에서 직접 넣고 고칠 수 있게 했다. 모듈·플러그인·템플릿이 한 엔드포인트를 공유한다 — 타입별로 나누면 같은 검증이 세 벌로 갈리고 그중 약한 하나가 우회로가 된다. 여기서 올린 스크립트는 그 레이아웃 한 장이 아니라 사이트 전 화면에서 실행되므로 레이아웃 편집과 분리된 전용 권한으로 연다. 운영자 CSS 가 화면을 조작 불능으로 만들면 그것을 고칠 화면에도 같은 CSS 가 실려 스스로 갇히므로, 서버가 목록을 비우는 탈출구(?custom=off)를 함께 뒀다. 동봉 자산은 재생성 경로에 버전 대조 가드를 붙였다. 선언과 다른 버전을 버전 디렉토리에 써 넣는 조용한 거짓말은 배포된 뒤에는 드러나지 않는다.
This commit is contained in:
1 parent
72f2e94c1a
commit
3945b6f1b3
1042 files changed
+107435
-947
No files matched your search
@@ -0,0 +1,392 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Contracts\Extension\CacheInterface;
|
||||
use App\Exceptions\CustomAssetOperationException;
|
||||
use App\Extension\HookManager;
|
||||
use App\Extension\Traits\ClearsTemplateCaches;
|
||||
use App\Rules\AllowedTemplateFileType;
|
||||
use App\Support\CustomAssets;
|
||||
use Illuminate\Http\UploadedFile;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
/**
|
||||
* 사용자 추가 에셋(`custom/`) 관리 서비스
|
||||
*
|
||||
* 운영자가 자기 CSS·JS·폰트·이미지를 확장의 `custom/` 디렉토리에 넣고 고칠 수 있게 한다.
|
||||
* 종전에는 FTP 나 서버 셸이 유일한 경로였다 — 그 접근이 없는 운영자에게는 기능 자체가
|
||||
* 없는 것과 같았고, 있는 운영자에게도 "고쳤는데 화면에 안 나온다"(정적 게시본 미갱신)가
|
||||
* 남았다.
|
||||
*
|
||||
* 쓰기 뒤에는 반드시 캐시 버전을 올린다. 그 단일 지점이 재게시까지 예약하므로, 편집한
|
||||
* 파일이 게시본에 반영되는 경로가 구조적으로 보장된다.
|
||||
*
|
||||
* @see docs/extension/module-assets.md "사용자 추가 에셋"
|
||||
*/
|
||||
class CustomAssetService
|
||||
{
|
||||
use ClearsTemplateCaches;
|
||||
|
||||
/**
|
||||
* 편집기가 본문을 직접 열고 고칠 수 있는 확장자
|
||||
*
|
||||
* 이 목록 밖(폰트·이미지)은 업로드·삭제만 가능하다 — 바이너리를 텍스트 편집기에
|
||||
* 열면 내용이 손상된 채 저장된다.
|
||||
*/
|
||||
public const EDITABLE_EXTENSIONS = ['css', 'js', 'mjs', 'json'];
|
||||
|
||||
/** 텍스트 편집 대상 파일의 최대 크기 (바이트) */
|
||||
public const MAX_TEXT_BYTES = 524288;
|
||||
|
||||
/** 업로드 파일의 최대 크기 (바이트) */
|
||||
public const MAX_UPLOAD_BYTES = 5242880;
|
||||
|
||||
/**
|
||||
* 확장의 사용자 추가 에셋 목록을 돌려줍니다.
|
||||
*
|
||||
* 서빙 여부와 무관하게 디스크에 있는 파일을 전부 싣는다 — 규약 스캔이 자동으로
|
||||
* 싣지 않는 폰트·이미지도 운영자에게는 관리 대상이고, 목록에서 빠지면 지울 방법이
|
||||
* 없어진다.
|
||||
*
|
||||
* @param string $extensionType `templates` | `modules` | `plugins`
|
||||
* @param string $identifier 확장 식별자
|
||||
* @return array<int, array<string, mixed>> 파일 목록 (상대 경로 오름차순)
|
||||
*/
|
||||
public function list(string $extensionType, string $identifier): array
|
||||
{
|
||||
$directory = CustomAssets::directory($extensionType, $identifier);
|
||||
|
||||
if ($directory === null || ! is_dir($directory)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
// 로드 대상 서술자를 미리 만들어, 목록의 각 파일이 실제로 페이지에 실리는지
|
||||
// (`loaded`) 알려준다. 규약 스캔·선언 파일 어느 쪽이든 결과는 같은 형태다.
|
||||
//
|
||||
// 서술자는 상대 경로 필드를 갖지 않는다 — 소비자가 출처에 의존하지 않도록 URL 과
|
||||
// id 만 노출하는 계약이다. 그래서 id 접두(`custom:{type}:{identifier}:`)를 떼어
|
||||
// 상대 경로를 얻는다. 훅이 더한 항목은 이 접두가 없어 자연히 제외되는데, 그것이
|
||||
// 옳다 — 디스크에 없는 항목을 파일 목록에 표시할 이유가 없다.
|
||||
$idPrefix = 'custom:'.$extensionType.':'.$identifier.':';
|
||||
$loadedPaths = [];
|
||||
|
||||
foreach (CustomAssets::forExtension($extensionType, $identifier) as $asset) {
|
||||
$id = (string) ($asset['id'] ?? '');
|
||||
|
||||
if (($asset['source'] ?? null) !== 'file' || ! str_starts_with($id, $idPrefix)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$loadedPaths[substr($id, strlen($idPrefix))] = true;
|
||||
}
|
||||
|
||||
$files = [];
|
||||
$iterator = new \RecursiveIteratorIterator(
|
||||
new \RecursiveDirectoryIterator($directory, \FilesystemIterator::SKIP_DOTS),
|
||||
\RecursiveIteratorIterator::SELF_FIRST
|
||||
);
|
||||
|
||||
foreach ($iterator as $file) {
|
||||
if (! $file->isFile()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$relative = str_replace('\\', '/', substr($file->getPathname(), strlen($directory) + 1));
|
||||
$extension = strtolower($file->getExtension());
|
||||
|
||||
$files[] = [
|
||||
'path' => $relative,
|
||||
'name' => $file->getFilename(),
|
||||
'extension' => $extension,
|
||||
'size' => $file->getSize(),
|
||||
'modified_at' => date('c', $file->getMTime()),
|
||||
'editable' => in_array($extension, self::EDITABLE_EXTENSIONS, true),
|
||||
'loaded' => isset($loadedPaths[$relative]),
|
||||
];
|
||||
}
|
||||
|
||||
usort($files, fn (array $a, array $b) => strcmp($a['path'], $b['path']));
|
||||
|
||||
return $files;
|
||||
}
|
||||
|
||||
/**
|
||||
* 텍스트 파일 본문을 읽습니다.
|
||||
*
|
||||
* @param string $extensionType 확장 타입
|
||||
* @param string $identifier 확장 식별자
|
||||
* @param string $relative `custom/` 기준 상대 경로
|
||||
* @return array{path: string, content: string, size: int} 본문
|
||||
*
|
||||
* @throws CustomAssetOperationException 파일 부재·비편집 대상·크기 초과 시
|
||||
*/
|
||||
public function read(string $extensionType, string $identifier, string $relative): array
|
||||
{
|
||||
$absolute = $this->resolveExisting($extensionType, $identifier, $relative);
|
||||
|
||||
$extension = strtolower(pathinfo($relative, PATHINFO_EXTENSION));
|
||||
|
||||
if (! in_array($extension, self::EDITABLE_EXTENSIONS, true)) {
|
||||
throw new CustomAssetOperationException('custom_assets.errors.not_editable', ['extension' => $extension]);
|
||||
}
|
||||
|
||||
$size = (int) filesize($absolute);
|
||||
|
||||
if ($size > self::MAX_TEXT_BYTES) {
|
||||
throw new CustomAssetOperationException('custom_assets.errors.too_large_to_edit', [
|
||||
'limit' => (string) self::MAX_TEXT_BYTES,
|
||||
]);
|
||||
}
|
||||
|
||||
$content = file_get_contents($absolute);
|
||||
|
||||
if ($content === false) {
|
||||
throw new CustomAssetOperationException('custom_assets.errors.read_failed', ['path' => $relative]);
|
||||
}
|
||||
|
||||
return ['path' => $relative, 'content' => $content, 'size' => $size];
|
||||
}
|
||||
|
||||
/**
|
||||
* 텍스트 파일 본문을 저장합니다 (없으면 생성).
|
||||
*
|
||||
* @param string $extensionType 확장 타입
|
||||
* @param string $identifier 확장 식별자
|
||||
* @param string $relative `custom/` 기준 상대 경로
|
||||
* @param string $content 본문
|
||||
* @return array<string, mixed> 저장된 파일 정보
|
||||
*
|
||||
* @throws CustomAssetOperationException 경로 무효·쓰기 실패 시
|
||||
*/
|
||||
public function save(string $extensionType, string $identifier, string $relative, string $content): array
|
||||
{
|
||||
$absolute = $this->resolveWritable($extensionType, $identifier, $relative);
|
||||
|
||||
$extension = strtolower(pathinfo($relative, PATHINFO_EXTENSION));
|
||||
|
||||
if (! in_array($extension, self::EDITABLE_EXTENSIONS, true)) {
|
||||
throw new CustomAssetOperationException('custom_assets.errors.not_editable', ['extension' => $extension]);
|
||||
}
|
||||
|
||||
if (strlen($content) > self::MAX_TEXT_BYTES) {
|
||||
throw new CustomAssetOperationException('custom_assets.errors.too_large_to_edit', [
|
||||
'limit' => (string) self::MAX_TEXT_BYTES,
|
||||
]);
|
||||
}
|
||||
|
||||
$this->ensureDirectory(dirname($absolute));
|
||||
|
||||
if (file_put_contents($absolute, $content) === false) {
|
||||
throw new CustomAssetOperationException('custom_assets.errors.write_failed', ['path' => $relative]);
|
||||
}
|
||||
|
||||
$this->invalidate($extensionType, $identifier, 'save', $relative);
|
||||
|
||||
return [
|
||||
'path' => $relative,
|
||||
'size' => strlen($content),
|
||||
'modified_at' => date('c'),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 업로드 파일을 `custom/` 에 저장합니다.
|
||||
*
|
||||
* @param string $extensionType 확장 타입
|
||||
* @param string $identifier 확장 식별자
|
||||
* @param UploadedFile $file 업로드 파일
|
||||
* @param string|null $directory `custom/` 기준 하위 디렉토리 (선택)
|
||||
* @return array<string, mixed> 저장된 파일 정보
|
||||
*
|
||||
* @throws CustomAssetOperationException 경로 무효·확장자 불허·쓰기 실패 시
|
||||
*/
|
||||
public function upload(
|
||||
string $extensionType,
|
||||
string $identifier,
|
||||
UploadedFile $file,
|
||||
?string $directory = null
|
||||
): array {
|
||||
$name = $this->sanitizeFileName($file->getClientOriginalName());
|
||||
$relative = $directory !== null && $directory !== '' ? trim($directory, '/').'/'.$name : $name;
|
||||
|
||||
$absolute = $this->resolveWritable($extensionType, $identifier, $relative);
|
||||
|
||||
$extension = strtolower(pathinfo($name, PATHINFO_EXTENSION));
|
||||
|
||||
if (! in_array($extension, AllowedTemplateFileType::getAllowedExtensions(), true)) {
|
||||
throw new CustomAssetOperationException('custom_assets.errors.extension_not_allowed', [
|
||||
'extension' => $extension,
|
||||
]);
|
||||
}
|
||||
|
||||
if ($file->getSize() > self::MAX_UPLOAD_BYTES) {
|
||||
throw new CustomAssetOperationException('custom_assets.errors.upload_too_large', [
|
||||
'limit' => (string) self::MAX_UPLOAD_BYTES,
|
||||
]);
|
||||
}
|
||||
|
||||
$this->ensureDirectory(dirname($absolute));
|
||||
$file->move(dirname($absolute), basename($absolute));
|
||||
|
||||
$this->invalidate($extensionType, $identifier, 'upload', $relative);
|
||||
|
||||
return [
|
||||
'path' => $relative,
|
||||
'size' => (int) @filesize($absolute),
|
||||
'modified_at' => date('c'),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 파일을 삭제합니다.
|
||||
*
|
||||
* @param string $extensionType 확장 타입
|
||||
* @param string $identifier 확장 식별자
|
||||
* @param string $relative `custom/` 기준 상대 경로
|
||||
* @return void
|
||||
*
|
||||
* @throws CustomAssetOperationException 파일 부재·삭제 실패 시
|
||||
*/
|
||||
public function delete(string $extensionType, string $identifier, string $relative): void
|
||||
{
|
||||
$absolute = $this->resolveExisting($extensionType, $identifier, $relative);
|
||||
|
||||
if (! @unlink($absolute)) {
|
||||
throw new CustomAssetOperationException('custom_assets.errors.delete_failed', ['path' => $relative]);
|
||||
}
|
||||
|
||||
$this->invalidate($extensionType, $identifier, 'delete', $relative);
|
||||
}
|
||||
|
||||
/**
|
||||
* 쓰기 뒤 캐시·게시본을 무효화합니다.
|
||||
*
|
||||
* 확장 캐시 버전을 올리면 그 단일 지점이 정적 재게시까지 예약한다 — 편집한 파일이
|
||||
* 게시본에 반영되는 경로가 여기 한 곳으로 모인다.
|
||||
*
|
||||
* 변경 감지 서명은 **지운다**. 뷰 컴포저가 다음 렌더에서 같은 변경을 다시 발견해
|
||||
* 버전을 한 번 더 올리는 것을 막기 위해서다 (서명이 없으면 그 관측은 기록만 한다).
|
||||
*
|
||||
* @param string $extensionType 확장 타입
|
||||
* @param string $identifier 확장 식별자
|
||||
* @param string $operation 수행한 작업 (로그용)
|
||||
* @param string $relative 대상 상대 경로 (로그용)
|
||||
* @return void
|
||||
*/
|
||||
private function invalidate(string $extensionType, string $identifier, string $operation, string $relative): void
|
||||
{
|
||||
CustomAssets::flushCache();
|
||||
|
||||
try {
|
||||
app(CacheInterface::class)->forget(CustomAssets::SIGNATURE_CACHE_KEY);
|
||||
} catch (\Exception $e) {
|
||||
Log::warning('사용자 추가 에셋 서명 캐시 삭제 실패', ['error' => $e->getMessage()]);
|
||||
}
|
||||
|
||||
$this->incrementExtensionCacheVersion();
|
||||
|
||||
Log::info('사용자 추가 에셋 변경', [
|
||||
'extension_type' => $extensionType,
|
||||
'identifier' => $identifier,
|
||||
'operation' => $operation,
|
||||
'path' => $relative,
|
||||
]);
|
||||
|
||||
// 운영자가 올린 스크립트는 사이트 전 화면에서 실행된다 — 누가 언제 무엇을 바꿨는지
|
||||
// 남지 않으면 사후에 되짚을 수단이 없다. 활동 로그가 그 유일한 기록이다.
|
||||
HookManager::doAction('core.custom_assets.after_change', $extensionType, $identifier, $operation, $relative);
|
||||
}
|
||||
|
||||
/**
|
||||
* 존재하는 파일의 절대 경로를 해석합니다.
|
||||
*
|
||||
* @param string $extensionType 확장 타입
|
||||
* @param string $identifier 확장 식별자
|
||||
* @param string $relative 상대 경로
|
||||
* @return string 절대 경로
|
||||
*
|
||||
* @throws CustomAssetOperationException 경로 무효·파일 부재 시
|
||||
*/
|
||||
private function resolveExisting(string $extensionType, string $identifier, string $relative): string
|
||||
{
|
||||
$absolute = $this->resolveWritable($extensionType, $identifier, $relative);
|
||||
|
||||
if (! is_file($absolute)) {
|
||||
throw new CustomAssetOperationException('custom_assets.errors.not_found', ['path' => $relative]);
|
||||
}
|
||||
|
||||
return $absolute;
|
||||
}
|
||||
|
||||
/**
|
||||
* 쓰기 대상 절대 경로를 해석합니다 (아직 없어도 됩니다).
|
||||
*
|
||||
* 컨테인먼트는 문자열 접두 비교가 아니라 세그먼트 검사로 판정한다. 아직 없는
|
||||
* 파일은 `realpath` 가 실패하므로 실경로 정규화에 기댈 수 없고, 접두 비교만으로는
|
||||
* `custom-evil/` 같은 형제 디렉토리가 통과한다.
|
||||
*
|
||||
* @param string $extensionType 확장 타입
|
||||
* @param string $identifier 확장 식별자
|
||||
* @param string $relative 상대 경로
|
||||
* @return string 절대 경로
|
||||
*
|
||||
* @throws CustomAssetOperationException 경로가 무효한 경우
|
||||
*/
|
||||
private function resolveWritable(string $extensionType, string $identifier, string $relative): string
|
||||
{
|
||||
$directory = CustomAssets::directory($extensionType, $identifier);
|
||||
|
||||
if ($directory === null) {
|
||||
throw new CustomAssetOperationException('custom_assets.errors.invalid_extension_target', [
|
||||
'identifier' => $identifier,
|
||||
]);
|
||||
}
|
||||
|
||||
$normalized = str_replace('\\', '/', trim($relative));
|
||||
|
||||
if ($normalized === '' || str_starts_with($normalized, '/')) {
|
||||
throw new CustomAssetOperationException('custom_assets.errors.invalid_path', ['path' => $relative]);
|
||||
}
|
||||
|
||||
foreach (explode('/', $normalized) as $segment) {
|
||||
if ($segment === '' || $segment === '.' || $segment === '..') {
|
||||
throw new CustomAssetOperationException('custom_assets.errors.invalid_path', ['path' => $relative]);
|
||||
}
|
||||
}
|
||||
|
||||
return $directory.DIRECTORY_SEPARATOR.str_replace('/', DIRECTORY_SEPARATOR, $normalized);
|
||||
}
|
||||
|
||||
/**
|
||||
* 업로드 파일명을 안전한 형태로 정규화합니다.
|
||||
*
|
||||
* @param string $name 원본 파일명
|
||||
* @return string 정규화된 파일명
|
||||
*/
|
||||
private function sanitizeFileName(string $name): string
|
||||
{
|
||||
$base = basename(str_replace('\\', '/', $name));
|
||||
|
||||
return preg_replace('/[^A-Za-z0-9._-]/', '_', $base) ?? '';
|
||||
}
|
||||
|
||||
/**
|
||||
* 디렉토리를 보장합니다.
|
||||
*
|
||||
* @param string $directory 절대 경로
|
||||
* @return void
|
||||
*
|
||||
* @throws CustomAssetOperationException 생성 실패 시
|
||||
*/
|
||||
private function ensureDirectory(string $directory): void
|
||||
{
|
||||
if (is_dir($directory)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (! @mkdir($directory, 0755, true) && ! is_dir($directory)) {
|
||||
throw new CustomAssetOperationException('custom_assets.errors.directory_failed', ['path' => $directory]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Contracts\Repositories\ModuleRepositoryInterface;
|
||||
use App\Contracts\Repositories\PluginRepositoryInterface;
|
||||
use App\Contracts\Repositories\TemplateRepositoryInterface;
|
||||
use App\Exceptions\StaticCachePublishException;
|
||||
use App\Extension\Helpers\FilePermissionHelper;
|
||||
@@ -9,6 +11,7 @@ use App\Extension\Traits\ClearsTemplateCaches;
|
||||
use App\Helpers\ResponseHelper;
|
||||
use App\Models\Template;
|
||||
use App\Rules\AllowedTemplateFileType;
|
||||
use App\Support\CustomAssets;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
@@ -55,6 +58,8 @@ class ExtensionStaticCacheService
|
||||
public function __construct(
|
||||
private TemplateService $templateService,
|
||||
private TemplateRepositoryInterface $templateRepository,
|
||||
private ModuleRepositoryInterface $moduleRepository,
|
||||
private PluginRepositoryInterface $pluginRepository,
|
||||
private ExtensionBundleService $bundleService,
|
||||
private LanguagePackService $languagePackService,
|
||||
) {}
|
||||
@@ -312,6 +317,8 @@ class ExtensionStaticCacheService
|
||||
|
||||
$this->publishBundles($tmp, $version, $files);
|
||||
|
||||
$this->publishExtensionCustomAssets($tmp, $files);
|
||||
|
||||
// 원자적 스왑 — force 재게시 시 기존 디렉토리를 비켜낸 뒤 rename
|
||||
if (File::isDirectory($final)) {
|
||||
File::deleteDirectory($final);
|
||||
@@ -341,9 +348,14 @@ class ExtensionStaticCacheService
|
||||
|
||||
return true;
|
||||
} catch (\Throwable $e) {
|
||||
// 예외 종류와 발생 위치까지 남긴다. 메시지만으로는 파일시스템 오류인지 병합
|
||||
// 오류인지 구분되지 않아, 운영자도 개발자도 재현부터 다시 해야 한다 —
|
||||
// 게시 실패는 사이트를 멈추지 않고 폴백으로 넘어가므로 이 로그가 유일한 흔적이다.
|
||||
Log::warning('부트스트랩 리소스 정적 게시 실패 — API 폴백으로 동작합니다', [
|
||||
'version' => $version,
|
||||
'exception' => $e::class,
|
||||
'error' => $e->getMessage(),
|
||||
'at' => $e->getFile().':'.$e->getLine(),
|
||||
]);
|
||||
File::deleteDirectory($tmp);
|
||||
|
||||
@@ -443,18 +455,43 @@ class ExtensionStaticCacheService
|
||||
$files,
|
||||
$tmp
|
||||
);
|
||||
|
||||
// 5. 운영자 소유 디렉토리(`custom/`) 사본
|
||||
//
|
||||
// 게시하지 않으면 이 자산만 API 경로에 남는데, 그 경로에서는 CSS 내부 상대
|
||||
// `url()` 이 해석되지 않는다 — `?file=` 형태는 기준 URL 이 `/api/templates/assets/`
|
||||
// 라 `url('./font.woff2')` 가 그 디렉토리를 가리키고, 확장자 형태는 정적 최적화
|
||||
// 서버가 먼저 가로챈다(그래서 `extensionless` 모드가 존재한다). 즉 정적 확장자
|
||||
// URL 은 **public 아래 실제 파일일 때만** 200 이 되므로, 문서가 안내하는
|
||||
// "폰트·이미지를 custom/ 에 두고 상대 경로로 참조" 를 성립시키는 방법은 게시뿐이다.
|
||||
//
|
||||
// 갱신 축은 확장 자산과 동일하다 — 운영자가 파일을 고치면 `CustomAssets` 가
|
||||
// 그것을 감지해 `ext.cache_version` 을 올리고, 그 단일 지점이 재게시까지 예약한다.
|
||||
$this->publishDistAssets(
|
||||
base_path("templates/{$identifier}/".CustomAssets::DIRECTORY),
|
||||
$templateDir.DIRECTORY_SEPARATOR.'assets'.DIRECTORY_SEPARATOR.CustomAssets::DIRECTORY,
|
||||
$files,
|
||||
$tmp,
|
||||
excludeCustom: false
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 템플릿 dist 디렉토리를 재귀 복사합니다 (허용 확장자만, 소스맵 제외).
|
||||
*
|
||||
* @param string $sourceDir 원본 dist 절대 경로
|
||||
* @param string $sourceDir 원본 절대 경로 (dist 또는 custom)
|
||||
* @param string $targetDir 게시 대상 절대 경로
|
||||
* @param array<string> $files 기록된 상대 경로 누적 (참조)
|
||||
* @param string $tmp tmp 루트 (상대 경로 계산용)
|
||||
* @param bool $excludeCustom 원본 안의 `custom/` 하위를 건너뛸지 (dist 원본에서만 참)
|
||||
*/
|
||||
private function publishDistAssets(string $sourceDir, string $targetDir, array &$files, string $tmp): void
|
||||
{
|
||||
private function publishDistAssets(
|
||||
string $sourceDir,
|
||||
string $targetDir,
|
||||
array &$files,
|
||||
string $tmp,
|
||||
bool $excludeCustom = true
|
||||
): void {
|
||||
$realSource = realpath($sourceDir);
|
||||
|
||||
if ($realSource === false || ! is_dir($realSource)) {
|
||||
@@ -486,10 +523,33 @@ class ExtensionStaticCacheService
|
||||
}
|
||||
|
||||
$relative = substr($realFile, strlen($realSource) + 1);
|
||||
|
||||
// dist 원본에서는 `custom/` 하위를 건너뛴다 — 운영자 파일은 자기 원본
|
||||
// 루트로 따로 게시되므로, dist 를 통해 한 번 더 실리면 같은 파일이 두 경로에
|
||||
// 놓여 어느 쪽이 유효한지가 갈린다. custom 원본으로 호출될 때는 끄고 들어온다
|
||||
// (그러지 않으면 `custom/custom/…` 이 조용히 누락된다).
|
||||
if ($excludeCustom && $this->isCustomAssetPath($relative)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$this->copyFile($realFile, $targetDir.DIRECTORY_SEPARATOR.$relative, $files, $tmp);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 상대 경로가 운영자 소유 디렉토리(`custom/`) 소속인지 판정합니다.
|
||||
*
|
||||
* @param string $relative 게시 원본 기준 상대 경로
|
||||
* @return bool custom 소속이면 true
|
||||
*/
|
||||
private function isCustomAssetPath(string $relative): bool
|
||||
{
|
||||
$normalized = str_replace(DIRECTORY_SEPARATOR, '/', $relative);
|
||||
|
||||
return $normalized === CustomAssets::DIRECTORY
|
||||
|| str_starts_with($normalized, CustomAssets::DIRECTORY.'/');
|
||||
}
|
||||
|
||||
/**
|
||||
* 확장 병합 번들 4종(modules/plugins × js/css)을 게시합니다.
|
||||
*
|
||||
@@ -519,6 +579,59 @@ class ExtensionStaticCacheService
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 활성 모듈·플러그인의 운영자 소유 디렉토리(`custom/`)를 게시합니다.
|
||||
*
|
||||
* 모듈·플러그인의 빌드 산출물은 **병합 번들**로만 게시되는데, `custom/` 은 그 번들에
|
||||
* 들어가지 않는다(운영자 파일은 번들보다 뒤에 따로 로드되어야 재정의가 성립한다).
|
||||
* 그래서 게시하지 않으면 확장 자산 중 이것만 요청마다 PHP 를 거치고, 무엇보다
|
||||
* CSS 내부 상대 `url()` 이 해석되지 않는다 — `?file=` 형태는 기준 URL 이
|
||||
* `/api/modules/assets/` 라 `url('./font.woff2')` 가 그 디렉토리를 가리키고,
|
||||
* 확장자 형태는 정적 최적화 서버가 먼저 가로챈다. 정적 확장자 URL 은 **public 아래
|
||||
* 실제 파일일 때만** 200 이 되므로 게시가 유일한 방법이다 (템플릿과 같은 사유).
|
||||
*
|
||||
* **활성 확장만** 게시한다. 자산 서빙이 활성 확장에만 응답하므로, 비활성 확장의 파일을
|
||||
* 게시해 봐야 아무도 참조하지 않는 사본이 버전 디렉토리마다 쌓일 뿐이다.
|
||||
*
|
||||
* @param string $tmp tmp 디렉토리 절대 경로
|
||||
* @param array<string> $files 기록된 상대 경로 누적 (참조)
|
||||
*/
|
||||
private function publishExtensionCustomAssets(string $tmp, array &$files): void
|
||||
{
|
||||
// 활성 목록은 **레포지토리**에서 읽는다. 매니저(`getActiveModules()`)는 확장을
|
||||
// 실제로 적재하는 부작용이 있어, 게시 중에 그 부작용을 끌어들이면 게시가 확장
|
||||
// 부팅 상태에 좌우된다. 같은 메서드가 템플릿을 `templateRepository->getActive()`
|
||||
// 로 세는 것과 대칭이다.
|
||||
$sources = [
|
||||
'modules' => $this->moduleRepository->getActiveModuleIdentifiers(),
|
||||
'plugins' => $this->pluginRepository->getActivePluginIdentifiers(),
|
||||
];
|
||||
|
||||
foreach ($sources as $root => $identifiers) {
|
||||
foreach ($identifiers as $identifier) {
|
||||
$identifier = (string) $identifier;
|
||||
|
||||
if (! preg_match(self::IDENTIFIER_PATTERN, $identifier)) {
|
||||
Log::warning('정적 게시 제외 — 식별자 패턴 불일치', [
|
||||
'type' => $root,
|
||||
'identifier' => $identifier,
|
||||
]);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$this->publishDistAssets(
|
||||
base_path("{$root}/{$identifier}/".CustomAssets::DIRECTORY),
|
||||
$tmp.DIRECTORY_SEPARATOR.$root.DIRECTORY_SEPARATOR.$identifier
|
||||
.DIRECTORY_SEPARATOR.'assets'.DIRECTORY_SEPARATOR.CustomAssets::DIRECTORY,
|
||||
$files,
|
||||
$tmp,
|
||||
excludeCustom: false
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 게시 대상 로케일을 열거합니다 — `/api/locales/active` 와 동일 소스
|
||||
* (언어팩이 추가한 로케일 포함).
|
||||
|
||||
@@ -366,13 +366,20 @@ class ModuleService
|
||||
* @param string $moduleName 제거할 모듈명
|
||||
* @param bool $deleteData 모듈 데이터(테이블) 삭제 여부
|
||||
* @param string|null $failureReason 실패 시 사유가 담기는 out 파라미터 (성공 시 null)
|
||||
* @param array<int, array{directory: string, archive: string}>|null $preservedBackups
|
||||
* 삭제 전에 보관한 운영자 소유 디렉토리(`custom/`)의 사본 경로가 담기는 out 파라미터
|
||||
* @return bool 제거 성공 여부
|
||||
*
|
||||
* @throws ValidationException 모듈 제거 실패 시
|
||||
*/
|
||||
public function uninstallModule(string $moduleName, bool $deleteData = false, ?string &$failureReason = null): bool
|
||||
{
|
||||
public function uninstallModule(
|
||||
string $moduleName,
|
||||
bool $deleteData = false,
|
||||
?string &$failureReason = null,
|
||||
?array &$preservedBackups = null,
|
||||
): bool {
|
||||
$failureReason = null;
|
||||
$preservedBackups = [];
|
||||
|
||||
HookManager::doAction('core.modules.before_uninstall', $moduleName, $deleteData);
|
||||
|
||||
@@ -381,7 +388,13 @@ class ModuleService
|
||||
$this->moduleManager->loadModules();
|
||||
$moduleInfo = $this->moduleManager->getModuleInfo($moduleName);
|
||||
|
||||
$result = $this->moduleManager->uninstallModule($moduleName, $deleteData, null, $failureReason);
|
||||
$result = $this->moduleManager->uninstallModule(
|
||||
$moduleName,
|
||||
$deleteData,
|
||||
null,
|
||||
$failureReason,
|
||||
$preservedBackups
|
||||
);
|
||||
|
||||
if ($result) {
|
||||
$module = $this->moduleRepository->findByName($moduleName);
|
||||
|
||||
@@ -243,20 +243,33 @@ class PluginService
|
||||
* @param string $pluginName 플러그인 식별자
|
||||
* @param bool $deleteData 플러그인이 생성한 DB 데이터/스토리지 디렉토리까지 삭제 여부
|
||||
* @param string|null $failureReason 실패 시 사유가 담기는 out 파라미터 (성공 시 null)
|
||||
* @param array<int, array{directory: string, archive: string}>|null $preservedBackups
|
||||
* 삭제 전에 보관한 운영자 소유 디렉토리(`custom/`)의 사본 경로가 담기는 out 파라미터
|
||||
* @return bool 제거 성공 여부
|
||||
*
|
||||
* @throws ValidationException 제거 실패 시
|
||||
*/
|
||||
public function uninstallPlugin(string $pluginName, bool $deleteData = false, ?string &$failureReason = null): bool
|
||||
{
|
||||
public function uninstallPlugin(
|
||||
string $pluginName,
|
||||
bool $deleteData = false,
|
||||
?string &$failureReason = null,
|
||||
?array &$preservedBackups = null,
|
||||
): bool {
|
||||
$failureReason = null;
|
||||
$preservedBackups = [];
|
||||
|
||||
HookManager::doAction('core.plugins.before_uninstall', $pluginName, $deleteData);
|
||||
|
||||
try {
|
||||
$this->pluginManager->loadPlugins();
|
||||
|
||||
$result = $this->pluginManager->uninstallPlugin($pluginName, $deleteData, null, $failureReason);
|
||||
$result = $this->pluginManager->uninstallPlugin(
|
||||
$pluginName,
|
||||
$deleteData,
|
||||
null,
|
||||
$failureReason,
|
||||
$preservedBackups
|
||||
);
|
||||
|
||||
HookManager::doAction('core.plugins.after_uninstall', $pluginName, $deleteData, $result);
|
||||
|
||||
|
||||
@@ -16,6 +16,7 @@ use App\Extension\Helpers\GithubHelper;
|
||||
use App\Extension\Helpers\ZipInstallHelper;
|
||||
use App\Extension\HookManager;
|
||||
use App\Extension\Traits\ResolvesLanguageFragments;
|
||||
use App\Support\CustomAssets;
|
||||
use Illuminate\Http\UploadedFile;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
@@ -432,19 +433,26 @@ class TemplateService
|
||||
*
|
||||
* @param string $identifier 제거할 템플릿 식별자
|
||||
* @param bool $deleteData 템플릿 관련 데이터 삭제 여부
|
||||
* @param array<int, array{directory: string, archive: string}>|null $preservedBackups
|
||||
* 삭제 전에 보관한 운영자 소유 디렉토리(`custom/`)의 사본 경로가 담기는 out 파라미터
|
||||
* @return array|null 제거된 템플릿 정보 또는 null
|
||||
*
|
||||
* @throws ValidationException 제거 실패 시
|
||||
*/
|
||||
public function uninstallTemplate(string $identifier, bool $deleteData = false): ?array
|
||||
{
|
||||
public function uninstallTemplate(
|
||||
string $identifier,
|
||||
bool $deleteData = false,
|
||||
?array &$preservedBackups = null,
|
||||
): ?array {
|
||||
$preservedBackups = [];
|
||||
|
||||
HookManager::doAction('core.templates.before_uninstall', $identifier, $deleteData);
|
||||
|
||||
try {
|
||||
// 제거 전 템플릿 정보 보존
|
||||
$templateInfo = $this->templateManager->getTemplateInfo($identifier);
|
||||
|
||||
$result = $this->templateManager->uninstallTemplate($identifier);
|
||||
$result = $this->templateManager->uninstallTemplate($identifier, null, $preservedBackups);
|
||||
|
||||
if ($result) {
|
||||
HookManager::doAction('core.templates.after_uninstall', $identifier, $templateInfo, $deleteData);
|
||||
@@ -660,7 +668,13 @@ class TemplateService
|
||||
$safePath = $this->sanitizePath($path);
|
||||
|
||||
// 3. 파일 경로 구성
|
||||
$filePath = base_path("templates/{$identifier}/dist/{$safePath}");
|
||||
//
|
||||
// 템플릿 자산은 `dist/` 이하가 기본이지만, 운영자 소유 디렉토리(`custom/`)만은
|
||||
// 그 밖에 있다 — 빌드 산출물이 아니라 사람이 넣은 파일이고, 확장 교체가
|
||||
// 보존하는 대상이라 빌드 디렉토리에 둘 수 없다.
|
||||
$filePath = str_starts_with($safePath, CustomAssets::DIRECTORY.'/')
|
||||
? base_path("templates/{$identifier}/{$safePath}")
|
||||
: base_path("templates/{$identifier}/dist/{$safePath}");
|
||||
|
||||
// 4. 파일 존재 확인
|
||||
if (! file_exists($filePath) || ! is_file($filePath)) {
|
||||
|
||||
Reference in new issue
Block a user