Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 16 additions & 13 deletions app/Console/Commands/DeleteUnusedImages.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@

namespace App\Console\Commands;

use App\Models\AppSetting;
use App\Models\Blog;
use App\Models\ForumAnswer;
use App\Models\ForumPost;
use App\Models\Notice;
use App\Models\Resource;
use App\Models\SupportTicket;
use App\Models\User;
Expand Down Expand Up @@ -33,17 +33,13 @@ public function handle(): void
Blog::whereNotNull('featured_image_path')->pluck('featured_image_path')->toArray()
);

// Notice images — use DB::table to bypass the getImageAttribute accessor,
// which converts stored paths to full URLs and would cause every notice
// image to be falsely flagged as unused.
$this->cleanDirectory(
'notices',
DB::table('notices')
->whereNotNull('image')
->where('image', 'not like', 'http%')
->pluck('image')
->toArray()
);
$rawNotice = AppSetting::get('site_notice');
$noticeData = is_array($rawNotice) ? $rawNotice : json_decode($rawNotice ?? '', true);
$noticeImages = [];
if (! empty($noticeData['image']) && ! str($noticeData['image'])->startsWith(['http://', 'https://'])) {
$noticeImages[] = $noticeData['image'];
}
$this->cleanDirectory('notices', $noticeImages);

// Resource files (items stored under resources/)
$rawItems = DB::table('resources')
Expand All @@ -67,9 +63,16 @@ public function handle(): void
);

// Forum post images
$forumPostImages = ForumPost::whereNotNull('images')
->pluck('images')
->flatten()
->filter(fn ($path) => is_string($path) && $path !== '' && ! str_starts_with($path, 'http'))
->values()
->all();

$this->cleanDirectory(
'forum/posts',
ForumPost::whereNotNull('image_path')->pluck('image_path')->toArray()
$forumPostImages
);

// Forum answer images
Expand Down
37 changes: 25 additions & 12 deletions app/Http/Controllers/ForumAnswerController.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use App\Models\ForumPost;
use App\Models\User;
use App\Notifications\ForumAnswerNotification;
use App\Notifications\ForumMentionNotification;
use App\Notifications\ForumReportNotification;
use App\Rules\CleanText;
use Illuminate\Http\JsonResponse;
Expand Down Expand Up @@ -48,7 +49,7 @@ public function store(Request $request, ForumPost $post): RedirectResponse
}

