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

@@ -269,8 +269,6 @@ class BoardController extends AdminBaseController
$data['description'] = [$fallbackLocale => ''];
$data['categories'] = [];
$data['notify_author_channels'] = $basicDefaults['notify_author_channels'] ?? [];
$data['notify_admin_on_post_channels'] = $basicDefaults['notify_admin_on_post_channels'] ?? [];
$spamSecurity = g7_module_settings('sirsoft-board', 'spam_security', []);
$data['blocked_keywords'] = collect($spamSecurity['blocked_keywords'] ?? [])->join(',');
$data['allowed_extensions'] = collect($basicDefaults['allowed_extensions'] ?? [])->join(',');
@@ -1,176 +0,0 @@
<?php
namespace Modules\Sirsoft\Board\Http\Controllers\Admin;
use App\Helpers\ResponseHelper;
use App\Http\Controllers\Api\Base\AdminBaseController;
use App\Http\Requests\MailTemplate\MailTemplateIndexRequest;
use App\Http\Requests\MailTemplate\MailTemplatePreviewRequest;
use App\Http\Requests\MailTemplate\UpdateMailTemplateRequest;
use App\Http\Resources\MailTemplateCollection;
use App\Http\Resources\MailTemplateResource;
use Modules\Sirsoft\Board\Models\BoardMailTemplate;
use Modules\Sirsoft\Board\Services\BoardMailTemplateService;
use Illuminate\Http\JsonResponse;
/**
* 게시판 메일 템플릿 관리 컨트롤러
*/
class BoardMailTemplateController extends AdminBaseController
{
/**
* BoardMailTemplateController 생성자.
*
* @param BoardMailTemplateService $service 메일 템플릿 서비스
*/
public function __construct(
private BoardMailTemplateService $service
) {
parent::__construct();
}
/**
* 메일 템플릿 목록을 페이지네이션하여 조회합니다.
*
* @param MailTemplateIndexRequest $request 검증된 목록 조회 요청
* @return JsonResponse 페이지네이션된 템플릿 목록
*/
public function index(MailTemplateIndexRequest $request): JsonResponse
{
try {
$filters = array_filter($request->validated(), fn ($value) => $value !== null);
$perPage = (int) ($request->validated('per_page') ?? 20);
$templates = $this->service->getTemplates($filters, $perPage);
$collection = new MailTemplateCollection($templates);
return ResponseHelper::moduleSuccess(
'sirsoft-board',
'messages.mail_template_fetch_success',
$collection->toArray($request)
);
} catch (\Exception $e) {
return ResponseHelper::moduleError(
'sirsoft-board',
'messages.mail_template_fetch_failed',
500
);
}
}
/**
* 메일 템플릿을 수정합니다.
*
* @param UpdateMailTemplateRequest $request 수정 요청
* @param BoardMailTemplate $boardMailTemplate 수정 대상
* @return JsonResponse 수정 결과
*/
public function update(UpdateMailTemplateRequest $request, BoardMailTemplate $boardMailTemplate): JsonResponse
{
try {
$userId = $request->user()?->id;
$template = $this->service->updateTemplate(
$boardMailTemplate,
$request->validated(),
$userId
);
return ResponseHelper::moduleSuccess(
'sirsoft-board',
'messages.mail_template_save_success',
new MailTemplateResource($template)
);
} catch (\Exception $e) {
return ResponseHelper::moduleError(
'sirsoft-board',
'messages.mail_template_save_error',
500
);
}
}
/**
* 메일 템플릿의 활성 상태를 토글합니다.
*
* @param BoardMailTemplate $boardMailTemplate 토글 대상
* @return JsonResponse 토글 결과
*/
public function toggleActive(BoardMailTemplate $boardMailTemplate): JsonResponse
{
try {
$template = $this->service->toggleActive($boardMailTemplate);
return ResponseHelper::moduleSuccess(
'sirsoft-board',
'messages.mail_template_toggle_success',
new MailTemplateResource($template)
);
} catch (\Exception $e) {
return ResponseHelper::moduleError(
'sirsoft-board',
'messages.mail_template_toggle_failed',
500
);
}
}
/**
* 메일 템플릿 미리보기를 반환합니다.
*
* @param MailTemplatePreviewRequest $request 검증된 미리보기 요청
* @return JsonResponse 미리보기 결과
*/
public function preview(MailTemplatePreviewRequest $request): JsonResponse
{
try {
$result = $this->service->getPreview($request->validated());
return ResponseHelper::moduleSuccess(
'sirsoft-board',
'messages.mail_template_preview_success',
$result
);
} catch (\Exception $e) {
return ResponseHelper::moduleError(
'sirsoft-board',
'messages.mail_template_preview_failed',
500
);
}
}
/**
* 메일 템플릿을 시더 기본값으로 복원합니다.
*
* @param BoardMailTemplate $boardMailTemplate 복원 대상
* @return JsonResponse 복원 결과
*/
public function reset(BoardMailTemplate $boardMailTemplate): JsonResponse
{
try {
$defaultData = $this->service->getDefaultTemplateData($boardMailTemplate->type);
if (! $defaultData) {
return ResponseHelper::moduleError(
'sirsoft-board',
'messages.mail_template_reset_no_default',
404
);
}
$template = $this->service->resetToDefault($boardMailTemplate, $defaultData);
return ResponseHelper::moduleSuccess(
'sirsoft-board',
'messages.mail_template_reset_success',
new MailTemplateResource($template)
);
} catch (\Exception $e) {
return ResponseHelper::moduleError(
'sirsoft-board',
'messages.mail_template_reset_failed',
500
);
}
}
}
@@ -3,13 +3,11 @@
namespace Modules\Sirsoft\Board\Http\Controllers\Admin;
use App\Helpers\PermissionHelper;
use App\Extension\HookManager;
use App\Helpers\ResponseHelper;
use App\Http\Controllers\Api\Base\AdminBaseController;
use Exception;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Modules\Sirsoft\Board\Http\Requests\Admin\BulkApplySettingsRequest;
use Modules\Sirsoft\Board\Http\Requests\Admin\StoreBoardSettingsRequest;
use Modules\Sirsoft\Board\Services\BoardService;
@@ -172,29 +170,6 @@ class BoardSettingsController extends AdminBaseController
}
}
/**
* 사용 가능한 알림 채널 목록을 반환합니다.
*
* 기본 채널(mail, database)을 제공하며, 플러그인이
* 'sirsoft-board.notification.available_channels' Filter 훅으로 채널을 추가할 수 있습니다.
* 추후 코어에 공통 API가 생기면 이 메서드만 교체하면 됩니다.
*
* @return JsonResponse 채널 목록 JSON 응답
*/
public function notificationChannels(): JsonResponse
{
$defaultChannels = [
['value' => 'mail', 'label' => __('sirsoft-board::admin.settings.notification_channels.channel_mail')],
];
$channels = HookManager::applyFilters(
'sirsoft-board.notification.available_channels',
$defaultChannels
);
return ResponseHelper::success('messages.fetch_success', $channels);
}
/**
* 설정 캐시를 초기화합니다.
*
@@ -208,8 +183,8 @@ class BoardSettingsController extends AdminBaseController
// ModuleSettings 캐시 초기화
$this->settingsService->clearCache();
// 게시판 캐시 초기화 (boards:list)
Cache::forget('boards:list');
// 게시판 캐시 전체 초기화
$this->boardService->clearAllBoardCaches();
return ResponseHelper::moduleSuccess(
'sirsoft-board',
@@ -18,6 +18,7 @@ use Modules\Sirsoft\Board\Http\Resources\PostCollection;
use Modules\Sirsoft\Board\Http\Resources\PostResource;
use Modules\Sirsoft\Board\Services\BoardService;
use Modules\Sirsoft\Board\Services\PostService;
use Modules\Sirsoft\Board\Services\ReportService;
use Modules\Sirsoft\Board\Traits\ChecksBoardPermission;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
@@ -35,10 +36,12 @@ class PostController extends AdminBaseController
*
* @param PostService $postService 게시글 서비스
* @param BoardService $boardService 게시판 서비스
* @param ReportService $reportService 신고 서비스
*/
public function __construct(
private PostService $postService,
private BoardService $boardService
private BoardService $boardService,
private ReportService $reportService
) {
parent::__construct();
}
@@ -69,9 +72,11 @@ class PostController extends AdminBaseController
// 삭제된 게시글 포함 여부 (admin.manage 또는 admin.control 권한)
$canViewDeleted = $this->checkBoardPermission($slug, 'admin.manage');
// 게시글 목록 조회
$posts = $this->postService->getPosts($slug, $listParams['filters'], $listParams['perPage'], withTrashed: $canViewDeleted);
$totalNormalPosts = $this->postService->getTotalNormalPosts($slug, $listParams['filters'], $canViewDeleted);
// 게시글 목록 조회 (simplePaginate — COUNT 쿼리 제거)
$posts = $this->postService->getPosts($slug, $listParams['filters'], $listParams['perPage'], withTrashed: $canViewDeleted, board: $board);
// 일반 게시글 총 건수는 캐시에서 조회 (simplePaginate는 total 미제공)
$totalNormalPosts = $this->postService->getCachedNormalPostCount($slug, $board->id, $listParams['filters'], $canViewDeleted, 'admin');
// PostCollection 구성
$collection = new PostCollection($posts);
@@ -123,6 +128,21 @@ class PostController extends AdminBaseController
// 상세 정보 로드 (조회수 증가, 댓글 로드, 이전/다음 게시글 조회)
$post = $this->postService->loadPostDetail($slug, $id, $canViewDeleted);
// 댓글 신고 여부 일괄 사전 로드 (N+1 방지: 댓글별 개별 쿼리 → 1회 일괄 쿼리)
$user = Auth::user();
if ($user && $post->relationLoaded('comments')) {
$comments = $post->comments;
$board = $post->board;
$commentIds = $comments->pluck('id')->all();
$reportedCommentIds = ! empty($commentIds)
? $this->reportService->getReportedTargetIds($user->id, $board->id, 'comment', $commentIds)
: [];
foreach ($comments as $comment) {
$comment->is_already_reported_preloaded = in_array($comment->id, $reportedCommentIds);
}
}
return $this->successWithResource(
'sirsoft-board::messages.posts.fetch_success',
new PostResource($post)
@@ -3,13 +3,10 @@
namespace Modules\Sirsoft\Board\Http\Controllers\User;
use App\Http\Controllers\Api\Base\PublicBaseController;
use App\Models\User;
use App\Services\CacheService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Modules\Sirsoft\Board\Http\Resources\BoardMenuResource;
use Modules\Sirsoft\Board\Http\Resources\BoardResource;
use Modules\Sirsoft\Board\Models\Board;
use Modules\Sirsoft\Board\Services\BoardService;
/**
@@ -28,7 +25,9 @@ class BoardController extends PublicBaseController
*/
public function __construct(
protected BoardService $boardService
) {}
) {
parent::__construct();
}
/**
* 활성화된 게시판 목록 조회 (경량)
@@ -53,9 +52,9 @@ class BoardController extends PublicBaseController
$data = $boards->map(function ($board) use ($recentPostsLimit) {
$boardData = (new BoardResource($board))->toListArray();
// limit가 0보다 크면 최신글 조회
// limit가 0보다 크면 최신글 조회 (board_id 직접 전달로 slug 재조회 방지)
if ($recentPostsLimit > 0) {
$boardData['recent_posts'] = $this->boardService->getBoardRecentPosts($board->slug, $recentPostsLimit);
$boardData['recent_posts'] = $this->boardService->getBoardRecentPostsById($board->id, $recentPostsLimit);
}
return $boardData;
@@ -100,10 +99,8 @@ class BoardController extends PublicBaseController
*/
public function boardMenu(): JsonResponse
{
// 활성화된 게시판을 오래된 순으로 조회
$boards = $this->boardService->getActiveBoards(orderBy: 'created_at', orderDirection: 'asc');
$boards = $this->boardService->getCachedActiveBoardsForMenu();
// 경량 리소스로 변환하여 반환
return $this->success(
'common.success',
BoardMenuResource::collection($boards)->resolve()
@@ -122,14 +119,7 @@ class BoardController extends PublicBaseController
*/
public function stats(): JsonResponse
{
$stats = CacheService::remember(
'sirsoft-board',
'stats',
fn () => $this->calculateStats(),
config('sirsoft-board.cache.ttl', 60)
);
return $this->success('common.success', $stats);
return $this->success('common.success', $this->boardService->getCachedStats());
}
/**
@@ -145,14 +135,7 @@ class BoardController extends PublicBaseController
{
$limit = min((int) $request->input('limit', 5), 20);
$posts = CacheService::remember(
'sirsoft-board',
"recent_posts_{$limit}",
fn () => $this->boardService->getRecentPosts($limit),
config('sirsoft-board.cache.ttl', 60)
);
return $this->success('common.success', $posts);
return $this->success('common.success', $this->boardService->getCachedRecentPosts($limit));
}
/**
@@ -160,26 +143,22 @@ class BoardController extends PublicBaseController
*
* 조회수가 많은 순으로 게시글 목록을 반환합니다.
* - 기본 20개, 최대 50개까지 조회 가능
* - 기간별 필터링: today, week, month, all (기본: week)
* - 기간별 필터링: today, week, month, year (기본: week)
* - period=all은 하위 호환을 위해 year로 매핑
*
* @param Request $request
* @return JsonResponse
*/
public function popular(Request $request): JsonResponse
{
$period = $request->input('period', 'week'); // today, week, month, all
$period = $request->input('period', 'week');
// all → year 매핑 (하위 호환)
if ($period === 'all') {
$period = 'year';
}
$limit = min((int) $request->input('limit', 20), 50);
$locale = app()->getLocale();
// 캐시 키에 period, locale 포함
$posts = CacheService::remember(
'sirsoft-board',
"popular_posts_{$locale}_{$period}_{$limit}",
fn () => $this->boardService->getPopularPosts($period, $limit),
config('sirsoft-board.cache.ttl', 60)
);
return $this->success('common.success', $posts);
return $this->success('common.success', $this->boardService->getCachedPopularPosts($period, $limit));
}
/**
@@ -194,30 +173,7 @@ class BoardController extends PublicBaseController
public function popularBoards(Request $request): JsonResponse
{
$limit = min((int) $request->input('limit', 4), 20);
$locale = app()->getLocale();
$boards = CacheService::remember(
'sirsoft-board',
"popular_boards_{$locale}_{$limit}",
fn () => $this->boardService->getPopularBoards($limit),
config('sirsoft-board.cache.ttl', 60)
);
return $this->success('common.success', $boards);
}
/**
* 통계 계산 (홈페이지용)
*
* @return array{users: int, boards: int, posts: int, comments: int}
*/
private function calculateStats(): array
{
return [
'users' => User::count(),
'boards' => Board::where('is_active', true)->count(),
'posts' => $this->boardService->getTotalPostsCount(),
'comments' => $this->boardService->getTotalCommentsCount(),
];
return $this->success('common.success', $this->boardService->getCachedPopularBoards($limit));
}
}
@@ -7,7 +7,6 @@ use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use Modules\Sirsoft\Board\Http\Requests\StoreCommentRequest;
@@ -93,7 +92,7 @@ class CommentController extends PublicBaseController
$cooldown = (int) ($spamSecurity['comment_cooldown_seconds'] ?? 0);
if ($cooldown > 0) {
$identifier = Auth::id() ?? $request->ip();
Cache::put("comment_cooldown_{$slug}_{$identifier}", true, $cooldown);
$this->commentService->recordCommentCooldown($slug, $identifier, $cooldown);
}
return $this->successWithResource(
@@ -8,7 +8,6 @@ use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use App\Enums\PermissionType;
@@ -24,6 +23,7 @@ use Modules\Sirsoft\Board\Http\Resources\PostResource;
use Modules\Sirsoft\Board\Services\BoardService;
use Modules\Sirsoft\Board\Services\CommentService;
use Modules\Sirsoft\Board\Services\PostService;
use Modules\Sirsoft\Board\Services\ReportService;
use Modules\Sirsoft\Board\Traits\ChecksBoardPermission;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
@@ -46,11 +46,13 @@ class PostController extends PublicBaseController
* @param PostService $postService 게시글 서비스
* @param BoardService $boardService 게시판 서비스
* @param CommentService $commentService 댓글 서비스
* @param ReportService $reportService 신고 서비스
*/
public function __construct(
private PostService $postService,
private BoardService $boardService,
private CommentService $commentService
private CommentService $commentService,
private ReportService $reportService
) {}
/**
@@ -80,9 +82,12 @@ class PostController extends PublicBaseController
$canViewDeleted = $this->checkBoardPermission($slug, 'manager', PermissionType::User);
$withTrashed = $canViewDeleted && $request->boolean('del');
// 게시글 목록 조회
$posts = $this->postService->getPosts($slug, $listParams['filters'], $listParams['perPage'], withTrashed: $withTrashed, context: 'user');
$totalNormalPosts = $this->postService->getTotalNormalPosts($slug, $listParams['filters'], $withTrashed, context: 'user');
// 게시글 목록 조회 (simplePaginate — COUNT 쿼리 제거)
// board 객체 전달로 Service/Repository의 중복 Board 조회 방지
$posts = $this->postService->getPosts($slug, $listParams['filters'], $listParams['perPage'], withTrashed: $withTrashed, context: 'user', board: $board);
// 일반 게시글 총 건수는 캐시에서 조회 (simplePaginate는 total 미제공)
$totalNormalPosts = $this->postService->getCachedNormalPostCount($slug, $board->id, $listParams['filters'], $withTrashed, 'user');
// PostCollection 구성
$collection = new PostCollection($posts);
@@ -122,7 +127,7 @@ class PostController extends PublicBaseController
throw new BoardNotFoundException($slug);
}
// 게시글 조회
// 게시글 조회 (스코프 접근 검사 포함)
$post = $this->postService->getPost($slug, $id, context: 'user');
// 삭제된 게시글은 manager 권한 필요
@@ -135,8 +140,8 @@ class PostController extends PublicBaseController
// 조회수 증가 (캐시 기반 중복 방지)
$this->postService->incrementViewCountOnce($slug, $id);
// 댓글/첨부파일 카운트 포함하여 게시글 조회
$post = $this->postService->getPostWithCounts($slug, $id);
// 댓글/첨부파일/답글 포함하여 게시글 조회 (boardId 전달로 Board 재조회 방지)
$post = $this->postService->getPostWithCounts($slug, $id, $board->id);
// board 관계 수동 설정
$post->setRelation('board', $board);
@@ -146,20 +151,30 @@ class PostController extends PublicBaseController
// 댓글 로드 (게시판 comment_order 설정 적용, manager 권한 + 토글 ON 시 삭제 댓글 포함)
$withTrashedComments = $canViewDeleted && $request->boolean('del_cmt');
$comments = $this->commentService->getCommentsByPostId($slug, $id, context: 'user', withTrashed: $withTrashedComments);
$comments = $this->commentService->getCommentsByPostId($slug, $id, context: 'user', withTrashed: $withTrashedComments, boardId: $board->id);
// 댓글의 post에 board 관계 수동 설정 (CommentResource의 권한 체크에 필요)
foreach ($comments as $comment) {
$comment->setRelation('post', $post);
// 신고 여부 일괄 조회 (N+1 방지: 댓글별 개별 쿼리 → 1회 일괄 쿼리)
$user = $request->user();
if ($user) {
$commentIds = $comments->pluck('id')->all();
$reportedCommentIds = $this->reportService
->getReportedTargetIds($user->id, $board->id, 'comment', $commentIds);
foreach ($comments as $comment) {
$comment->is_already_reported_preloaded = in_array($comment->id, $reportedCommentIds);
$comment->setRelation('post', $post);
}
} else {
// 비로그인: 신고 불가이므로 모두 false
foreach ($comments as $comment) {
$comment->is_already_reported_preloaded = false;
$comment->setRelation('post', $post);
}
}
// 정렬된 댓글을 post에 설정
$post->setRelation('comments', $comments);
// 이전/다음 게시글 조회 (manager 권한 + del=1 시 삭제된 게시글 포함)
$withTrashedNav = $canViewDeleted && $request->boolean('del');
$post->navigation = $this->postService->getAdjacentPosts($slug, $id, filters: [], withTrashed: $withTrashedNav);
// 비밀글 권한 체크 및 content 필터링은 PostResource에서 처리
return $this->successWithResource(
'sirsoft-board::messages.posts.fetch_success',
@@ -176,6 +191,50 @@ class PostController extends PublicBaseController
}
}
/**
* 게시글의 이전/다음 네비게이션 정보를 조회합니다.
*
* 상세 API에서 분리하여 비동기 로딩 지원.
* 게시판 정렬 설정에 따라 이전/다음글을 반환합니다.
*
* @param Request $request HTTP 요청
* @param string $slug 게시판 슬러그
* @param string|int $id 게시글 ID
* @return JsonResponse 이전/다음 게시글 정보
*/
public function navigation(Request $request, string $slug, string|int $id): JsonResponse
{
$id = (int) $id;
try {
$board = $this->boardService->getBoardBySlug($slug, checkScope: false);
if (! $board || ! $board->is_active) {
throw new BoardNotFoundException($slug);
}
// 공지글은 이전/다음 네비게이션 미제공
$post = $this->postService->getPost($slug, $id, context: 'user');
if ($post->is_notice) {
return $this->success('sirsoft-board::messages.posts.fetch_success', ['prev' => null, 'next' => null]);
}
// manager 권한 + del=1 시 삭제된 게시글 포함
$canViewDeleted = $this->checkBoardPermission($slug, 'manager', PermissionType::User);
$withTrashed = $canViewDeleted && $request->boolean('del');
$navigation = $this->postService->getAdjacentPosts($slug, $id, filters: [
'order_by' => $board->order_by instanceof \BackedEnum ? $board->order_by->value : $board->order_by,
'order_direction' => $board->order_direction instanceof \BackedEnum ? $board->order_direction->value : $board->order_direction,
], withTrashed: $withTrashed, board: $board);
return $this->success('sirsoft-board::messages.posts.fetch_success', $navigation);
} catch (BoardNotFoundException $e) {
throw $e;
} catch (\Exception $e) {
return $this->error('sirsoft-board::messages.posts.fetch_failed', 500, $e->getMessage());
}
}
/**
* 게시글을 생성합니다.
*
@@ -234,7 +293,7 @@ class PostController extends PublicBaseController
$cooldown = (int) ($spamSecurity['post_cooldown_seconds'] ?? 0);
if ($cooldown > 0) {
$identifier = Auth::id() ?? $request->ip();
Cache::put("post_cooldown_{$slug}_{$identifier}", true, $cooldown);
$this->postService->recordPostCooldown($slug, $identifier, $cooldown);
}
// board 관계 수동 설정
@@ -428,18 +487,17 @@ class PostController extends PublicBaseController
return $this->error($verifyResult['error_key'], $verifyResult['error_code']);
}
// 검증 성공 시 임시 토큰 생성 및 캐시 저장 (1시간 유효)
// 검증 성공 시 임시 토큰 생성 및 캐시 저장
$verificationToken = Str::random(32);
$expiresAt = now()->addHours(1);
Cache::put("board_post_verify_{$slug}_{$id}_{$verificationToken}", true, $expiresAt);
$tokenResult = $this->postService->storeDeleteVerifyToken($slug, $id, $verificationToken);
return $this->success(
'sirsoft-board::messages.posts.password_verified',
[
'verified' => true,
'post_id' => $id,
'verification_token' => $verificationToken,
'expires_at' => $expiresAt->toIso8601String(),
'verification_token' => $tokenResult['token'],
'expires_at' => $tokenResult['expires_at'],
]
);
} catch (ModelNotFoundException $e) {
@@ -511,8 +569,9 @@ class PostController extends PublicBaseController
// 첨부파일 관계 로드
$post->load('attachments');
// 폼용 경량 변환 (abilities/IP/신고 등 불필요한 권한 체크 생략)
$postResource = new PostResource($post);
$postData = $postResource->toArray($request);
$postData = $postResource->toFormArray($request);
$metaData['author'] = $postData['author'] ?? null;
$metaData['created_at'] = $postData['created_at'] ?? null;
@@ -533,7 +592,7 @@ class PostController extends PublicBaseController
$parentPost = $this->postService->getPost($slug, $parentId, context: 'user');
$parentPostResource = new PostResource($parentPost);
$metaData['parent_post'] = $parentPostResource->toArray($request);
$metaData['parent_post'] = $parentPostResource->toFormArray($request);
}
return $this->success('sirsoft-board::messages.posts.form_meta_retrieved', $metaData);
@@ -590,8 +649,9 @@ class PostController extends PublicBaseController
}
}
// 폼용 경량 변환 (abilities/IP/신고 등 불필요한 권한 체크 생략)
$postResource = new PostResource($post);
$postData = $postResource->toArray($request);
$postData = $postResource->toFormArray($request);
$formData = [
'id' => $postData['id'] ?? null,
@@ -699,7 +759,7 @@ class PostController extends PublicBaseController
// =========================================================================
/**
* verification_token이 유효한지 확인합니다.
* verification_token이 유효한지 확인하고 소비합니다.
*
* @param string $slug 게시판 슬러그
* @param int $postId 게시글 ID
@@ -708,7 +768,7 @@ class PostController extends PublicBaseController
*/
private function isVerificationTokenValid(string $slug, int $postId, string $token): bool
{
return (bool) Cache::get("board_post_verify_{$slug}_{$postId}_{$token}");
return $this->postService->consumeDeleteVerifyToken($slug, $postId, $token);
}
// =========================================================================
@@ -6,7 +6,6 @@ use App\Http\Controllers\Api\Base\AuthBaseController;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Modules\Sirsoft\Board\Enums\ReportStatus;
use Modules\Sirsoft\Board\Enums\ReportType;
use Modules\Sirsoft\Board\Exceptions\DuplicateReportException;
@@ -112,7 +111,7 @@ class ReportController extends AuthBaseController
$cooldown = (int) ($security['report_cooldown_seconds'] ?? 60);
if ($cooldown > 0) {
$identifier = Auth::id() ?? $request->ip();
Cache::put("report_cooldown_{$slug}_{$identifier}", true, $cooldown);
$this->reportService->recordReportCooldown($slug, $identifier, $cooldown);
}
$this->logUserActivity('board_report.create', [
@@ -42,9 +42,7 @@ class BulkApplySettingsRequest extends FormRequest
'max_file_count',
'allowed_extensions',
'notify_admin_on_post',
'notify_admin_on_post_channels',
'notify_author',
'notify_author_channels',
'new_display_hours',
];
@@ -57,6 +57,21 @@ class StoreBoardSettingsRequest extends FormRequest
'spam_security.view_count_cache_ttl',
];
$booleanFields = [
'basic_defaults.use_comment',
'basic_defaults.use_reply',
'basic_defaults.show_view_count',
'basic_defaults.use_report',
'basic_defaults.use_file_upload',
'basic_defaults.notify_admin_on_post',
'basic_defaults.notify_author',
'report_policy.notify_admin_on_report',
'report_policy.notify_author_on_report_action',
'seo.seo_boards',
'seo.seo_board',
'seo.seo_post_detail',
];
$data = $this->all();
foreach ($integerFields as $field) {
@@ -66,6 +81,13 @@ class StoreBoardSettingsRequest extends FormRequest
}
}
foreach ($booleanFields as $field) {
[$category, $key] = explode('.', $field, 2);
if (isset($data[$category][$key])) {
$data[$category][$key] = filter_var($data[$category][$key], FILTER_VALIDATE_BOOLEAN);
}
}
$this->replace($data);
}
@@ -78,7 +100,16 @@ class StoreBoardSettingsRequest extends FormRequest
{
return [
// 현재 탭 정보 (메타 데이터)
'_tab' => ['sometimes', 'string', 'in:basic_defaults,report_policy,spam_security,general'],
'_tab' => ['sometimes', 'string', 'in:basic_defaults,report_policy,spam_security,general,seo,notifications,notification_definitions'],
// ========================================
// notifications (알림 채널 설정) 카테고리
// ========================================
'notifications' => ['sometimes', 'array'],
'notifications.channels' => ['sometimes', 'array'],
'notifications.channels.*.id' => ['required_with:notifications.channels', 'string', 'max:50'],
'notifications.channels.*.is_active' => ['required_with:notifications.channels', 'boolean'],
'notifications.channels.*.sort_order' => ['nullable', 'integer', 'min:0'],
// ========================================
// basic_defaults (기본 설정) 카테고리
@@ -112,10 +143,6 @@ class StoreBoardSettingsRequest extends FormRequest
'basic_defaults.allowed_extensions.*' => ['string', 'max:20'],
'basic_defaults.notify_admin_on_post' => ['nullable', 'boolean'],
'basic_defaults.notify_author' => ['nullable', 'boolean'],
'basic_defaults.notify_admin_on_post_channels' => ['nullable', 'array'],
'basic_defaults.notify_admin_on_post_channels.*' => ['string', 'in:mail'],
'basic_defaults.notify_author_channels' => ['nullable', 'array'],
'basic_defaults.notify_author_channels.*' => ['string', 'in:mail'],
'basic_defaults.new_display_hours' => ['nullable', 'integer', 'min:1', 'max:720'],
// default_board_permissions는 flat key 구조 (예: {"posts.read": ["admin","user"], "manager": ["admin"]})
// Laravel dot notation으로 하위 키를 개별 검증하면 flat key가 중첩 배열로 파싱되어 데이터 유실됨
@@ -133,11 +160,7 @@ class StoreBoardSettingsRequest extends FormRequest
'report_policy.rejection_limit_days' => ['nullable', 'integer', 'min:1', 'max:365'],
'report_policy.notify_admin_on_report' => ['nullable', 'boolean'],
'report_policy.notify_admin_on_report_scope' => ['nullable', 'string', 'in:per_case,per_report'],
'report_policy.notify_admin_on_report_channels' => ['nullable', 'array'],
'report_policy.notify_admin_on_report_channels.*' => ['string', 'in:mail'],
'report_policy.notify_author_on_report_action' => ['nullable', 'boolean'],
'report_policy.notify_author_on_report_action_channels' => ['nullable', 'array'],
'report_policy.notify_author_on_report_action_channels.*' => ['string', 'in:mail'],
// ========================================
// report_permissions (신고 관리 권한) — 설정값이 아닌 DB 권한 데이터
@@ -163,6 +186,20 @@ class StoreBoardSettingsRequest extends FormRequest
'spam_security.comment_cooldown_seconds' => ['nullable', 'integer', 'min:0', 'max:3600'],
'spam_security.report_cooldown_seconds' => ['nullable', 'integer', 'min:0', 'max:3600'],
'spam_security.view_count_cache_ttl' => ['nullable', 'integer', 'min:60', 'max:604800'],
// ========================================
// seo (SEO 설정) 카테고리
// ========================================
'seo' => ['sometimes', 'array'],
'seo.meta_boards_title' => ['nullable', 'string', 'max:500'],
'seo.meta_boards_description' => ['nullable', 'string', 'max:1000'],
'seo.meta_board_title' => ['nullable', 'string', 'max:500'],
'seo.meta_board_description' => ['nullable', 'string', 'max:1000'],
'seo.meta_post_title' => ['nullable', 'string', 'max:500'],
'seo.meta_post_description' => ['nullable', 'string', 'max:1000'],
'seo.seo_boards' => ['nullable', 'boolean'],
'seo.seo_board' => ['nullable', 'boolean'],
'seo.seo_post_detail' => ['nullable', 'boolean'],
];
}
@@ -201,7 +238,7 @@ class StoreBoardSettingsRequest extends FormRequest
public function validatedSettings(): array
{
$validated = $this->validated();
$validCategories = ['basic_defaults', 'report_policy', 'spam_security', 'display'];
$validCategories = ['basic_defaults', 'report_policy', 'spam_security', 'display', 'seo', 'notifications'];
return array_filter(
$validated,
@@ -51,8 +51,6 @@ class StoreBoardRequest extends FormRequest
'comment_order' => $settings['comment_order'] ?? 'ASC',
'notify_admin_on_post' => $settings['notify_admin_on_post'] ?? true,
'notify_author' => $settings['notify_author'] ?? true,
'notify_author_channels' => $settings['notify_author_channels'] ?? [],
'notify_admin_on_post_channels' => $settings['notify_admin_on_post_channels'] ?? [],
'permissions' => [], // 빈 배열 → Service에서 Manager/Step 주입
];
@@ -193,10 +191,6 @@ class StoreBoardRequest extends FormRequest
// 알림 설정
'notify_admin_on_post' => ['required', 'boolean'],
'notify_author' => ['required', 'boolean'],
'notify_author_channels' => ['nullable', 'array'],
'notify_author_channels.*' => ['string', 'max:50'],
'notify_admin_on_post_channels' => ['nullable', 'array'],
'notify_admin_on_post_channels.*' => ['string', 'max:50'],
// 보안 설정 (배열도 허용)
'blocked_keywords' => ['nullable', 'array'],
@@ -174,10 +174,6 @@ class UpdateBoardRequest extends FormRequest
// 알림 설정
'notify_admin_on_post' => ['sometimes', 'required', 'boolean'],
'notify_author' => ['sometimes', 'required', 'boolean'],
'notify_author_channels' => ['sometimes', 'nullable', 'array'],
'notify_author_channels.*' => ['string', 'max:50'],
'notify_admin_on_post_channels' => ['sometimes', 'nullable', 'array'],
'notify_admin_on_post_channels.*' => ['string', 'max:50'],
// 보안 설정 (배열도 허용)
'blocked_keywords' => ['sometimes', 'nullable', 'array'],
@@ -3,7 +3,7 @@
namespace Modules\Sirsoft\Board\Http\Resources;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\ResourceCollection;
use App\Http\Resources\BaseApiCollection;
use Illuminate\Pagination\LengthAwarePaginator;
use Modules\Sirsoft\Board\Traits\ChecksBoardPermission;
@@ -12,7 +12,7 @@ use Modules\Sirsoft\Board\Traits\ChecksBoardPermission;
*
* 게시판 목록을 페이지네이션과 함께 반환합니다.
*/
class BoardCollection extends ResourceCollection
class BoardCollection extends BaseApiCollection
{
use ChecksBoardPermission;
@@ -28,7 +28,7 @@ class BoardCollection extends ResourceCollection
'data' => $this->collection->map(function ($board) {
return new BoardResource($board);
}),
'pagination' => $this->when($this->resource instanceof LengthAwarePaginator, fn () => [
'pagination' => $this->resource instanceof LengthAwarePaginator ? [
'current_page' => $this->resource->currentPage(),
'last_page' => $this->resource->lastPage(),
'per_page' => $this->resource->perPage(),
@@ -36,7 +36,7 @@ class BoardCollection extends ResourceCollection
'from' => $this->resource->firstItem(),
'to' => $this->resource->lastItem(),
'has_more_pages' => $this->resource->hasMorePages(),
]),
] : null,
];
}
@@ -78,17 +78,12 @@ class BoardResource extends BaseApiResource
// 표시 설정
'new_display_hours' => $this->new_display_hours ?? 24,
// 게시판 관리 인원 (역할 기반)
'board_managers' => $this->getBoardRoleUsers("sirsoft-board.{$this->slug}.manager"),
'board_steps' => $this->getBoardRoleUsers("sirsoft-board.{$this->slug}.step"),
'board_manager_ids' => $this->getBoardRoleUserIds("sirsoft-board.{$this->slug}.manager"),
'board_step_ids' => $this->getBoardRoleUserIds("sirsoft-board.{$this->slug}.step"),
// 게시판 관리 인원 (역할 기반, 역할별 1회 조회로 통합)
...$this->getBoardRoleData("sirsoft-board.{$this->slug}"),
// 알림 설정
'notify_author' => $this->notify_author,
'notify_admin_on_post' => $this->notify_admin_on_post,
'notify_author_channels' => $this->notify_author_channels ?? [],
'notify_admin_on_post_channels' => $this->notify_admin_on_post_channels ?? [],
// 타임스탬프
'created_at' => $this->created_at?->format('Y-m-d H:i:s'),
@@ -258,36 +253,48 @@ class BoardResource extends BaseApiResource
* @param string $roleIdentifier 역할 identifier
* @return array 사용자 목록 [{id, name, email}, ...]
*/
private function getBoardRoleUsers(string $roleIdentifier): array
{
$role = \App\Models\Role::where('identifier', $roleIdentifier)->first();
if (! $role) {
return [];
}
return $role->users->map(fn ($user) => [
'uuid' => $user->uuid,
'name' => $user->name,
'email' => $user->email,
])->values()->toArray();
}
/**
* 게시판 역할에 할당된 사용자 ID 목록을 반환합니다.
* 게시판 역할(manager/step) 사용자 정보를 1회 조회로 통합 반환합니다.
*
* @param string $roleIdentifier 역할 identifier
* @return array 사용자 ID 배열
* 기존 getBoardRoleUsers() + getBoardRoleUserIds()가 역할별 2회씩 조회하던 것을
* 역할별 1회 조회로 통합합니다.
*
* @param string $rolePrefix 역할 접두사 (예: "sirsoft-board.free")
* @return array board_managers, board_steps, board_manager_ids, board_step_ids
*/
private function getBoardRoleUserIds(string $roleIdentifier): array
private function getBoardRoleData(string $rolePrefix): array
{
$role = \App\Models\Role::where('identifier', $roleIdentifier)->first();
$result = [
'board_managers' => [],
'board_steps' => [],
'board_manager_ids' => [],
'board_step_ids' => [],
];
if (! $role) {
return [];
$roles = \App\Models\Role::whereIn('identifier', [
"{$rolePrefix}.manager",
"{$rolePrefix}.step",
])->with('users')->get();
foreach ($roles as $role) {
$users = $role->users->map(fn ($user) => [
'uuid' => $user->uuid,
'name' => $user->name,
'email' => $user->email,
])->values()->toArray();
$ids = $role->users->pluck('uuid')->toArray();
if (str_ends_with($role->identifier, '.manager')) {
$result['board_managers'] = $users;
$result['board_manager_ids'] = $ids;
} else {
$result['board_steps'] = $users;
$result['board_step_ids'] = $ids;
}
}
return $role->users->pluck('uuid')->toArray();
return $result;
}
// =========================================================================
@@ -385,18 +392,41 @@ class BoardResource extends BaseApiResource
'can_manage' => "sirsoft-board.{$slug}.manager",
];
// 8개 권한을 일괄 조회 (개별 Permission::where() 8회 → whereIn 1회)
$identifiers = array_values($permissionMap);
$permissions = Permission::whereIn('identifier', $identifiers)->get()->keyBy('identifier');
$result = [];
foreach ($permissionMap as $canKey => $identifier) {
$permission = Permission::where('identifier', $identifier)->first();
if ($user) {
// 사용자의 역할별 권한을 한 번만 로드 (identifier + type 쌍으로 메모리 체크)
$userPermissions = $user->roles()
->with('permissions')
->get()
->pluck('permissions')
->flatten()
->map(fn ($p) => $p->identifier . '|' . ($p->type instanceof \BackedEnum ? $p->type->value : $p->type))
->unique()
->toArray();
if (! $permission) {
continue;
foreach ($permissionMap as $canKey => $identifier) {
$permission = $permissions->get($identifier);
if (! $permission) {
continue;
}
$typeValue = $permission->type instanceof \BackedEnum ? $permission->type->value : $permission->type;
$result[$canKey] = in_array($permission->identifier . '|' . $typeValue, $userPermissions);
}
} else {
foreach ($permissionMap as $canKey => $identifier) {
$permission = $permissions->get($identifier);
if (! $permission) {
continue;
}
$result[$canKey] = $user
? $user->hasPermission($permission->identifier, $permission->type)
: $this->checkGuestPermission($permission);
$result[$canKey] = $this->checkGuestPermission($permission);
}
}
return $result;
@@ -117,13 +117,21 @@ class CommentResource extends BaseApiResource
/**
* 현재 로그인 사용자가 이 댓글을 이미 신고했는지 반환합니다.
*
* 비로그인 또는 post.board 관계 미로드 시 false 반환.
* Controller에서 사전 로드(is_already_reported_preloaded)된 값이 있으면
* DB 쿼리 없이 반환합니다. (N+1 방지)
* 사전 로드가 없는 경우(목록 등) fallback으로 개별 쿼리를 실행합니다.
*
* @param Request $request HTTP 요청
* @return bool 이미 신고 여부
*/
private function getIsAlreadyReported(Request $request): bool
{
// 사전 로드된 값이 있으면 DB 쿼리 없이 반환 (N+1 방지)
if (isset($this->resource->is_already_reported_preloaded)) {
return $this->resource->is_already_reported_preloaded;
}
// fallback: 개별 쿼리 (목록 등 사전 로드 미적용 경로)
$user = $request->user();
$boardId = $this->post?->board?->id ?? null;
@@ -3,9 +3,8 @@
namespace Modules\Sirsoft\Board\Http\Resources;
use App\Enums\PermissionType;
use App\Http\Resources\Traits\HasRowNumber;
use App\Http\Resources\BaseApiCollection;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\ResourceCollection;
use Modules\Sirsoft\Board\Traits\ChecksBoardPermission;
/**
@@ -14,10 +13,9 @@ use Modules\Sirsoft\Board\Traits\ChecksBoardPermission;
* 게시글 목록을 페이지네이션과 함께 반환합니다.
* 순번, 공지사항, 답글 표시를 지원합니다.
*/
class PostCollection extends ResourceCollection
class PostCollection extends BaseApiCollection
{
use ChecksBoardPermission;
use HasRowNumber;
/**
* 전체 일반 게시글(원글) 수
@@ -198,13 +196,14 @@ class PostCollection extends ResourceCollection
return [
'total' => $total,
'all_total' => $this->total(),
'all_total' => $total,
'count' => $currentPageItemCount,
'per_page' => $perPage,
'current_page' => $currentPage,
'last_page' => $lastPage,
'from' => $from,
'to' => $to,
'has_more_pages' => $this->hasMorePages(),
];
}
@@ -22,7 +22,7 @@ class PostResource extends BaseApiResource
use FormatsBoardDate;
/**
* 리소스를 배열로 변환합니다.
* 리소스를 배열로 변환합니다. (상세 페이지용)
*
* @param Request $request HTTP 요청
* @return array<string, mixed> 변환된 배열 데이터
@@ -32,71 +32,37 @@ class PostResource extends BaseApiResource
$slug = $this->getSlug($request);
return [
'id' => $this->id,
'category' => $this->category,
...$this->getCommonFields($request, $slug),
// 상세 전용: 필터링된 제목/내용 (삭제글·비밀글 권한 체크)
'title' => $this->getFilteredTitle($slug),
'content' => $this->getFilteredContent($request, $slug),
// 작성자 정보
// 상세 전용: 작성자 UUID
'user_id' => $this->user?->uuid,
'author' => $this->getAuthorInfo(includeIsGuest: true),
// 게시글 속성
'is_notice' => (bool) $this->is_notice,
'is_secret' => (bool) $this->is_secret,
'content_mode' => $this->content_mode ?? 'text',
'is_new' => $this->isNew(),
'status' => $this->status?->value,
'status_label' => $this->status?->label(),
// 상세 전용: 트리거 타입
'trigger_type' => $this->trigger_type,
// 통계
'view_count' => $this->view_count,
'comment_count' => (int) ($this->comments_count ?? 0),
'reply_count' => (int) ($this->replies_count ?? 0),
'has_attachment' => ((int) ($this->attachments_count ?? 0)) > 0,
// 썸네일 이미지 (첫 번째 이미지 첨부파일)
'thumbnail' => $this->relationLoaded('attachments') ? $this->getThumbnailUrl() : null,
// 계층 구조
'parent_id' => $this->parent_id,
'depth' => $this->depth,
'is_reply' => $this->parent_id !== null,
// 타임스탬프
'created_at' => $this->formatCreatedAt($this->created_at),
'created_at_formatted' => $this->formatCreatedAtFormat(
$this->created_at,
g7_module_settings('sirsoft-board', 'display.date_display_format', 'standard')
),
// 상세 전용: 타임스탬프
'updated_at' => $this->formatDateTimeStringForUser($this->updated_at),
'deleted_at' => $this->deleted_at ? $this->formatDateTimeStringForUser($this->deleted_at) : null,
// IP 주소 (admin.manage 권한 보유자만)
'ip_address' => ($slug && $this->checkBoardPermission($slug, 'admin.manage'))
? $this->ip_address
: null,
// 상세 전용: IP 주소 (admin.manage 권한 보유자만)
'ip_address' => $this->getIpAddressForResponse($slug),
// 상세 정보 (조건부 로딩)
// 상세 전용: 관계 데이터 (조건부 로딩)
'board' => $this->relationLoaded('board') ? $this->getBoardInfo() : null,
'navigation' => isset($this->navigation) ? $this->navigation : null,
'navigation' => $this->navigation ?? null,
'parent' => $this->relationLoaded('parent') ? $this->getParentInfo() : null,
'comments' => $this->relationLoaded('comments') ? CommentResource::collection($this->comments) : null,
'attachments' => $this->relationLoaded('attachments')
? (($this->is_secret && ! $this->canViewSecretContent($request)) ? [] : AttachmentResource::collection($this->attachments))
: null,
'attachments' => $this->getAttachmentsForResponse($request, $slug),
'replies' => $this->relationLoaded('replies') ? static::collection($this->replies) : null,
// 소유권 정보
// is_author: 회원 글인 경우만 본인 여부 체크 (비회원 글은 세션 검증 불가하므로 항상 false)
'is_author' => $this->user_id !== null && $request->user()?->id === $this->user_id,
'is_guest_post' => $this->user_id === null,
// 신고 여부 (로그인 사용자 + board 관계 로드 시에만)
// 상세 전용: 신고 여부 (로그인 사용자 + board 관계 로드 시에만)
'is_already_reported' => $this->getIsAlreadyReported($request),
// 권한 정보 (is_owner + permissions)
// 권한 정보 (is_owner + abilities) — 상세 페이지에서만 포함
...$this->resourceMeta($request),
];
}
@@ -104,6 +70,9 @@ class PostResource extends BaseApiResource
/**
* 목록용 간략 정보를 배열로 변환합니다.
*
* 목록에서는 권한 정보(resourceMeta)를 포함하지 않습니다.
* 게시판 권한은 PostCollection의 컬렉션 레벨 abilities로 제공됩니다.
*
* 주의: 이 메서드는 toArray() 외부에서 수동 호출되므로
* $this->when() 대신 삼항 연산자를 사용해야 합니다.
*
@@ -116,11 +85,83 @@ class PostResource extends BaseApiResource
$slug = $this->getSlug($request);
return [
'id' => $this->id,
...$this->getCommonFields($request, $slug),
// 목록 전용: 게시판 슬러그
'slug' => $this->board_slug ?? null,
'category' => $this->category,
// 목록 전용: 필터링 없는 제목 (목록은 권한 체크 불필요)
'title' => $this->title,
// 목록 전용: 타임스탬프
'deleted_at' => $this->deleted_at ? $this->formatDateTimeStringForUser($this->deleted_at) : null,
// 목록 전용: 본문 요약 (DB SUBSTRING 우선, 없으면 content에서 추출)
'content_preview' => $this->getContentPreviewForList(150),
];
}
/**
* 폼(글쓰기/글수정)용 경량 배열을 반환합니다.
*
* toArray()와 달리 권한 체크(resolveAbilities, IP, 신고 여부)를 생략하여
* 불필요한 DB 쿼리를 방지합니다. 폼에서 필요한 필드만 포함합니다.
*
* @param Request|null $request HTTP 요청
* @return array<string, mixed> 변환된 배열 데이터
*/
public function toFormArray(?Request $request = null): array
{
$request = $request ?? request();
$slug = $this->getSlug($request);
return [
'id' => $this->id,
'title' => $this->title,
'content' => $this->content,
'content_mode' => $this->content_mode ?? 'text',
'category' => $this->category,
'is_notice' => (bool) $this->is_notice,
'is_secret' => (bool) $this->is_secret,
'parent_id' => $this->parent_id,
// 작성자 정보
'author' => $this->getAuthorInfo(includeIsGuest: true),
// 타임스탬프
'created_at' => $this->formatCreatedAt($this->created_at),
'created_at_formatted' => $this->formatCreatedAtFormat(
$this->created_at,
g7_module_settings('sirsoft-board', 'display.date_display_format', 'standard')
),
// 첨부파일 (권한 체크 없이 직접 반환 — 폼 진입 시 이미 본인/관리자 검증 완료)
'attachments' => $this->relationLoaded('attachments')
? AttachmentResource::collection($this->attachments)
: null,
// 원글 정보 (답변글 수정 시)
'parent' => $this->relationLoaded('parent') ? $this->getParentInfoForForm() : null,
];
}
// =========================================================================
// 공통 필드 추출
// =========================================================================
/**
* toArray()와 toListArray()에서 공유하는 공통 필드를 반환합니다.
*
* @param Request $request HTTP 요청
* @param string|null $slug 게시판 슬러그
* @return array<string, mixed> 공통 필드 데이터
*/
private function getCommonFields(Request $request, ?string $slug): array
{
return [
'id' => $this->id,
'category' => $this->category,
// 작성자 정보
'author' => $this->getAuthorInfo(includeIsGuest: true),
@@ -138,8 +179,8 @@ class PostResource extends BaseApiResource
'reply_count' => (int) ($this->replies_count ?? 0),
'has_attachment' => ((int) ($this->attachments_count ?? 0)) > 0,
// 썸네일 이미지
'thumbnail' => $this->relationLoaded('attachments') ? $this->getThumbnailUrl() : null,
// 썸네일 이미지 (첫 번째 이미지 첨부파일)
'thumbnail' => $this->getThumbnailUrlFromRelations(),
// 계층 구조
'parent_id' => $this->parent_id,
@@ -152,23 +193,16 @@ class PostResource extends BaseApiResource
$this->created_at,
g7_module_settings('sirsoft-board', 'display.date_display_format', 'standard')
),
'deleted_at' => $this->deleted_at ? $this->formatDateTimeStringForUser($this->deleted_at) : null,
// 본문 요약 (html 모드: strip_tags → 평문 앞 150자, text 모드: 그대로 앞 150자)
'content_preview' => $this->getContentPreview(150),
// 소유권 정보
// is_author: 회원 글인 경우만 본인 여부 체크 (비회원 글은 세션 검증 불가하므로 항상 false)
'is_author' => $this->user_id !== null && $request->user()?->id === $this->user_id,
'is_guest_post' => $this->user_id === null,
// 권한 정보 (is_owner + permissions)
...$this->resourceMeta($request),
];
}
// =========================================================================
// 헬퍼 메서드 - 공통 데이터 추출
// 헬퍼 메서드 - 데이터 추출
// =========================================================================
/**
@@ -179,7 +213,8 @@ class PostResource extends BaseApiResource
*/
private function getSlug(Request $request): ?string
{
return $this->board?->slug ?? $request->route('slug');
// route slug 우선 → board relation이 미로딩 시 lazy loading 방지
return $request->route('slug') ?? ($this->relationLoaded('board') ? $this->board?->slug : null);
}
/**
@@ -243,6 +278,36 @@ class PostResource extends BaseApiResource
return $firstImage?->preview_url ?? null;
}
/**
* 썸네일 URL을 관계 로딩 상태에 따라 반환합니다.
*
* thumbnailAttachment(경량 hasOne) 우선, attachments(전체) fallback.
* 둘 다 미로딩 시 null 반환 (lazy loading 방지).
*
* @return string|null 썸네일 URL
*/
private function getThumbnailUrlFromRelations(): ?string
{
// 목록용 경량 관계 우선 — slug를 직접 전달하여 Board::find() N+1 방지
if ($this->relationLoaded('thumbnailAttachment') && $this->thumbnailAttachment) {
$attachment = $this->thumbnailAttachment;
$slug = request()->route('slug') ?? ($this->relationLoaded('board') ? $this->board?->slug : null);
if ($slug && $attachment->hash) {
return '/api/modules/sirsoft-board/boards/' . $slug . '/attachment/' . $attachment->hash . '/preview';
}
return null;
}
// 상세 페이지 등에서 attachments가 로딩된 경우 fallback
if ($this->relationLoaded('attachments')) {
return $this->getThumbnailUrl();
}
return null;
}
/**
* 게시판 정보 배열을 반환합니다.
*
@@ -286,6 +351,25 @@ class PostResource extends BaseApiResource
return $parentData;
}
/**
* 폼용 원글 정보를 반환합니다.
*
* getParentInfo()와 달리 toFormArray()를 사용하여
* 불필요한 권한 체크(resolveAbilities 등)를 생략합니다.
*
* @return array|null 원글 정보 또는 null
*/
private function getParentInfoForForm(): ?array
{
if (! $this->parent) {
return null;
}
$parentResource = new static($this->parent);
return $parentResource->toFormArray();
}
/**
* 본문 요약 텍스트를 반환합니다.
*
@@ -311,6 +395,34 @@ class PostResource extends BaseApiResource
return $preview . (mb_strlen($plain) > $length ? '...' : '');
}
/**
* 목록용 본문 요약을 반환합니다.
*
* DB SUBSTRING으로 가져온 content_preview_raw가 있으면 우선 사용하고,
* 없으면 content에서 추출합니다. (상세 페이지 등 content가 로딩된 경우)
*
* @param int $length 최대 길이
* @return string 본문 요약 텍스트
*/
private function getContentPreviewForList(int $length = 150): string
{
// DB SUBSTRING으로 가져온 raw가 있으면 우선 사용
$raw = $this->content_preview_raw ?? null;
if ($raw !== null) {
$mode = $this->content_mode ?? 'text';
$plain = $mode === 'html'
? trim(preg_replace('/\s+/', ' ', html_entity_decode(strip_tags($raw))))
: trim(preg_replace('/\s+/', ' ', $raw));
$preview = mb_substr($plain, 0, $length);
return $preview . (mb_strlen($plain) > $length ? '...' : '');
}
// fallback: content 전체가 로딩된 경우 (상세 페이지 등)
return $this->getContentPreview($length);
}
/**
* 현재 로그인 사용자가 이 게시글을 이미 신고했는지 반환합니다.
*
@@ -330,6 +442,45 @@ class PostResource extends BaseApiResource
->hasUserReported($user->id, $this->board->id, 'post', $this->id);
}
// =========================================================================
// 상세 페이지 전용: 조건부 필드 메서드
// =========================================================================
/**
* IP 주소를 권한에 따라 반환합니다. (admin.manage 권한 보유자만)
*
* @param string|null $slug 게시판 슬러그
* @return string|null IP 주소
*/
private function getIpAddressForResponse(?string $slug): ?string
{
if (! $slug || ! $this->checkBoardPermission($slug, 'admin.manage')) {
return null;
}
return $this->ip_address;
}
/**
* 첨부파일을 권한에 따라 반환합니다. (비밀글 열람 권한 체크)
*
* @param Request $request HTTP 요청
* @param string|null $slug 게시판 슬러그
* @return mixed 첨부파일 리소스 컬렉션 또는 null
*/
private function getAttachmentsForResponse(Request $request, ?string $slug): mixed
{
if (! $this->relationLoaded('attachments')) {
return null;
}
if ($this->is_secret && ! $this->canViewSecretContent($request, $slug)) {
return [];
}
return AttachmentResource::collection($this->attachments);
}
// =========================================================================
// 권한 관련 메서드
// =========================================================================
@@ -350,6 +501,9 @@ class PostResource extends BaseApiResource
* Admin/User 페이지별로 동일한 키를 사용하되,
* 실제 체크하는 permission identifier는 컨텍스트에 따라 다릅니다.
*
* 참고: 목록에서는 이 메서드가 호출되지 않습니다.
* 목록의 권한은 PostCollection::getBoardPermissions()에서 컬렉션 레벨로 제공됩니다.
*
* @param Request $request HTTP 요청
* @return array<string, bool> 통합 권한 정보
*/
@@ -409,58 +563,46 @@ class PostResource extends BaseApiResource
/**
* 비밀글 내용 열람 가능 여부를 확인합니다.
*
* 열람 가능 조건:
* 열람 가능 조건 (우선순위 순):
* 1. 작성자 본인 (회원 게시글)
* 2. 비밀번호 검증 완료 (회원/비회원 게시글, password_verified 플래그)
* 3. 게시판별 비밀글 읽기 권한 (posts.read-secret)
* 4. 게시판 관리자 권한 (Admin: admin.manage / User: manager)
*
* @param Request $request HTTP 요청
* @param string|null $slug 게시판 슬러그 (getSlug 중복 호출 방지)
* @return bool 열람 가능 여부
*/
private function canViewSecretContent(Request $request): bool
private function canViewSecretContent(Request $request, ?string $slug = null): bool
{
$slug = $this->getSlug($request);
// 1. 작성자 본인 (회원 게시글)
$user = Auth::user();
if ($user && $this->user_id && $this->user_id === $user->id) {
return true;
}
// 2. 비밀번호 검증 완료 (회원/비회원 게시글 모두 지원)
// 2. 비밀번호 검증 완료
if ($this->password_verified === true) {
return true;
}
// 3. 게시판별 비밀글 읽기 권한 + 4. 게시판 관리자 권한
if ($slug) {
if ($this->isAdminRequest($request)) {
// 3. 비밀글 읽기 권한 (Admin: admin.posts.read-secret)
if ($this->checkBoardPermission($slug, 'admin.posts.read-secret')) {
return true;
}
// 4. 게시판 관리자 권한 (Admin: admin.manage)
if ($this->checkBoardPermission($slug, 'admin.manage')) {
return true;
}
} else {
// 3. 비밀글 읽기 권한 (User: posts.read-secret)
if ($this->checkBoardPermission($slug, 'posts.read-secret', PermissionType::User)) {
return true;
}
// 4. 게시판 관리자 권한 (User: manager)
if ($this->checkBoardPermission($slug, 'manager', PermissionType::User)) {
return true;
}
}
// 3-4. 게시판별 권한 체크
$slug = $slug ?? $this->getSlug($request);
if (! $slug) {
return false;
}
return false;
if ($this->isAdminRequest($request)) {
return $this->checkBoardPermission($slug, 'admin.posts.read-secret')
|| $this->checkBoardPermission($slug, 'admin.manage');
}
return $this->checkBoardPermission($slug, 'posts.read-secret', PermissionType::User)
|| $this->checkBoardPermission($slug, 'manager', PermissionType::User);
}
// =========================================================================
// 콘텐츠 필터링 메서드
// 콘텐츠 필터링 메서드 (상세 페이지 전용)
// =========================================================================
/**
@@ -500,11 +642,10 @@ class PostResource extends BaseApiResource
// 비밀글: 권한 없으면 content를 null로 반환
// - is_secret = true인 경우에만 검증 필요
// - 일반글(is_secret = false)은 비밀번호 유무와 관계없이 공개
if ($this->is_secret && ! $this->canViewSecretContent($request)) {
if ($this->is_secret && ! $this->canViewSecretContent($request, $slug)) {
return null;
}
return $this->content;
}
}
@@ -3,7 +3,7 @@
namespace Modules\Sirsoft\Board\Http\Resources;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\ResourceCollection;
use App\Http\Resources\BaseApiCollection;
use Modules\Sirsoft\Board\Traits\ChecksBoardPermission;
/**
@@ -11,7 +11,7 @@ use Modules\Sirsoft\Board\Traits\ChecksBoardPermission;
*
* 신고 목록을 페이지네이션과 함께 반환합니다.
*/
class ReportCollection extends ResourceCollection
class ReportCollection extends BaseApiCollection
{
use ChecksBoardPermission;