feat(ckeditor5,board,ecommerce,page,core,admin_basic): 미참조 에디터 업로드 이미지 정리 신설 + 업로드 고아 동종 결함 7건 전수 해소

공개 (@Tuwasduliebst 제보) 대응.

- ckeditor5: 미참조 이미지 정리 엔진 신설 — 참조 판정(hash + 파일명 2토큰,
 filter_reference_sources 훅으로 확장 콘텐츠 등록) + 정리 커맨드(기본 꺼짐 옵트인,
 3중 게이트) + 업로드 관리 화면(권한 분리·참조 배지·개별/선택 삭제) + 기설치본
 설정 백필 upgrade step
- board: 임시 첨부 GC(상시) + 소프트삭제 첨부 영구 정리(옵트인) + 설정 UI,
 저장 payload 누락(F4)·빈 temp 디렉토리 잔존(F5) 수정
- ecommerce: 임시 상품 이미지 GC + 카테고리 삭제 시 이미지 파일 미삭제(S4) 수정
- page: 임시 첨부 GC
- 코어: 고아 첨부 정리 커맨드(옵트인, site_logo 보호) + 사이트 로고 교체 시
 구 로고 재편입 차단(S6) + DB 백업 미구현 501 정직화(B3) + 플러그인 관리자
 메뉴 설치·업데이트 자동 동기화(F1·F7)
- 동반: 플러그인 설정 검증 오류 필드명 라벨화(F3), Toggle 노드 type 정정
 수평 전개(marketing 1.0.2 bump·gdpr·ecommerce), ja 언어팩 4종, API 문서,
 hooks.md, 시나리오 매니페스트 8종, Playwright E2E 4종
This commit is contained in:
HeuJung committed 2026-08-17 02:44:54 +09:00
1 parent 1d895a6428
commit cfc2caba1b
170 files changed
+11142 -209

No files matched your search