$validated = $request->validate([
'body' => ['required', 'string', 'min:2', 'max:10000', new CleanText],
'body' => ['required', 'string', 'min:2', 'max:1000', new CleanText],
'image' => ['nullable', 'image', 'mimes:jpeg,png,jpg,webp', 'max:5120'],
'parent_id' => ['nullable', 'exists:forum_answers,id'],
'reply_to_user_id' => ['nullable', 'exists:users,id'],
Expand All @@ -75,21 +76,33 @@ public function store(Request $request, ForumPost $post): RedirectResponse

$post->increment('answers_count');

$targetUser = null;
$isReply = false;
$mentionedUserIds = [];

if (isset($parent)) {
$isReply = true;
if (preg_match('/@([a-zA-Z0-9_]+)/', $validated['body'], $matches)) {
$targetUser = User::where('username', $matches[1])->first();
// Parse @username mentions in the answer body and dispatch notification to up to 5 mentioned users
if (preg_match_all('/@([a-zA-Z0-9_]+)/', $validated['body'], $matches)) {
$mentionedUsernames = array_unique(array_filter($matches[1], fn ($u) => strcasecmp($u, $user->username) !== 0));
if (! empty($mentionedUsernames)) {
$mentionedUsers = User::whereIn('username', array_slice($mentionedUsernames, 0, 5))
->select(['id', 'name', 'username', 'email'])
->get();

if ($mentionedUsers->isNotEmpty()) {
Notification::send($mentionedUsers, new ForumMentionNotification($post, $answer, $user));
$mentionedUserIds = $mentionedUsers->pluck('id')->all();
}
}
$targetUser = $targetUser ?: $parent->user;
} elseif ($post->user_id) {
$targetUser = $post->user;
}

if ($targetUser && $targetUser->id !== $user->id) {
$targetUser->notify(new ForumAnswerNotification($post, $answer, $isReply));
// Notify parent answer author or post author if not already notified via @mention
if (isset($parent)) {
$parentAuthor = $parent->user;
// Only notify root author if no @mention was present in the reply
if ($parentAuthor && $parentAuthor->id !== $user->id && empty($mentionedUserIds)) {
$parentAuthor->notify(new ForumAnswerNotification($post, $answer, true));
$mentionedUserIds[] = $parentAuthor->id;
}
} elseif ($post->user_id && $post->user_id !== $user->id && ! in_array($post->user_id, $mentionedUserIds, true)) {
$post->user?->notify(new ForumAnswerNotification($post, $answer, false));
}

return back()->with('success', 'Answer posted!');
Expand Down
77 changes: 54 additions & 23 deletions app/Http/Controllers/ForumController.php
Original file line number Diff line number Diff line change
Expand Up @@ -168,34 +168,54 @@ public function show(Request $request, ForumPost $post): Response
]);
}

public function create(): Response|RedirectResponse
public function generateUploadUrl(Request $request): JsonResponse
{
$user = auth()->user();
if ($user && $user->isBanned()) {
$bannedUntilFormatted = $user->banned_until->diffForHumans();

return redirect()->route('forum.index')->with('error', "You are temporarily suspended from community participation until {$user->banned_until->toDateTimeString()} ({$bannedUntilFormatted}).");
return response()->json([
'message' => 'You are suspended from uploading.',
], 403);
}

$isPostingEnabled = (bool) AppSetting::get('forum_posting_enabled', true);
if (! $isPostingEnabled) {
$reason = AppSetting::get('forum_disabled_reason', 'Creating new questions is temporarily paused.');

return redirect()->route('forum.index')->with('error', $reason ?: 'Creating new questions is temporarily paused.');
return response()->json([
'message' => AppSetting::get('forum_disabled_reason', 'Creating new questions is temporarily paused.'),
], 403);
}

$subjects = Cache::remember('forum_filter_subjects', now()->addDay(), function () {
return Subject::where('is_trackable', true)
->select('id', 'name', 'course', 'slug')
->with(['nodes' => fn ($q) => $q->where('is_trackable', true)->select('id', 'subject_id', 'name', 'slug')->orderBy('sort_order')])
->orderBy('sort_order')
->get()
->toArray();
});

return Inertia::render('Forum/Create', [
'subjects' => $subjects,
$validated = $request->validate([
'files' => ['required', 'array', 'min:1', 'max:4'],
'files.*.content_type' => ['required', 'string', 'in:image/jpeg,image/png,image/webp'],
'files.*.size' => ['required', 'integer', 'min:1', 'max:5242880'],
]);

$results = [];

foreach ($validated['files'] as $fileData) {
$extension = match ($fileData['content_type']) {
'image/jpeg' => 'jpg',
'image/png' => 'png',
'image/webp' => 'webp',
};

$key = 'forum/posts/'.(string) Str::uuid().'.'.$extension;
$signed = Storage::disk('s3')->temporaryUploadUrl(
$key,
now()->addMinutes(15),
[
'ContentType' => $fileData['content_type'],
'ContentLengthRange' => [1, $fileData['size']],
]
);

$results[] = [
'key' => $key,
'upload_url' => is_array($signed) ? $signed['url'] : $signed,
];
}

return response()->json(['urls' => $results]);
}

public function store(Request $request): RedirectResponse
Expand All @@ -220,11 +240,15 @@ public function store(Request $request): RedirectResponse
'subject_id' => ['nullable', 'exists:subjects,id'],
'node_id' => ['nullable', 'exists:nodes,id'],
'image' => ['nullable', 'image', 'mimes:jpeg,png,jpg,webp', 'max:5120'],
'images' => ['nullable', 'array', 'max:4'],
'images.*' => ['string', 'max:255', 'regex:#^forum/posts/[A-Za-z0-9._/-]+$#', 'not_regex:#\\.\\.#'],
]);

$imagePath = null;
if ($request->hasFile('image')) {
$imagePath = $request->file('image')->store('forum/posts');
$images = [];
if (! empty($validated['images'])) {
$images = array_slice($validated['images'], 0, 4);
} elseif ($request->hasFile('image')) {
$images = [$request->file('image')->store('forum/posts')];
}

$subjectId = $validated['subject_id'] ?? null;
Expand Down Expand Up @@ -258,7 +282,7 @@ public function store(Request $request): RedirectResponse
'curriculum' => $validated['curriculum'],
'slug' => $slug,
'body' => $validated['body'],
'image_path' => $imagePath,
'images' => ! empty($images) ? $images : null,
'is_locked' => false,
'moderation_status' => $moderationStatus,
]);
Expand All @@ -284,7 +308,14 @@ public function destroy(ForumPost $post): RedirectResponse
{
abort_unless(auth()->id() === $post->user_id || auth()->user()?->can('manage forums'), 403);

if ($post->image_path) {
$postImages = $post->images ?? [];
if (is_array($postImages)) {
foreach ($postImages as $img) {
if ($img && ! str($img)->startsWith(['http://', 'https://'])) {
Storage::delete($img);
}
}
} elseif (! empty($post->image_path)) {
Storage::delete($post->image_path);
}

Expand Down
4 changes: 2 additions & 2 deletions app/Http/Requests/Resource/StoreResourceRequest.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ public function authorize(): bool
if ($this->filled('node_id')) {
$node = Node::find($this->input('node_id'));

return ! ($node?->isEffectivelyFrozen());
return ! ($node?->is_frozen);
}

return true;
Expand All @@ -23,7 +23,7 @@ public function rules(): array
return [
'subject_id' => ['required', 'integer', 'exists:subjects,id'],
'node_id' => ['nullable', 'integer', 'exists:nodes,id'],
'resource_type' => ['required', 'string', 'in:note,practical,marked_book,other,video'],
'resource_type' => ['required', 'string', 'in:note,lecture_sheet,practical,marked_book,other,video'],
'title' => ['required', 'string', 'max:255'],
'description' => ['nullable', 'string'],
'items' => ['required', 'array', 'min:1'],
Expand Down
4 changes: 3 additions & 1 deletion app/Http/Requests/Resource/UpdateResourceRequest.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,11 @@ public function authorize(): bool
public function rules(): array
{
return [
'subject_id' => ['sometimes', 'nullable', 'integer', 'exists:subjects,id'],
'node_id' => ['sometimes', 'nullable', 'integer', 'exists:nodes,id'],
'title' => ['required', 'string', 'max:255'],
'description' => ['nullable', 'string'],
'resource_type' => ['required', 'string', 'in:note,practical,marked_book,other,video'],
'resource_type' => ['required', 'string', 'in:note,lecture_sheet,practical,marked_book,other,video'],
'items' => ['required', 'array', 'min:1'],
'items.*' => ['required', 'array'],
'items.*.format' => ['required', 'in:image,pdf,video'],
Expand Down
30 changes: 23 additions & 7 deletions app/Models/ForumPost.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ class ForumPost extends Model
'curriculum',
'slug',
'body',
'image_path',
'images',
'is_locked',
'moderation_status',
'vote_score',
Expand All @@ -35,11 +35,13 @@ class ForumPost extends Model

protected $appends = [
'image_url',
'image_urls',
];

protected function casts(): array
{
return [
'images' => 'array',
'is_locked' => 'boolean',
'vote_score' => 'integer',
'upvotes_count' => 'integer',
Expand All @@ -53,15 +55,29 @@ public function getRouteKeyName(): string
return 'slug';
}

public function getImageUrlAttribute(): ?string
public function getImageUrlsAttribute(): array
{
if (! $this->image_path) {
return null;
$images = $this->images;
if (! is_array($images) || empty($images)) {
return [];
}

return str($this->image_path)->startsWith(['http://', 'https://'])
? $this->image_path
: Storage::url($this->image_path);
return array_values(array_map(function ($img) {
if (! $img) {
return null;
}

return str($img)->startsWith(['http://', 'https://'])
? $img
: Storage::url($img);
}, array_filter($images)));
}

public function getImageUrlAttribute(): ?string
{
$urls = $this->image_urls;

return $urls[0] ?? null;
}

protected static function booted(): void
Expand Down
43 changes: 43 additions & 0 deletions app/Notifications/ForumMentionNotification.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<?php

namespace App\Notifications;

use App\Models\ForumAnswer;
use App\Models\ForumPost;
use App\Models\User;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Notification;
use Illuminate\Support\Str;

class ForumMentionNotification extends Notification implements ShouldQueue
{
use Queueable;

public function __construct(
public ForumPost $post,
public ForumAnswer $answer,
public User $sender,
) {}

public function via(object $notifiable): array
{
return ['database'];
}

public function toArray(object $notifiable): array
{
$snippet = Str::limit(strip_tags($this->answer->body), 80);
$postSnippet = $this->post->snippet(40);

return [
'type' => 'user_mention',
'title' => "@{$this->sender->username} mentioned you on \"{$postSnippet}\"",
'message' => "\"{$snippet}\"",
'url' => route('forum.show', $this->post->slug),
'post_id' => $this->post->id,
'answer_id' => $this->answer->id,
'sender_id' => $this->sender->id,
];
}
}
2 changes: 0 additions & 2 deletions database/factories/BlogFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,6 @@ public function definition(): array
'meta_description' => fake()->sentence(),

'seo_tags' => implode(',', fake()->words(5)),

'views' => fake()->numberBetween(0, 1000),
];
}
}
Loading
Loading