@@ -0,0 +1,165 @@
<?php
namespace Plugins\Sirsoft\Ckeditor5\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Plugins\Sirsoft\Ckeditor5\Services\ImageCleanupService;
/**
* 미참조 CKEditor5 업로드 이미지 정리 커맨드
*
* 에디터로 올렸지만 어떤 콘텐츠에서도 쓰이지 않는 이미지를 파일·기록 함께 정리합니다.
*
* 자동 정리는 사용자 파일을 지우므로 기본 꺼짐(운영자 옵트인)입니다. 스케줄러 호출
* (`--scheduled`)은 커맨드 안에서 설정을 **false 폴백으로** 재확인합니다 — 스케줄 등록부의
* `enabled_config` 게이트는 설정 조회가 실패하면 true 로 폴백하므로, 그것만으로는
* "설정을 만지지 않은 사이트에서 자동 삭제 0" 을 보장할 수 없습니다.
*
* @example php artisan sirsoft-ckeditor5:prune-unused-images --dry-run
* @example php artisan sirsoft-ckeditor5:prune-unused-images --days=7 --limit=50
*/
class PruneUnusedImagesCommand extends Command
{
/**
* 커맨드 이름 및 시그니처
*
* @var string
*/
protected $signature = 'sirsoft-ckeditor5:prune-unused-images
{--dry-run : 실제 삭제 없이 판정 결과만 확인}
{--limit=200 : 한 번에 스캔할 최대 후보 수}
{--days= : 보존기간(일) 재정의 — 미지정 시 플러그인 설정값}
{--scheduled : 스케줄러 호출 표시 — 자동 정리 토글이 꺼져 있으면 조기 종료}';
/**
* 커맨드 설명
*
* @var string
*/
protected $description = '어떤 콘텐츠에서도 사용되지 않는 에디터 업로드 이미지를 정리합니다.';
/**
* @param ImageCleanupService $cleanupService 이미지 정리 서비스
*/
public function __construct(
protected ImageCleanupService $cleanupService
) {
parent::__construct();
}
/**
* 커맨드 실행
*
* @return int 종료 코드
*/
public function handle(): int
{
if ($this->option('scheduled') && ! $this->isAutoCleanupEnabled()) {
$this->info('미사용 이미지 자동 정리가 꺼져 있어 실행하지 않았습니다. (unusedImageCleanup = false)');
return Command::SUCCESS;
}
$days = $this->resolveRetentionDays();
if ($days < 1) {
$this->info(__('sirsoft-ckeditor5::messages.cleanup.retention_disabled'));
return Command::SUCCESS;
}
$limit = max(1, (int) $this->option('limit'));
$isDryRun = (bool) $this->option('dry-run');
$result = $this->cleanupService->pruneUnused($days, $limit, $isDryRun);
if ($isDryRun) {
$this->renderDryRun($result, $days);
return Command::SUCCESS;
}
$this->info(sprintf(
'보존기간(%d일) 경과 후보 %d건 중 참조됨 %d건, 삭제 %d건, 실패 %d건.',
$days,
$result['scanned'],
$result['referenced'],
$result['deleted'],
$result['failed'],
));
if ($result['failed'] > 0) {
$this->warn(sprintf('%d건은 파일 삭제에 실패해 기록을 보존했습니다. 다음 회차에 재시도합니다.', $result['failed']));
}
Log::info('PruneUnusedImagesCommand: 미참조 에디터 이미지 정리 완료', [
'days' => $days,
'limit' => $limit,
'scanned' => $result['scanned'],
'referenced' => $result['referenced'],
'deleted' => $result['deleted'],
'failed' => $result['failed'],
]);
return Command::SUCCESS;
}
/**
* 자동 정리 토글을 false 폴백으로 조회합니다.
*
* @return bool 자동 정리 활성 여부
*/
private function isAutoCleanupEnabled(): bool
{
return (bool) plugin_setting('sirsoft-ckeditor5', 'unusedImageCleanup', false);
}
/**
* 보존기간을 해석합니다 (옵션 > 플러그인 설정 > 기본 30일).
*
* @return int 보존기간(일)
*/
private function resolveRetentionDays(): int
{
$option = $this->option('days');
if ($option !== null && $option !== '') {
return (int) $option;
}
return (int) plugin_setting('sirsoft-ckeditor5', 'unusedImageRetentionDays', 30);
}
/**
* dry-run 결과를 표로 출력합니다.
*
* @param array{scanned: int, referenced: int, deleted: int, failed: int, items: array<int, array<string, mixed>>} $result 판정 결과
* @param int $days 보존기간(일)
*/
private function renderDryRun(array $result, int $days): void
{
$this->info(sprintf(
'[DRY RUN] 보존기간(%d일) 경과 후보 %d건 중 참조됨 %d건, 삭제 대상 %d건.',
$days,
$result['scanned'],
$result['referenced'],
count($result['items']),
));
if ($result['items'] === []) {
return;
}
$this->table(
['ID', 'HASH', '원본명', '크기(bytes)', '업로드 시각'],
array_map(fn (array $item) => [
$item['id'],
$item['hash'],
$item['original_name'],
$item['file_size'],
$item['created_at'],
], $result['items'])
);
}
}
@@ -0,0 +1,99 @@
<?php
namespace Plugins\Sirsoft\Ckeditor5\Http\Controllers\Admin;
use App\Helpers\ResponseHelper;
use App\Http\Controllers\Api\Base\AdminBaseController;
use Illuminate\Http\JsonResponse;
use Plugins\Sirsoft\Ckeditor5\Http\Requests\BulkDeleteUploadsRequest;
use Plugins\Sirsoft\Ckeditor5\Http\Requests\IndexUploadsRequest;
use Plugins\Sirsoft\Ckeditor5\Http\Resources\ImageUploadResource;
use Plugins\Sirsoft\Ckeditor5\Services\ImageUploadAdminService;
/**
* CKEditor5 업로드 이미지 관리 컨트롤러
*
* GET /api/plugins/sirsoft-ckeditor5/admin/uploads
* DELETE /api/plugins/sirsoft-ckeditor5/admin/uploads/{id}
* POST /api/plugins/sirsoft-ckeditor5/admin/uploads/bulk-delete
*
* 권한은 라우트 미들웨어(`sirsoft-ckeditor5.uploads.read` / `.delete`)가 검증합니다.
*/
class ImageUploadAdminController extends AdminBaseController
{
/**
* @param ImageUploadAdminService $adminService 업로드 관리 서비스
*/
public function __construct(
private readonly ImageUploadAdminService $adminService,
) {
parent::__construct();
}
/**
* 업로드 이미지 목록을 반환합니다.
*
* @param IndexUploadsRequest $request HTTP 요청
* @return JsonResponse
*/
public function index(IndexUploadsRequest $request): JsonResponse
{
$result = $this->adminService->paginate(
$request->filters(),
$request->perPage(),
$request->pageNumber(),
);
return ResponseHelper::success('common.success', [
'data' => ImageUploadResource::collection($result['items']),
'pagination' => $result['pagination'],
'meta' => [
'scan_limited' => $result['scan_limited'],
'scan_window' => ImageUploadAdminService::SCAN_WINDOW,
],
]);
}
/**
* 업로드 이미지 1건을 삭제합니다.
*
* @param int $id 업로드 ID
* @return JsonResponse
*/
public function destroy(int $id): JsonResponse
{
$upload = $this->adminService->find($id);
if ($upload === null) {
return ResponseHelper::notFound('messages.uploads.not_found', domain: 'sirsoft-ckeditor5');
}
if (! $this->adminService->delete($upload)) {
return ResponseHelper::error('messages.uploads.file_delete_failed', 500, domain: 'sirsoft-ckeditor5');
}
return ResponseHelper::success('messages.uploads.deleted', domain: 'sirsoft-ckeditor5');
}
/**
* 업로드 이미지를 일괄 삭제합니다.
*
* @param BulkDeleteUploadsRequest $request HTTP 요청
* @return JsonResponse
*/
public function bulkDestroy(BulkDeleteUploadsRequest $request): JsonResponse
{
$result = $this->adminService->bulkDelete($request->ids());
if ($result['deleted'] === 0 && $result['failed'] > 0) {
return ResponseHelper::error('messages.uploads.file_delete_failed', 500, $result, domain: 'sirsoft-ckeditor5');
}
return ResponseHelper::success(
'messages.uploads.bulk_deleted',
$result,
messageParams: ['deleted' => $result['deleted']],
domain: 'sirsoft-ckeditor5',
);
}
}
@@ -0,0 +1,67 @@
<?php
namespace Plugins\Sirsoft\Ckeditor5\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
use Plugins\Sirsoft\Ckeditor5\Models\Ckeditor5ImageUpload;
/**
* 관리자 업로드 이미지 일괄 삭제 요청 검증
*/
class BulkDeleteUploadsRequest extends FormRequest
{
/** 한 번에 삭제할 수 있는 최대 건수 */
public const MAX_IDS = 100;
/**
* 요청 권한 — 라우트 permission 미들웨어가 담당하므로 true 고정.
*
* @return bool 항상 true
*/
public function authorize(): bool
{
return true;
}
/**
* 검증 규칙을 반환합니다.
*
* @return array<string, array<int, mixed>> 검증 규칙
*/
public function rules(): array
{
return [
'ids' => ['required', 'array', 'min:1', 'max:'.self::MAX_IDS],
'ids.*' => ['integer', Rule::exists(Ckeditor5ImageUpload::class, 'id')],
];
}
/**
* 검증 메시지를 반환합니다.
*
* @return array<string, string> 메시지 배열
*/
public function messages(): array
{
return [
'ids.required' => __('sirsoft-ckeditor5::messages.uploads.ids_required'),
'ids.min' => __('sirsoft-ckeditor5::messages.uploads.ids_required'),
'ids.*.exists' => __('sirsoft-ckeditor5::messages.uploads.ids_invalid'),
'ids.*.integer' => __('sirsoft-ckeditor5::messages.uploads.ids_invalid'),
];
}
/**
* 삭제 대상 ID 목록을 반환합니다.
*
* @return array<int, int> ID 목록
*/
public function ids(): array
{
/** @var array<int, int|string> $ids */
$ids = $this->validated('ids') ?? [];
return array_values(array_unique(array_map('intval', $ids)));
}
}
@@ -0,0 +1,123 @@
<?php
namespace Plugins\Sirsoft\Ckeditor5\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
/**
* 관리자 업로드 이미지 목록 조회 요청 검증
*
* 정렬 허용 어휘(`sort_by`)는 Repository 화이트리스트의 부분집합이어야 합니다 —
* 게이트가 더 넓으면 저장소가 조용히 기본 정렬로 되돌리고, 화면 옵션이 더 넓으면
* 그 옵션을 고를 때마다 목록 전체가 422 가 됩니다.
*/
class IndexUploadsRequest extends FormRequest
{
/** 기본 페이지 크기 */
public const DEFAULT_PER_PAGE = 20;
/** 페이지 크기 상한 */
public const MAX_PER_PAGE = 100;
/**
* 정렬 허용 컬럼 (Repository 화이트리스트와 동일 어휘)
*
* @var list<string>
*/
public const SORTABLE = ['created_at', 'file_size', 'original_name'];
/**
* 참조 상태 필터 허용 어휘
*
* @var list<string>
*/
public const REFERENCED_STATES = ['all', 'referenced', 'unreferenced'];
/**
* 요청 권한 — 라우트 permission 미들웨어가 담당하므로 true 고정.
*
* @return bool 항상 true
*/
public function authorize(): bool
{
return true;
}
/**
* 빈 문자열로 도착한 필터를 검증 전에 제거합니다.
*
* 화면은 값을 비울 때 `?referenced=` 처럼 빈 문자열을 보냅니다 — 그대로 두면
* `Rule::in` 에 걸려 목록 전체가 422 가 됩니다.
*/
protected function prepareForValidation(): void
{
$cleared = [];
foreach (['search', 'referenced', 'date_from', 'date_to', 'sort_by', 'sort_order', 'per_page', 'page'] as $key) {
if ($this->has($key) && $this->input($key) === '') {
$cleared[$key] = null;
}
}
if ($cleared !== []) {
$this->merge($cleared);
}
}
/**
* 검증 규칙을 반환합니다.
*
* @return array<string, array<int, mixed>> 검증 규칙
*/
public function rules(): array
{
return [
'search' => ['nullable', 'string', 'max:255'],
'referenced' => ['nullable', 'string', Rule::in(self::REFERENCED_STATES)],
'date_from' => ['nullable', 'date'],
'date_to' => ['nullable', 'date'],
'sort_by' => ['nullable', 'string', Rule::in(self::SORTABLE)],
'sort_order' => ['nullable', 'string', Rule::in(['asc', 'desc'])],
'page' => ['nullable', 'integer', 'min:1'],
'per_page' => ['nullable', 'integer', 'min:1', 'max:'.self::MAX_PER_PAGE],
];
}
/**
* 목록 필터를 반환합니다.
*
* @return array<string, mixed> 필터 배열
*/
public function filters(): array
{
return [
'search' => $this->validated('search'),
'referenced' => $this->validated('referenced') ?? 'all',
'date_from' => $this->validated('date_from'),
'date_to' => $this->validated('date_to'),
'sort_by' => $this->validated('sort_by'),
'sort_order' => $this->validated('sort_order'),
];
}
/**
* 페이지 크기를 반환합니다.
*
* @return int 페이지 크기
*/
public function perPage(): int
{
return (int) ($this->validated('per_page') ?? self::DEFAULT_PER_PAGE);
}
/**
* 페이지 번호를 반환합니다.
*
* @return int 페이지 번호
*/
public function pageNumber(): int
{
return (int) ($this->validated('page') ?? 1);
}
}
@@ -0,0 +1,37 @@
<?php
namespace Plugins\Sirsoft\Ckeditor5\Http\Resources;
use App\Http\Resources\BaseApiResource;
use Illuminate\Http\Request;
/**
* CKEditor5 업로드 이미지 관리 화면 API 리소스
*
* `referenced` 는 저장 컬럼이 아니라 조회 시 판정해 붙인 응답 전용 값입니다
* (ImageUploadAdminService 참조). 판정하지 못한 행은 안전 방향인 "참조됨" 으로 봅니다.
*/
class ImageUploadResource extends BaseApiResource
{
/**
* 리소스를 배열로 변환합니다.
*
* @param Request $request HTTP 요청
* @return array<string, mixed>
*/
public function toArray(Request $request): array
{
return [
'id' => $this->id,
'hash' => $this->hash,
'original_name' => $this->original_name,
'file_size' => (int) $this->file_size,
'mime_type' => $this->mime_type,
'uploaded_by' => $this->uploaded_by,
'uploader_name' => $this->relationLoaded('uploader') ? $this->uploader?->name : null,
'created_at' => $this->formatDateTimeStringForUser($this->created_at),
'download_url' => $this->download_url,
'referenced' => (bool) ($this->referenced ?? true),
];
}
}
@@ -3,8 +3,12 @@
namespace Plugins\Sirsoft\Ckeditor5\Providers;
use App\Extension\BasePluginServiceProvider;
use Plugins\Sirsoft\Ckeditor5\Console\Commands\PruneUnusedImagesCommand;
use Plugins\Sirsoft\Ckeditor5\Repositories\Contracts\ImageReferenceSourceRepositoryInterface;
use Plugins\Sirsoft\Ckeditor5\Repositories\Contracts\ImageUploadRepositoryInterface;
use Plugins\Sirsoft\Ckeditor5\Repositories\ImageReferenceSourceRepository;
use Plugins\Sirsoft\Ckeditor5\Repositories\ImageUploadRepository;
use Plugins\Sirsoft\Ckeditor5\Services\ImageCleanupService;
use Plugins\Sirsoft\Ckeditor5\Services\ImageServeService;
use Plugins\Sirsoft\Ckeditor5\Services\ImageUploadService;
@@ -20,10 +24,12 @@ class Ckeditor5ServiceProvider extends BasePluginServiceProvider
protected array $repositories = [
ImageUploadRepositoryInterface::class => ImageUploadRepository::class,
ImageReferenceSourceRepositoryInterface::class => ImageReferenceSourceRepository::class,
];
protected array $storageServices = [
ImageServeService::class,
ImageCleanupService::class,
];
/**
@@ -38,4 +44,18 @@ class Ckeditor5ServiceProvider extends BasePluginServiceProvider
protected array $storageCategoryServices = [
ImageUploadService::class => 'images',
];
/**
* 플러그인 부팅 — 콘솔 실행 시 정리 커맨드를 등록합니다.
*/
public function boot(): void
{
parent::boot();
if ($this->app->runningInConsole()) {
$this->commands([
PruneUnusedImagesCommand::class,
]);
}
}
}
@@ -0,0 +1,32 @@
<?php
namespace Plugins\Sirsoft\Ckeditor5\Repositories\Contracts;
/**
* 에디터 이미지 참조 소스 조회 Repository 인터페이스
*
* 참조 소스는 확장이 훅으로 등록하는 "테이블명 + 컬럼명" 이라 전용 모델이 없습니다.
* 그래서 이 Repository 는 특정 엔티티가 아니라 **선언된 소스에 대한 조회**를 소유합니다 —
* Service 는 어느 소스를 볼지와 무엇을 찾을지만 정하고, 실제 데이터 접근은 여기로 모읍니다.
*/
interface ImageReferenceSourceRepositoryInterface
{
/**
* 소스 선언이 실제 스키마에 존재하는지 검증하고, 존재하는 컬럼만 남깁니다.
*
* @param string $table 테이블명 (프리픽스 제외)
* @param array<int, string> $columns 컬럼명 목록
* @return array<int, string> 실재하는 컬럼 목록 (테이블이 없으면 빈 배열)
*/
public function resolveExistingColumns(string $table, array $columns): array;
/**
* 지정 소스의 컬럼 중 하나라도 토큰을 포함하는 행이 있는지 확인합니다.
*
* @param string $table 테이블명 (프리픽스 제외)
* @param array<int, string> $columns 검사할 컬럼 목록
* @param array<int, string> $tokens 판정 토큰 (LIKE 이스케이프는 구현이 담당)
* @return bool 하나라도 등장하면 true
*/
public function containsAnyToken(string $table, array $columns, array $tokens): bool;
}
@@ -2,6 +2,9 @@
namespace Plugins\Sirsoft\Ckeditor5\Repositories\Contracts;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Carbon;
use Plugins\Sirsoft\Ckeditor5\Models\Ckeditor5ImageUpload;
/**
@@ -24,4 +27,68 @@ interface ImageUploadRepositoryInterface
* @return Ckeditor5ImageUpload
*/
public function create(array $data): Ckeditor5ImageUpload;
/**
* 기준 시각보다 오래된 업로드를 오래된 순으로 조회합니다.
*
* 정리 후보 조회 전용이라 판정·삭제에 필요한 컬럼만 읽습니다.
*
* @param Carbon $threshold 기준 시각 (이 시각 이전 업로드가 대상)
* @param int $limit 최대 조회 건수
* @return Collection<int, Ckeditor5ImageUpload> 업로드 목록 (created_at 오름차순)
*/
public function findOlderThan(Carbon $threshold, int $limit): Collection;
/**
* 기준 시각보다 오래된 업로드 건수를 반환합니다.
*
* @param Carbon $threshold 기준 시각
* @return int 건수
*/
public function countOlderThan(Carbon $threshold): int;
/**
* 관리 화면용 업로드 목록을 페이지네이션 조회합니다.
*
* @param array $filters 필터 (search / date_from / date_to / sort_by / sort_order)
* @param int $perPage 페이지 크기
* @return LengthAwarePaginator 페이지네이터
*/
public function paginateForAdmin(array $filters, int $perPage): LengthAwarePaginator;
/**
* 참조 판정 스캔 윈도우를 조회합니다 (최신순 상한).
*
* 참조 여부는 저장 컬럼이 아니라 매 조회 시 판정하므로, 참조 상태 필터를 쓸 때는
* 전수가 아니라 최신 N 건만 훑습니다. 상한을 넘긴 사실은 응답 메타로 알립니다.
*
* @param array $filters 필터 (search / date_from / date_to)
* @param int $limit 스캔 윈도우 상한
* @return Collection<int, Ckeditor5ImageUpload> 업로드 목록 (created_at 내림차순)
*/
public function findScanWindow(array $filters, int $limit): Collection;
/**
* ID 목록으로 업로드를 조회합니다.
*
* @param array<int, int> $ids 업로드 ID 목록
* @return Collection<int, Ckeditor5ImageUpload> 업로드 목록
*/
public function findManyByIds(array $ids): Collection;
/**
* ID 로 업로드 단건을 조회합니다.
*
* @param int $id 업로드 ID
* @return Ckeditor5ImageUpload|null
*/
public function findById(int $id): ?Ckeditor5ImageUpload;
/**
* 업로드 기록을 삭제합니다.
*
* @param Ckeditor5ImageUpload $upload 업로드 기록
* @return bool 삭제 성공 여부
*/
public function delete(Ckeditor5ImageUpload $upload): bool;
}
@@ -0,0 +1,66 @@
<?php
namespace Plugins\Sirsoft\Ckeditor5\Repositories;
use Illuminate\Database\Query\Builder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Plugins\Sirsoft\Ckeditor5\Repositories\Contracts\ImageReferenceSourceRepositoryInterface;
/**
* 에디터 이미지 참조 소스 조회 Repository 구현체
*
* 테이블명은 확장이 훅으로 선언한 값이라 런타임에 정해집니다. raw SQL 대신 쿼리빌더를
* 쓰는 이유는 테이블 프리픽스를 빌더가 붙이고 값 바인딩도 빌더가 처리하기 때문입니다.
*/
class ImageReferenceSourceRepository implements ImageReferenceSourceRepositoryInterface
{
/**
* {@inheritDoc}
*/
public function resolveExistingColumns(string $table, array $columns): array
{
if ($table === '' || $columns === [] || ! Schema::hasTable($table)) {
return [];
}
return array_values(array_filter(
$columns,
fn (string $column) => Schema::hasColumn($table, $column)
));
}
/**
* {@inheritDoc}
*/
public function containsAnyToken(string $table, array $columns, array $tokens): bool
{
if ($columns === [] || $tokens === []) {
return false;
}
return DB::table($table)
->where(function (Builder $query) use ($columns, $tokens) {
foreach ($columns as $column) {
foreach ($tokens as $token) {
$query->orWhere($column, 'like', '%'.$this->escapeLike($token).'%');
}
}
})
->exists();
}
/**
* LIKE 와일드카드를 이스케이프합니다.
*
* 원본명·해시에 `%`/`_` 가 포함되면 임의 문자로 해석돼 무관한 본문이 매칭됩니다
* (참조됨 오판 → 정리되지 않고 영구 잔존).
*
* @param string $value 원본 값
* @return string 이스케이프된 값
*/
private function escapeLike(string $value): string
{
return addcslashes($value, '\\%_');
}
}
@@ -2,6 +2,12 @@
namespace Plugins\Sirsoft\Ckeditor5\Repositories;
use App\Repositories\Concerns\FiltersByDateRange;
use App\Repositories\Concerns\ResolvesSortSpec;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Carbon;
use Plugins\Sirsoft\Ckeditor5\Models\Ckeditor5ImageUpload;
use Plugins\Sirsoft\Ckeditor5\Repositories\Contracts\ImageUploadRepositoryInterface;
@@ -10,6 +16,41 @@ use Plugins\Sirsoft\Ckeditor5\Repositories\Contracts\ImageUploadRepositoryInterf
*/
class ImageUploadRepository implements ImageUploadRepositoryInterface
{
use FiltersByDateRange;
use ResolvesSortSpec;
/**
* 목록·정리 조회에서 읽는 컬럼 목록
*
* 참조 판정(hash·file_path)·삭제(file_path·storage_disk)·화면 표시에 쓰이는 컬럼만
* 읽습니다. 이 테이블에는 본문 성격의 넓은 컬럼이 없으나, 컬럼을 명시해 두면 이후
* 컬럼이 늘어도 목록이 자동으로 넓어지지 않습니다.
*
* @var list<string>
*/
private const LIST_COLUMNS = [
'id',
'hash',
'original_name',
'file_path',
'storage_disk',
'file_size',
'mime_type',
'uploaded_by',
'created_at',
];
/**
* 관리 화면 정렬 허용 컬럼 화이트리스트
*
* @var list<string>
*/
private const SORTABLE_COLUMNS = [
'created_at',
'file_size',
'original_name',
];
public function __construct(
protected Ckeditor5ImageUpload $model
) {}
@@ -29,4 +70,125 @@ class ImageUploadRepository implements ImageUploadRepositoryInterface
{
return $this->model->create($data);
}
/**
* {@inheritDoc}
*/
public function findOlderThan(Carbon $threshold, int $limit): Collection
{
return $this->model->newQuery()
->where('created_at', '<', $threshold)
->orderBy('created_at')
->orderBy('id')
->limit($limit)
->get(self::LIST_COLUMNS);
}
/**
* {@inheritDoc}
*/
public function countOlderThan(Carbon $threshold): int
{
return $this->model->newQuery()
->where('created_at', '<', $threshold)
->count();
}
/**
* {@inheritDoc}
*/
public function paginateForAdmin(array $filters, int $perPage): LengthAwarePaginator
{
$sort = $this->resolveSortSpec(
$filters,
self::SORTABLE_COLUMNS,
defaultColumn: 'created_at',
defaultDirection: 'desc',
)[0];
$query = $this->applyFilters($this->model->newQuery(), $filters)
->with('uploader:id,name')
->orderBy($sort['column'], $sort['direction']);
// 정렬 마지막에 기본키를 덧붙여 전순서를 보장한다 — 동률 구간에서 인접 페이지가
// 같은 행을 중복 노출하거나 다른 행을 누락하는 것을 막는다.
if ($sort['column'] !== 'id') {
$query->orderBy('id', $sort['direction']);
}
return $query->paginate($perPage, self::LIST_COLUMNS);
}
/**
* {@inheritDoc}
*/
public function findScanWindow(array $filters, int $limit): Collection
{
return $this->applyFilters($this->model->newQuery(), $filters)
->with('uploader:id,name')
->orderByDesc('created_at')
->orderByDesc('id')
->limit($limit)
->get(self::LIST_COLUMNS);
}
/**
* {@inheritDoc}
*/
public function findManyByIds(array $ids): Collection
{
if ($ids === []) {
return new Collection;
}
return $this->model->newQuery()
->whereIn('id', $ids)
->get(self::LIST_COLUMNS);
}
/**
* {@inheritDoc}
*/
public function findById(int $id): ?Ckeditor5ImageUpload
{
return $this->model->newQuery()->find($id, self::LIST_COLUMNS);
}
/**
* {@inheritDoc}
*/
public function delete(Ckeditor5ImageUpload $upload): bool
{
return (bool) $upload->delete();
}
/**
* 목록 필터를 쿼리에 적용합니다.
*
* @param Builder<Ckeditor5ImageUpload> $query 대상 쿼리
* @param array $filters 필터 배열
* @return Builder<Ckeditor5ImageUpload> 필터가 적용된 쿼리
*/
private function applyFilters(Builder $query, array $filters): Builder
{
$search = trim((string) ($filters['search'] ?? ''));
if ($search !== '') {
$escaped = addcslashes($search, '\\%_');
$query->where(function (Builder $inner) use ($escaped) {
$inner->where('original_name', 'like', '%'.$escaped.'%')
->orWhere('hash', 'like', '%'.$escaped.'%');
});
}
$this->applyDateRangeFilter(
$query,
'created_at',
$filters['date_from'] ?? null,
$filters['date_to'] ?? null,
);
return $query;
}
}
@@ -0,0 +1,164 @@
<?php
namespace Plugins\Sirsoft\Ckeditor5\Services;
use App\Contracts\Extension\StorageInterface;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Log;
use Plugins\Sirsoft\Ckeditor5\Models\Ckeditor5ImageUpload;
use Plugins\Sirsoft\Ckeditor5\Repositories\Contracts\ImageUploadRepositoryInterface;
/**
* CKEditor5 미참조 업로드 이미지 정리 서비스
*
* 관리 화면의 수동 삭제와 정리 커맨드가 같은 삭제 경로(deleteUpload)를 공유합니다.
*
* 삭제 순서는 "물리 파일 먼저, 레코드 나중" 입니다. 반대로 하면 레코드가 사라진 파일은
* 어떤 경로로도 다시 찾을 수 없어 영구 고아가 됩니다. 파일이 이미 없는 행은 고아 레코드로
* 보고 레코드만 지웁니다 — 그러지 않으면 매 회차 같은 행을 재시도하는 루프가 됩니다.
*/
class ImageCleanupService
{
/**
* @param ImageUploadRepositoryInterface $repository 업로드 리포지토리
* @param ImageReferenceScanService $scanner 참조 판정 서비스
* @param StorageInterface $storage 플러그인 스토리지 드라이버
*/
public function __construct(
protected ImageUploadRepositoryInterface $repository,
protected ImageReferenceScanService $scanner,
protected StorageInterface $storage,
) {}
/**
* 보존기간이 지난 미참조 이미지를 정리합니다.
*
* @param int $days 보존기간(일)
* @param int $limit 한 회차에 스캔할 최대 후보 수
* @param bool $dryRun true 면 판정만 하고 삭제하지 않음
* @return array{scanned: int, referenced: int, deleted: int, failed: int, items: array<int, array<string, mixed>>}
*/
public function pruneUnused(int $days, int $limit, bool $dryRun = false): array
{
$threshold = Carbon::now()->subDays($days);
$candidates = $this->repository->findOlderThan($threshold, $limit);
$result = [
'scanned' => $candidates->count(),
'referenced' => 0,
'deleted' => 0,
'failed' => 0,
'items' => [],
];
foreach ($candidates as $upload) {
if ($this->scanner->isReferenced($upload)) {
$result['referenced']++;
continue;
}
if ($dryRun) {
$result['items'][] = $this->describe($upload, 'would_delete');
continue;
}
if ($this->deleteUpload($upload)) {
$result['deleted']++;
$result['items'][] = $this->describe($upload, 'deleted');
continue;
}
$result['failed']++;
$result['items'][] = $this->describe($upload, 'failed');
}
return $result;
}
/**
* 업로드 이미지 1건의 파일과 레코드를 삭제합니다.
*
* @param Ckeditor5ImageUpload $upload 업로드 기록
* @return bool 레코드까지 삭제되면 true, 파일 삭제 실패로 보류되면 false
*/
public function deleteUpload(Ckeditor5ImageUpload $upload): bool
{
[$category, $relativePath] = $this->splitFilePath((string) ($upload->file_path ?? ''));
if ($category === null || $relativePath === null) {
// 경로를 분해할 수 없는 행은 가리키는 파일이 없다 — 레코드만 정리한다.
Log::warning('CKEditor5 업로드 경로를 분해할 수 없어 레코드만 삭제합니다.', [
'id' => $upload->id,
'file_path' => $upload->file_path,
]);
return $this->repository->delete($upload);
}
$disk = (string) ($upload->storage_disk ?? '');
$storage = $disk !== '' ? $this->storage->withDisk($disk) : $this->storage;
if (! $storage->exists($category, $relativePath)) {
// 파일이 이미 없는 고아 레코드 — 재시도 루프를 만들지 않도록 레코드를 정리한다.
return $this->repository->delete($upload);
}
if (! $storage->delete($category, $relativePath)) {
Log::warning('CKEditor5 업로드 파일 삭제에 실패해 레코드를 보존합니다.', [
'id' => $upload->id,
'disk' => $disk,
'file_path' => $upload->file_path,
]);
return false;
}
return $this->repository->delete($upload);
}
/**
* 파일 경로를 카테고리와 상대 경로로 분해합니다.
*
* `file_path` 는 카테고리 prefix 를 포함합니다(`images/Y/m/d/{uuid}.{ext}`) —
* 모델의 `resolveDirectUrl()` 과 동일한 분해 규칙을 씁니다.
*
* @param string $filePath 저장 파일 경로
* @return array{0: string|null, 1: string|null} [카테고리, 상대 경로]
*/
private function splitFilePath(string $filePath): array
{
if ($filePath === '' || ! str_contains($filePath, '/')) {
return [null, null];
}
[$category, $relativePath] = explode('/', $filePath, 2);
if ($category === '' || $relativePath === '') {
return [null, null];
}
return [$category, $relativePath];
}
/**
* 커맨드 출력·로그용 항목 요약을 만듭니다.
*
* @param Ckeditor5ImageUpload $upload 업로드 기록
* @param string $status 처리 상태 (would_delete|deleted|failed)
* @return array<string, mixed> 요약 배열
*/
private function describe(Ckeditor5ImageUpload $upload, string $status): array
{
return [
'id' => (int) $upload->id,
'hash' => (string) $upload->hash,
'original_name' => (string) $upload->original_name,
'file_size' => (int) $upload->file_size,
'created_at' => $upload->created_at?->toDateTimeString(),
'status' => $status,
];
}
}
@@ -0,0 +1,217 @@
<?php
namespace Plugins\Sirsoft\Ckeditor5\Services;
use App\Extension\HookManager;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;
use Plugins\Sirsoft\Ckeditor5\Models\Ckeditor5ImageUpload;
use Plugins\Sirsoft\Ckeditor5\Repositories\Contracts\ImageReferenceSourceRepositoryInterface;
/**
* CKEditor5 업로드 이미지의 참조 여부 판정 서비스
*
* 에디터로 올린 이미지가 어떤 콘텐츠에서도 더 이상 쓰이지 않는지를 판정합니다.
*
* 판정 토큰이 둘인 이유: 본문에 박히는 URL 이 두 형태이기 때문입니다.
* - API 폴백형 `/api/plugins/sirsoft-ckeditor5/images/{12자hex}` → `hash` 가 들어간다
* - 디스크 직접 URL(`url` 설정 디스크/CDN) → 저장 파일명(uuid.ext)이 들어간다
* 한쪽만 검사하면 다른 형태로 저장된 이미지를 "미참조" 로 오판해 삭제하게 됩니다.
* `core.storage.filter_url` 훅으로 URL 이 변형될 수 있으므로 두 토큰을 OR 로 모두 검사합니다.
*
* 로그 사본 테이블(`notification_logs.body`, `mail_send_logs.body`,
* `boards_report_logs.snapshot`)과 미리보기(`template_layout_previews`)는 참조 소스에서
* 제외합니다. 이들은 자체 보존기간으로 삭제되는 사본이라 소스로 삼으면 "로그가 지워지는
* 순간 이미지가 고아가 되는" 역전이 생깁니다.
*/
class ImageReferenceScanService
{
/**
* 참조 소스 확장 훅 이름
*/
public const FILTER_REFERENCE_SOURCES = 'sirsoft-ckeditor5.image.filter_reference_sources';
/**
* 코어가 소유한 참조 소스 (테이블명은 프리픽스 제외 원시 이름)
*
* 모듈 콘텐츠(게시글·페이지·상품 설명 등)는 각 모듈이 훅으로 등록합니다.
*
* @var list<array{table: string, columns: list<string>}>
*/
private const CORE_SOURCES = [
['table' => 'notification_templates', 'columns' => ['body']],
['table' => 'mail_templates', 'columns' => ['body']],
['table' => 'identity_message_templates', 'columns' => ['body']],
['table' => 'template_layouts', 'columns' => ['content']],
['table' => 'template_layout_extensions', 'columns' => ['content']],
['table' => 'template_layout_versions', 'columns' => ['content']],
];
/**
* 요청 수명 memoize 된 검증 완료 소스 목록
*
* @var list<array{table: string, columns: list<string>}>|null
*/
private ?array $resolvedSources = null;
/**
* @param ImageReferenceSourceRepositoryInterface $sourceRepository 참조 소스 조회 리포지토리
*/
public function __construct(
protected ImageReferenceSourceRepositoryInterface $sourceRepository
) {}
/**
* 참조 스캔 대상 소스 목록을 반환합니다.
*
* 확장이 훅으로 추가한 선언은 테이블·컬럼 실재 여부를 검증하고, 불량 선언은
* 경고만 남기고 건너뜁니다 — 한 확장의 잘못된 선언이 판정 전체를 멈추지 않게 합니다.
*
* @return list<array{table: string, columns: list<string>}> 검증된 소스 목록
*/
public function getReferenceSources(): array
{
if ($this->resolvedSources !== null) {
return $this->resolvedSources;
}
$declared = HookManager::applyFilters(self::FILTER_REFERENCE_SOURCES, self::CORE_SOURCES);
if (! is_array($declared)) {
Log::warning('CKEditor5 참조 소스 훅이 배열이 아닌 값을 반환해 코어 기본값을 사용합니다.');
$declared = self::CORE_SOURCES;
}
return $this->resolvedSources = $this->validateSources($declared);
}
/**
* 업로드 이미지가 어떤 콘텐츠에서든 참조되는지 판정합니다.
*
* @param Ckeditor5ImageUpload $upload 업로드 기록
* @return bool 참조되면 true
*/
public function isReferenced(Ckeditor5ImageUpload $upload): bool
{
$tokens = $this->buildTokens($upload);
if ($tokens === []) {
// 판정 토큰을 만들 수 없는 행은 안전 방향(참조됨)으로 본다.
return true;
}
foreach ($this->getReferenceSources() as $source) {
if ($this->sourceContains($source, $tokens)) {
return true;
}
}
return false;
}
/**
* 업로드 목록의 참조 여부를 일괄 판정합니다.
*
* @param Collection<int, Ckeditor5ImageUpload>|iterable<Ckeditor5ImageUpload> $uploads 업로드 목록
* @return array<int, bool> [업로드 ID => 참조 여부]
*/
public function mapReferenced(iterable $uploads): array
{
$map = [];
foreach ($uploads as $upload) {
$map[(int) $upload->id] = $this->isReferenced($upload);
}
return $map;
}
/**
* 판정 토큰(해시 + 저장 파일명)을 만듭니다.
*
* @param Ckeditor5ImageUpload $upload 업로드 기록
* @return list<string> 토큰 목록
*/
private function buildTokens(Ckeditor5ImageUpload $upload): array
{
$tokens = [];
$hash = trim((string) ($upload->hash ?? ''));
if ($hash !== '') {
$tokens[] = $hash;
}
$filePath = trim((string) ($upload->file_path ?? ''));
if ($filePath !== '') {
$basename = basename($filePath);
if ($basename !== '' && ! in_array($basename, $tokens, true)) {
$tokens[] = $basename;
}
}
return $tokens;
}
/**
* 한 소스에 토큰이 하나라도 등장하는지 확인합니다.
*
* @param array{table: string, columns: list<string>} $source 참조 소스
* @param list<string> $tokens 판정 토큰
* @return bool 등장하면 true
*/
private function sourceContains(array $source, array $tokens): bool
{
return $this->sourceRepository->containsAnyToken($source['table'], $source['columns'], $tokens);
}
/**
* 훅으로 수집한 소스 선언을 검증합니다.
*
* @param array $declared 선언 목록
* @return list<array{table: string, columns: list<string>}> 검증 통과 소스
*/
private function validateSources(array $declared): array
{
$valid = [];
foreach ($declared as $source) {
if (! is_array($source) || ! isset($source['table'], $source['columns'])) {
Log::warning('CKEditor5 참조 소스 선언 형식이 올바르지 않아 건너뜁니다.', [
'source' => $source,
]);
continue;
}
$table = (string) $source['table'];
$columns = is_array($source['columns']) ? array_values(array_map('strval', $source['columns'])) : [];
if ($table === '' || $columns === []) {
Log::warning('CKEditor5 참조 소스 선언에 테이블 또는 컬럼이 비어 있어 건너뜁니다.', [
'table' => $table,
]);
continue;
}
$existingColumns = $this->sourceRepository->resolveExistingColumns($table, $columns);
if ($existingColumns === []) {
// 테이블 자체가 없거나(확장 미설치) 선언한 컬럼이 하나도 없는 경우다.
// 한 확장의 잘못된 선언이 판정 전체를 멈추지 않도록 경고만 남기고 건너뛴다.
Log::warning('CKEditor5 참조 소스에 존재하는 테이블/컬럼이 없어 건너뜁니다.', [
'table' => $table,
'columns' => $columns,
]);
continue;
}
$valid[] = ['table' => $table, 'columns' => $existingColumns];
}
return $valid;
}
}
@@ -0,0 +1,171 @@
<?php
namespace Plugins\Sirsoft\Ckeditor5\Services;
use Illuminate\Support\Collection;
use Plugins\Sirsoft\Ckeditor5\Models\Ckeditor5ImageUpload;
use Plugins\Sirsoft\Ckeditor5\Repositories\Contracts\ImageUploadRepositoryInterface;
/**
* CKEditor5 업로드 이미지 관리 화면 서비스
*
* 참조 여부는 컬럼에 저장하지 않고 조회할 때마다 판정합니다. 참조 관계는 콘텐츠가
* 편집될 때마다 바뀌므로 스냅샷을 저장하면 "저장 당시엔 미참조였던" 이미지를 이후에
* 오판 삭제할 수 있기 때문입니다. 대신 판정 비용에 상한을 둡니다.
*
* - 기본 목록: 현재 페이지(≤100행)만 판정 — 페이지 크기가 곧 비용 상한
* - 참조 상태 필터: 최신순 스캔 윈도우(SCAN_WINDOW) 안에서만 판정하고, 상한에 걸린
* 사실을 응답 메타(`scan_limited`)로 알려 화면이 "최근 N건 기준" 임을 표시하게 한다
*/
class ImageUploadAdminService
{
/**
* 참조 상태 필터를 적용할 때 훑는 최신 업로드 건수 상한
*/
public const SCAN_WINDOW = 500;
/**
* @param ImageUploadRepositoryInterface $repository 업로드 리포지토리
* @param ImageReferenceScanService $scanner 참조 판정 서비스
* @param ImageCleanupService $cleanupService 삭제 서비스 (커맨드와 동일 경로 공유)
*/
public function __construct(
protected ImageUploadRepositoryInterface $repository,
protected ImageReferenceScanService $scanner,
protected ImageCleanupService $cleanupService,
) {}
/**
* 관리 화면 목록을 조회합니다.
*
* @param array $filters 필터 (search / referenced / date_from / date_to / sort_by / sort_order)
* @param int $perPage 페이지 크기
* @param int $page 페이지 번호
* @return array{items: Collection<int, Ckeditor5ImageUpload>, pagination: array<string, mixed>, scan_limited: bool}
*/
public function paginate(array $filters, int $perPage, int $page = 1): array
{
$referencedFilter = (string) ($filters['referenced'] ?? 'all');
if ($referencedFilter === 'referenced' || $referencedFilter === 'unreferenced') {
return $this->paginateByReferenceState($filters, $perPage, $page, $referencedFilter === 'referenced');
}
$paginator = $this->repository->paginateForAdmin($filters, $perPage);
/** @var Collection<int, Ckeditor5ImageUpload> $items */
$items = collect($paginator->items());
$this->attachReferenceState($items);
return [
'items' => $items,
'pagination' => [
'current_page' => $paginator->currentPage(),
'last_page' => $paginator->lastPage(),
'per_page' => $paginator->perPage(),
'total' => $paginator->total(),
'from' => $paginator->firstItem(),
'to' => $paginator->lastItem(),
],
'scan_limited' => false,
];
}
/**
* 업로드 이미지 1건을 삭제합니다.
*
* @param Ckeditor5ImageUpload $upload 업로드 기록
* @return bool 삭제 성공 여부 (파일 삭제 실패 시 false)
*/
public function delete(Ckeditor5ImageUpload $upload): bool
{
return $this->cleanupService->deleteUpload($upload);
}
/**
* 업로드 이미지를 일괄 삭제합니다.
*
* @param array<int, int> $ids 업로드 ID 목록
* @return array{deleted: int, failed: int} 처리 결과
*/
public function bulkDelete(array $ids): array
{
$uploads = $this->repository->findManyByIds($ids);
$deleted = 0;
$failed = 0;
foreach ($uploads as $upload) {
$this->cleanupService->deleteUpload($upload) ? $deleted++ : $failed++;
}
return ['deleted' => $deleted, 'failed' => $failed];
}
/**
* ID 로 업로드를 조회합니다.
*
* @param int $id 업로드 ID
* @return Ckeditor5ImageUpload|null
*/
public function find(int $id): ?Ckeditor5ImageUpload
{
return $this->repository->findById($id);
}
/**
* 참조 상태 필터가 걸린 목록을 스캔 윈도우 안에서 페이지네이션합니다.
*
* @param array $filters 필터 배열
* @param int $perPage 페이지 크기
* @param int $page 페이지 번호
* @param bool $wantReferenced true 면 참조됨, false 면 미참조만
* @return array{items: Collection<int, Ckeditor5ImageUpload>, pagination: array<string, mixed>, scan_limited: bool}
*/
private function paginateByReferenceState(array $filters, int $perPage, int $page, bool $wantReferenced): array
{
$window = $this->repository->findScanWindow($filters, self::SCAN_WINDOW);
$scanLimited = $window->count() >= self::SCAN_WINDOW;
$this->attachReferenceState($window);
$matched = $window
->filter(fn (Ckeditor5ImageUpload $upload) => (bool) $upload->referenced === $wantReferenced)
->values();
$total = $matched->count();
$lastPage = max(1, (int) ceil($total / max(1, $perPage)));
$currentPage = max(1, min($page, $lastPage));
$items = $matched->slice(($currentPage - 1) * $perPage, $perPage)->values();
return [
'items' => $items,
'pagination' => [
'current_page' => $currentPage,
'last_page' => $lastPage,
'per_page' => $perPage,
'total' => $total,
'from' => $items->isEmpty() ? null : ($currentPage - 1) * $perPage + 1,
'to' => $items->isEmpty() ? null : ($currentPage - 1) * $perPage + $items->count(),
],
'scan_limited' => $scanLimited,
];
}
/**
* 업로드 목록에 참조 여부를 임시 속성으로 부착합니다.
*
* 저장 컬럼이 아니라 응답 전용 값이라 모델에 setAttribute 로만 실어 보냅니다
* (저장 호출 없음).
*
* @param Collection<int, Ckeditor5ImageUpload> $uploads 업로드 목록
*/
private function attachReferenceState(Collection $uploads): void
{
$map = $this->scanner->mapReferenced($uploads);
foreach ($uploads as $upload) {
$upload->setAttribute('referenced', $map[(int) $upload->id] ?? true);
}
}
}
@@ -1,6 +1,7 @@
<?php
use Illuminate\Support\Facades\Route;
use Plugins\Sirsoft\Ckeditor5\Http\Controllers\Admin\ImageUploadAdminController;
use Plugins\Sirsoft\Ckeditor5\Http\Controllers\ImageServeController;
use Plugins\Sirsoft\Ckeditor5\Http\Controllers\ImageUploadController;
@@ -21,3 +22,23 @@ Route::post('upload', [ImageUploadController::class, 'upload'])
Route::get('images/{hash}', [ImageServeController::class, 'serve'])
->where('hash', '[a-f0-9]{12}')
->name('api.sirsoft-ckeditor5.images.serve');
/*
| 업로드 이미지 관리 (관리자)
|
| 조회와 삭제를 별도 권한으로 분리한다 — 삭제는 파일을 실제로 파기하기 때문이다.
*/
Route::prefix('admin')->name('admin.')->middleware('auth:sanctum')->group(function () {
Route::get('uploads', [ImageUploadAdminController::class, 'index'])
->middleware('permission:admin,sirsoft-ckeditor5.uploads.read')
->name('uploads.index');
Route::post('uploads/bulk-delete', [ImageUploadAdminController::class, 'bulkDestroy'])
->middleware('permission:admin,sirsoft-ckeditor5.uploads.delete')
->name('uploads.bulk-delete');
Route::delete('uploads/{id}', [ImageUploadAdminController::class, 'destroy'])
->whereNumber('id')
->middleware('permission:admin,sirsoft-ckeditor5.uploads.delete')
->name('uploads.destroy');
});