more fixes
This commit is contained in:
@@ -31,11 +31,15 @@ class AvatarController extends Controller
|
||||
$file = $request->file('avatar');
|
||||
|
||||
try {
|
||||
$hash = $this->service->storeFromUploadedFile($user->id, $file);
|
||||
$hash = $this->service->storeFromUploadedFile(
|
||||
(int) $user->id,
|
||||
$file,
|
||||
(string) $request->input('avatar_position', 'center')
|
||||
);
|
||||
return response()->json([
|
||||
'success' => true,
|
||||
'hash' => $hash,
|
||||
'url' => AvatarUrl::forUser((int) $user->id, $hash, 128),
|
||||
'url' => AvatarUrl::forUser((int) $user->id, $hash, 256),
|
||||
], 200);
|
||||
} catch (RuntimeException $e) {
|
||||
logger()->warning('Avatar upload validation failed', [
|
||||
|
||||
@@ -4,9 +4,20 @@ namespace App\Http\Controllers\User;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Http\Requests\ProfileUpdateRequest;
|
||||
use App\Http\Requests\Settings\RequestEmailChangeRequest;
|
||||
use App\Http\Requests\Settings\UpdateAccountSectionRequest;
|
||||
use App\Http\Requests\Settings\UpdateNotificationsSectionRequest;
|
||||
use App\Http\Requests\Settings\UpdatePersonalSectionRequest;
|
||||
use App\Http\Requests\Settings\UpdateProfileSectionRequest;
|
||||
use App\Http\Requests\Settings\UpdateSecurityPasswordRequest;
|
||||
use App\Http\Requests\Settings\VerifyEmailChangeRequest;
|
||||
use App\Mail\EmailChangedSecurityAlertMail;
|
||||
use App\Mail\EmailChangeVerificationCodeMail;
|
||||
use App\Models\Artwork;
|
||||
use App\Models\ProfileComment;
|
||||
use App\Models\Story;
|
||||
use App\Models\User;
|
||||
use App\Services\AvatarService;
|
||||
use App\Services\ArtworkService;
|
||||
use App\Services\FollowService;
|
||||
use App\Services\ThumbnailPresenter;
|
||||
@@ -14,6 +25,7 @@ use App\Services\ThumbnailService;
|
||||
use App\Services\UsernameApprovalService;
|
||||
use App\Services\UserStatsService;
|
||||
use App\Support\AvatarUrl;
|
||||
use App\Support\CoverUrl;
|
||||
use App\Support\UsernamePolicy;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
@@ -24,6 +36,7 @@ use Illuminate\Support\Facades\Redirect;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\View\View;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use Illuminate\Validation\Rules\Password as PasswordRule;
|
||||
use Inertia\Inertia;
|
||||
|
||||
@@ -127,6 +140,16 @@ class ProfileController extends Controller
|
||||
public function editSettings(Request $request)
|
||||
{
|
||||
$user = $request->user();
|
||||
$cooldownDays = $this->usernameCooldownDays();
|
||||
$lastUsernameChangeAt = $this->lastUsernameChangeAt($user);
|
||||
$usernameCooldownRemainingDays = 0;
|
||||
|
||||
if ($lastUsernameChangeAt !== null) {
|
||||
$nextAllowedChangeAt = $lastUsernameChangeAt->copy()->addDays($cooldownDays);
|
||||
if ($nextAllowedChangeAt->isFuture()) {
|
||||
$usernameCooldownRemainingDays = now()->diffInDays($nextAllowedChangeAt);
|
||||
}
|
||||
}
|
||||
|
||||
// Parse birth date parts
|
||||
$birthDay = null;
|
||||
@@ -176,9 +199,15 @@ class ProfileController extends Controller
|
||||
// Avatar URL
|
||||
$avatarHash = $profileData['avatar_hash'] ?? $user->icon ?? null;
|
||||
$avatarUrl = !empty($avatarHash)
|
||||
? AvatarUrl::forUser((int) $user->id, $avatarHash, 128)
|
||||
? AvatarUrl::forUser((int) $user->id, $avatarHash, 256)
|
||||
: AvatarUrl::default();
|
||||
|
||||
$emailNotifications = (bool) ($profileData['email_notifications'] ?? $profileData['mlist'] ?? $user->mlist ?? true);
|
||||
$uploadNotifications = (bool) ($profileData['upload_notifications'] ?? $profileData['friend_upload_notice'] ?? $user->friend_upload_notice ?? true);
|
||||
$followerNotifications = (bool) ($profileData['follower_notifications'] ?? true);
|
||||
$commentNotifications = (bool) ($profileData['comment_notifications'] ?? true);
|
||||
$newsletter = (bool) ($profileData['newsletter'] ?? $profileData['mlist'] ?? $user->mlist ?? false);
|
||||
|
||||
return Inertia::render('Settings/ProfileEdit', [
|
||||
'user' => [
|
||||
'id' => $user->id,
|
||||
@@ -190,16 +219,23 @@ class ProfileController extends Controller
|
||||
'signature' => $user->signature ?? null,
|
||||
'description' => $user->description ?? null,
|
||||
'gender' => $user->gender ?? null,
|
||||
'birthday' => $user->birth ?? null,
|
||||
'country_code' => $user->country_code ?? null,
|
||||
'mlist' => $user->mlist ?? false,
|
||||
'friend_upload_notice' => $user->friend_upload_notice ?? false,
|
||||
'auto_post_upload' => $user->auto_post_upload ?? false,
|
||||
'email_notifications' => $emailNotifications,
|
||||
'upload_notifications' => $uploadNotifications,
|
||||
'follower_notifications' => $followerNotifications,
|
||||
'comment_notifications' => $commentNotifications,
|
||||
'newsletter' => $newsletter,
|
||||
'last_username_change_at' => $user->last_username_change_at,
|
||||
'username_changed_at' => $user->username_changed_at,
|
||||
],
|
||||
'avatarUrl' => $avatarUrl,
|
||||
'birthDay' => $birthDay,
|
||||
'birthMonth' => $birthMonth,
|
||||
'birthYear' => $birthYear,
|
||||
'usernameCooldownDays' => $cooldownDays,
|
||||
'usernameCooldownRemainingDays' => $usernameCooldownRemainingDays,
|
||||
'usernameCooldownActive' => $usernameCooldownRemainingDays > 0,
|
||||
'countries' => $countries->values(),
|
||||
'flash' => [
|
||||
'status' => session('status'),
|
||||
@@ -208,6 +244,331 @@ class ProfileController extends Controller
|
||||
])->rootView('settings');
|
||||
}
|
||||
|
||||
public function updateProfileSection(UpdateProfileSectionRequest $request, AvatarService $avatarService): RedirectResponse|JsonResponse
|
||||
{
|
||||
$user = $request->user();
|
||||
$validated = $request->validated();
|
||||
|
||||
$user->name = (string) $validated['display_name'];
|
||||
$user->save();
|
||||
|
||||
$profileUpdates = [
|
||||
'website' => $validated['website'] ?? null,
|
||||
'about' => $validated['bio'] ?? null,
|
||||
'signature' => $validated['signature'] ?? null,
|
||||
'description' => $validated['description'] ?? null,
|
||||
];
|
||||
|
||||
$avatarUrl = AvatarUrl::forUser((int) $user->id, null, 256);
|
||||
|
||||
if (!empty($validated['remove_avatar'])) {
|
||||
$avatarService->removeAvatar((int) $user->id);
|
||||
$avatarUrl = AvatarUrl::default();
|
||||
}
|
||||
|
||||
if ($request->hasFile('avatar')) {
|
||||
$hash = $avatarService->storeFromUploadedFile(
|
||||
(int) $user->id,
|
||||
$request->file('avatar'),
|
||||
(string) ($validated['avatar_position'] ?? 'center')
|
||||
);
|
||||
$avatarUrl = AvatarUrl::forUser((int) $user->id, $hash, 256);
|
||||
}
|
||||
|
||||
$this->persistProfileUpdates((int) $user->id, $profileUpdates);
|
||||
|
||||
return $this->settingsResponse(
|
||||
$request,
|
||||
'Profile updated successfully.',
|
||||
['avatarUrl' => $avatarUrl]
|
||||
);
|
||||
}
|
||||
|
||||
public function updateAccountSection(UpdateAccountSectionRequest $request): RedirectResponse|JsonResponse
|
||||
{
|
||||
return $this->updateUsername($request);
|
||||
}
|
||||
|
||||
public function updateUsername(UpdateAccountSectionRequest $request): RedirectResponse|JsonResponse
|
||||
{
|
||||
$user = $request->user();
|
||||
$validated = $request->validated();
|
||||
|
||||
$incomingUsername = UsernamePolicy::normalize((string) $validated['username']);
|
||||
$currentUsername = UsernamePolicy::normalize((string) ($user->username ?? ''));
|
||||
|
||||
if ($incomingUsername !== '' && $incomingUsername !== $currentUsername) {
|
||||
$similar = UsernamePolicy::similarReserved($incomingUsername);
|
||||
if ($similar !== null && ! UsernamePolicy::hasApprovedOverride($incomingUsername, (int) $user->id)) {
|
||||
$this->usernameApprovalService->submit($user, $incomingUsername, 'profile_update', [
|
||||
'current_username' => $currentUsername,
|
||||
]);
|
||||
|
||||
return $this->usernameValidationError($request, 'This username is too similar to a reserved name and requires manual approval.');
|
||||
}
|
||||
|
||||
$cooldownDays = $this->usernameCooldownDays();
|
||||
$isAdmin = method_exists($user, 'isAdmin') ? $user->isAdmin() : false;
|
||||
$lastUsernameChangeAt = $this->lastUsernameChangeAt($user);
|
||||
if (! $isAdmin && $lastUsernameChangeAt !== null && $lastUsernameChangeAt->gt(now()->subDays($cooldownDays))) {
|
||||
$remainingDays = now()->diffInDays($lastUsernameChangeAt->copy()->addDays($cooldownDays));
|
||||
|
||||
return $this->usernameValidationError($request, "You can change your username again in {$remainingDays} days.");
|
||||
}
|
||||
|
||||
$user->username = $incomingUsername;
|
||||
$user->username_changed_at = now();
|
||||
if (Schema::hasColumn('users', 'last_username_change_at')) {
|
||||
$user->last_username_change_at = now();
|
||||
}
|
||||
|
||||
$this->storeUsernameHistory((int) $user->id, $currentUsername);
|
||||
$this->storeUsernameRedirect((int) $user->id, $currentUsername, $incomingUsername);
|
||||
}
|
||||
|
||||
$user->save();
|
||||
|
||||
return $this->settingsResponse($request, 'Account updated successfully.');
|
||||
}
|
||||
|
||||
public function requestEmailChange(RequestEmailChangeRequest $request): RedirectResponse|JsonResponse
|
||||
{
|
||||
if (! Schema::hasTable('email_changes')) {
|
||||
return response()->json([
|
||||
'errors' => [
|
||||
'new_email' => ['Email change is not available right now.'],
|
||||
],
|
||||
], 422);
|
||||
}
|
||||
|
||||
$user = $request->user();
|
||||
$validated = $request->validated();
|
||||
$newEmail = strtolower((string) $validated['new_email']);
|
||||
$code = str_pad((string) random_int(0, 999999), 6, '0', STR_PAD_LEFT);
|
||||
$expiresInMinutes = 10;
|
||||
|
||||
DB::table('email_changes')->where('user_id', (int) $user->id)->delete();
|
||||
DB::table('email_changes')->insert([
|
||||
'user_id' => (int) $user->id,
|
||||
'new_email' => $newEmail,
|
||||
'verification_code' => hash('sha256', $code),
|
||||
'expires_at' => now()->addMinutes($expiresInMinutes),
|
||||
'created_at' => now(),
|
||||
'updated_at' => now(),
|
||||
]);
|
||||
|
||||
Mail::to($newEmail)->queue(new EmailChangeVerificationCodeMail($code, $expiresInMinutes));
|
||||
|
||||
return $this->settingsResponse($request, 'Verification code sent to your new email address.');
|
||||
}
|
||||
|
||||
public function verifyEmailChange(VerifyEmailChangeRequest $request): RedirectResponse|JsonResponse
|
||||
{
|
||||
if (! Schema::hasTable('email_changes')) {
|
||||
return response()->json([
|
||||
'errors' => [
|
||||
'code' => ['Email change verification is not available right now.'],
|
||||
],
|
||||
], 422);
|
||||
}
|
||||
|
||||
$user = $request->user();
|
||||
$validated = $request->validated();
|
||||
$codeHash = hash('sha256', (string) $validated['code']);
|
||||
|
||||
$change = DB::table('email_changes')
|
||||
->where('user_id', (int) $user->id)
|
||||
->whereNull('used_at')
|
||||
->orderByDesc('id')
|
||||
->first();
|
||||
|
||||
if (! $change) {
|
||||
return response()->json(['errors' => ['code' => ['No pending email change request found.']]], 422);
|
||||
}
|
||||
|
||||
if (now()->greaterThan($change->expires_at)) {
|
||||
DB::table('email_changes')->where('id', $change->id)->delete();
|
||||
|
||||
return response()->json(['errors' => ['code' => ['Verification code has expired. Please request a new one.']]], 422);
|
||||
}
|
||||
|
||||
if (! hash_equals((string) $change->verification_code, $codeHash)) {
|
||||
return response()->json(['errors' => ['code' => ['Verification code is invalid.']]], 422);
|
||||
}
|
||||
|
||||
$newEmail = strtolower((string) $change->new_email);
|
||||
$oldEmail = strtolower((string) ($user->email ?? ''));
|
||||
|
||||
DB::transaction(function () use ($user, $change, $newEmail): void {
|
||||
$lockedUser = User::query()->whereKey((int) $user->id)->lockForUpdate()->firstOrFail();
|
||||
$lockedUser->email = $newEmail;
|
||||
$lockedUser->email_verified_at = now();
|
||||
$lockedUser->save();
|
||||
|
||||
DB::table('email_changes')
|
||||
->where('id', (int) $change->id)
|
||||
->update([
|
||||
'used_at' => now(),
|
||||
'updated_at' => now(),
|
||||
]);
|
||||
|
||||
DB::table('email_changes')
|
||||
->where('user_id', (int) $user->id)
|
||||
->where('id', '!=', (int) $change->id)
|
||||
->delete();
|
||||
});
|
||||
|
||||
if ($oldEmail !== '' && $oldEmail !== $newEmail) {
|
||||
Mail::to($oldEmail)->queue(new EmailChangedSecurityAlertMail($newEmail));
|
||||
}
|
||||
|
||||
return $this->settingsResponse($request, 'Email updated successfully.', [
|
||||
'email' => $newEmail,
|
||||
]);
|
||||
}
|
||||
|
||||
public function updatePersonalSection(UpdatePersonalSectionRequest $request): RedirectResponse|JsonResponse
|
||||
{
|
||||
$validated = $request->validated();
|
||||
|
||||
$profileUpdates = [
|
||||
'birthdate' => $validated['birthday'] ?? null,
|
||||
'country_code' => $validated['country'] ?? null,
|
||||
];
|
||||
|
||||
if (!empty($validated['gender'])) {
|
||||
$profileUpdates['gender'] = strtoupper((string) $validated['gender']);
|
||||
}
|
||||
|
||||
$this->persistProfileUpdates((int) $request->user()->id, $profileUpdates);
|
||||
|
||||
return $this->settingsResponse($request, 'Personal details saved successfully.');
|
||||
}
|
||||
|
||||
public function updateNotificationsSection(UpdateNotificationsSectionRequest $request): RedirectResponse|JsonResponse
|
||||
{
|
||||
$validated = $request->validated();
|
||||
$userId = (int) $request->user()->id;
|
||||
|
||||
$profileUpdates = [
|
||||
'email_notifications' => (bool) $validated['email_notifications'],
|
||||
'upload_notifications' => (bool) $validated['upload_notifications'],
|
||||
'follower_notifications' => (bool) $validated['follower_notifications'],
|
||||
'comment_notifications' => (bool) $validated['comment_notifications'],
|
||||
'newsletter' => (bool) $validated['newsletter'],
|
||||
// Legacy compatibility mappings.
|
||||
'mlist' => (bool) $validated['newsletter'],
|
||||
'friend_upload_notice' => (bool) $validated['upload_notifications'],
|
||||
];
|
||||
|
||||
$this->persistProfileUpdates($userId, $profileUpdates);
|
||||
|
||||
return $this->settingsResponse($request, 'Notification settings saved successfully.');
|
||||
}
|
||||
|
||||
public function updateSecurityPassword(UpdateSecurityPasswordRequest $request): RedirectResponse|JsonResponse
|
||||
{
|
||||
$validated = $request->validated();
|
||||
$user = $request->user();
|
||||
$user->password = Hash::make((string) $validated['new_password']);
|
||||
$user->save();
|
||||
|
||||
return $this->settingsResponse($request, 'Password updated successfully.');
|
||||
}
|
||||
|
||||
private function settingsResponse(Request $request, string $message, array $payload = []): RedirectResponse|JsonResponse
|
||||
{
|
||||
if ($request->expectsJson()) {
|
||||
return response()->json([
|
||||
'success' => true,
|
||||
'message' => $message,
|
||||
...$payload,
|
||||
]);
|
||||
}
|
||||
|
||||
return Redirect::back()->with('status', $message);
|
||||
}
|
||||
|
||||
private function persistProfileUpdates(int $userId, array $updates): void
|
||||
{
|
||||
if ($updates === [] || !Schema::hasTable('user_profiles')) {
|
||||
return;
|
||||
}
|
||||
|
||||
$filtered = [];
|
||||
foreach ($updates as $column => $value) {
|
||||
if (Schema::hasColumn('user_profiles', $column)) {
|
||||
$filtered[$column] = $value;
|
||||
}
|
||||
}
|
||||
|
||||
if ($filtered === []) {
|
||||
return;
|
||||
}
|
||||
|
||||
DB::table('user_profiles')->updateOrInsert(['user_id' => $userId], $filtered);
|
||||
}
|
||||
|
||||
private function usernameCooldownDays(): int
|
||||
{
|
||||
return max(1, (int) config('usernames.rename_cooldown_days', 30));
|
||||
}
|
||||
|
||||
private function lastUsernameChangeAt(User $user): ?\Illuminate\Support\Carbon
|
||||
{
|
||||
return $user->last_username_change_at ?? $user->username_changed_at;
|
||||
}
|
||||
|
||||
private function usernameValidationError(Request $request, string $message): RedirectResponse|JsonResponse
|
||||
{
|
||||
$error = ['username' => [$message]];
|
||||
if ($request->expectsJson()) {
|
||||
return response()->json(['errors' => $error], 422);
|
||||
}
|
||||
|
||||
return Redirect::back()->withErrors($error);
|
||||
}
|
||||
|
||||
private function storeUsernameHistory(int $userId, string $oldUsername): void
|
||||
{
|
||||
if ($oldUsername === '' || ! Schema::hasTable('username_history')) {
|
||||
return;
|
||||
}
|
||||
|
||||
$payload = [
|
||||
'user_id' => $userId,
|
||||
'old_username' => $oldUsername,
|
||||
'created_at' => now(),
|
||||
];
|
||||
|
||||
if (Schema::hasColumn('username_history', 'changed_at')) {
|
||||
$payload['changed_at'] = now();
|
||||
}
|
||||
|
||||
if (Schema::hasColumn('username_history', 'updated_at')) {
|
||||
$payload['updated_at'] = now();
|
||||
}
|
||||
|
||||
DB::table('username_history')->insert($payload);
|
||||
}
|
||||
|
||||
private function storeUsernameRedirect(int $userId, string $oldUsername, string $newUsername): void
|
||||
{
|
||||
if ($oldUsername === '' || ! Schema::hasTable('username_redirects')) {
|
||||
return;
|
||||
}
|
||||
|
||||
DB::table('username_redirects')->updateOrInsert(
|
||||
['old_username' => $oldUsername],
|
||||
[
|
||||
'new_username' => $newUsername,
|
||||
'user_id' => $userId,
|
||||
'updated_at' => now(),
|
||||
'created_at' => now(),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
public function update(ProfileUpdateRequest $request, \App\Services\AvatarService $avatarService): RedirectResponse|JsonResponse
|
||||
{
|
||||
$user = $request->user();
|
||||
@@ -238,10 +599,11 @@ class ProfileController extends Controller
|
||||
return Redirect::back()->withErrors($error);
|
||||
}
|
||||
|
||||
$cooldownDays = (int) config('usernames.rename_cooldown_days', 90);
|
||||
$cooldownDays = $this->usernameCooldownDays();
|
||||
$isAdmin = method_exists($user, 'isAdmin') ? $user->isAdmin() : false;
|
||||
$lastUsernameChangeAt = $this->lastUsernameChangeAt($user);
|
||||
|
||||
if (! $isAdmin && $user->username_changed_at !== null && $user->username_changed_at->gt(now()->subDays($cooldownDays))) {
|
||||
if (! $isAdmin && $lastUsernameChangeAt !== null && $lastUsernameChangeAt->gt(now()->subDays($cooldownDays))) {
|
||||
$error = ['username' => ["Username can only be changed once every {$cooldownDays} days."]];
|
||||
if ($request->expectsJson()) {
|
||||
return response()->json(['errors' => $error], 422);
|
||||
@@ -251,26 +613,12 @@ class ProfileController extends Controller
|
||||
|
||||
$user->username = $incomingUsername;
|
||||
$user->username_changed_at = now();
|
||||
|
||||
DB::table('username_history')->insert([
|
||||
'user_id' => (int) $user->id,
|
||||
'old_username' => $currentUsername,
|
||||
'changed_at' => now(),
|
||||
'created_at' => now(),
|
||||
'updated_at' => now(),
|
||||
]);
|
||||
|
||||
if ($currentUsername !== '') {
|
||||
DB::table('username_redirects')->updateOrInsert(
|
||||
['old_username' => $currentUsername],
|
||||
[
|
||||
'new_username' => $incomingUsername,
|
||||
'user_id' => (int) $user->id,
|
||||
'updated_at' => now(),
|
||||
'created_at' => now(),
|
||||
]
|
||||
);
|
||||
if (Schema::hasColumn('users', 'last_username_change_at')) {
|
||||
$user->last_username_change_at = now();
|
||||
}
|
||||
|
||||
$this->storeUsernameHistory((int) $user->id, $currentUsername);
|
||||
$this->storeUsernameRedirect((int) $user->id, $currentUsername, $incomingUsername);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -579,6 +927,37 @@ class ProfileController extends Controller
|
||||
]);
|
||||
}
|
||||
|
||||
$creatorStories = Story::query()
|
||||
->published()
|
||||
->with(['tags'])
|
||||
->where('creator_id', $user->id)
|
||||
->latest('published_at')
|
||||
->limit(6)
|
||||
->get([
|
||||
'id',
|
||||
'slug',
|
||||
'title',
|
||||
'excerpt',
|
||||
'cover_image',
|
||||
'reading_time',
|
||||
'views',
|
||||
'likes_count',
|
||||
'comments_count',
|
||||
'published_at',
|
||||
])
|
||||
->map(fn (Story $story) => [
|
||||
'id' => $story->id,
|
||||
'slug' => $story->slug,
|
||||
'title' => $story->title,
|
||||
'excerpt' => $story->excerpt,
|
||||
'cover_url' => $story->cover_url,
|
||||
'reading_time' => $story->reading_time,
|
||||
'views' => (int) $story->views,
|
||||
'likes_count' => (int) $story->likes_count,
|
||||
'comments_count' => (int) $story->comments_count,
|
||||
'published_at' => $story->published_at?->toISOString(),
|
||||
]);
|
||||
|
||||
// ── Profile data ─────────────────────────────────────────────────────
|
||||
$profile = $user->profile;
|
||||
|
||||
@@ -593,15 +972,8 @@ class ProfileController extends Controller
|
||||
$countryName = $countryName ?? strtoupper((string) $profile->country_code);
|
||||
}
|
||||
|
||||
// ── Hero background artwork ─────────────────────────────────────────
|
||||
$heroBgUrl = Artwork::public()
|
||||
->published()
|
||||
->where('user_id', $user->id)
|
||||
->whereNotNull('hash')
|
||||
->whereNotNull('thumb_ext')
|
||||
->inRandomOrder()
|
||||
->limit(1)
|
||||
->first()?->thumbUrl('lg');
|
||||
// ── Cover image hero (preferred) ────────────────────────────────────
|
||||
$heroBgUrl = CoverUrl::forUser($user->cover_hash, $user->cover_ext, $user->updated_at?->timestamp ?? time());
|
||||
|
||||
// ── Increment profile views (async-safe, ignore errors) ──────────────
|
||||
if (! $isOwner) {
|
||||
@@ -645,6 +1017,8 @@ class ProfileController extends Controller
|
||||
'username' => $user->username,
|
||||
'name' => $user->name,
|
||||
'avatar_url' => $avatarUrl,
|
||||
'cover_url' => $heroBgUrl,
|
||||
'cover_position'=> (int) ($user->cover_position ?? 50),
|
||||
'created_at' => $user->created_at?->toISOString(),
|
||||
'last_visit_at' => $user->last_visit_at ? (string) $user->last_visit_at : null,
|
||||
],
|
||||
@@ -666,6 +1040,7 @@ class ProfileController extends Controller
|
||||
'viewerIsFollowing' => $viewerIsFollowing,
|
||||
'heroBgUrl' => $heroBgUrl,
|
||||
'profileComments' => $profileComments->values(),
|
||||
'creatorStories' => $creatorStories->values(),
|
||||
'countryName' => $countryName,
|
||||
'isOwner' => $isOwner,
|
||||
'auth' => $authData,
|
||||
|
||||
252
app/Http/Controllers/User/ProfileCoverController.php
Normal file
252
app/Http/Controllers/User/ProfileCoverController.php
Normal file
@@ -0,0 +1,252 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\User;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Support\CoverUrl;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\UploadedFile;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use Intervention\Image\Drivers\Gd\Driver as GdDriver;
|
||||
use Intervention\Image\Drivers\Imagick\Driver as ImagickDriver;
|
||||
use Intervention\Image\Encoders\JpegEncoder;
|
||||
use Intervention\Image\Encoders\PngEncoder;
|
||||
use Intervention\Image\Encoders\WebpEncoder;
|
||||
use Intervention\Image\ImageManager;
|
||||
use RuntimeException;
|
||||
|
||||
class ProfileCoverController extends Controller
|
||||
{
|
||||
private const ALLOWED_MIME_TYPES = ['image/jpeg', 'image/png', 'image/webp'];
|
||||
|
||||
private const MAX_FILE_SIZE_KB = 5120;
|
||||
|
||||
private const TARGET_WIDTH = 1920;
|
||||
|
||||
private const TARGET_HEIGHT = 480;
|
||||
|
||||
private const MIN_UPLOAD_WIDTH = 640;
|
||||
|
||||
private const MIN_UPLOAD_HEIGHT = 160;
|
||||
|
||||
private ?ImageManager $manager = null;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
try {
|
||||
$this->manager = extension_loaded('gd')
|
||||
? new ImageManager(new GdDriver())
|
||||
: new ImageManager(new ImagickDriver());
|
||||
} catch (\Throwable) {
|
||||
$this->manager = null;
|
||||
}
|
||||
}
|
||||
|
||||
public function upload(Request $request): JsonResponse
|
||||
{
|
||||
$user = $request->user();
|
||||
if (! $user) {
|
||||
return response()->json(['error' => 'Unauthorized'], 401);
|
||||
}
|
||||
|
||||
$validated = $request->validate([
|
||||
'cover' => [
|
||||
'required',
|
||||
'file',
|
||||
'image',
|
||||
'max:' . self::MAX_FILE_SIZE_KB,
|
||||
'mimes:jpg,jpeg,png,webp',
|
||||
'mimetypes:image/jpeg,image/png,image/webp',
|
||||
],
|
||||
]);
|
||||
|
||||
/** @var UploadedFile $file */
|
||||
$file = $validated['cover'];
|
||||
|
||||
try {
|
||||
$stored = $this->storeCoverFile($file);
|
||||
|
||||
$this->deleteCoverFile((string) $user->cover_hash, (string) $user->cover_ext);
|
||||
|
||||
$user->forceFill([
|
||||
'cover_hash' => $stored['hash'],
|
||||
'cover_ext' => $stored['ext'],
|
||||
'cover_position' => 50,
|
||||
])->save();
|
||||
|
||||
return response()->json([
|
||||
'success' => true,
|
||||
'cover_url' => CoverUrl::forUser($user->cover_hash, $user->cover_ext, time()),
|
||||
'cover_position' => (int) $user->cover_position,
|
||||
]);
|
||||
} catch (RuntimeException $e) {
|
||||
return response()->json([
|
||||
'error' => 'Validation failed',
|
||||
'message' => $e->getMessage(),
|
||||
], 422);
|
||||
} catch (\Throwable $e) {
|
||||
logger()->error('Profile cover upload failed', [
|
||||
'user_id' => (int) $user->id,
|
||||
'message' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
return response()->json(['error' => 'Processing failed'], 500);
|
||||
}
|
||||
}
|
||||
|
||||
public function updatePosition(Request $request): JsonResponse
|
||||
{
|
||||
$user = $request->user();
|
||||
if (! $user) {
|
||||
return response()->json(['error' => 'Unauthorized'], 401);
|
||||
}
|
||||
|
||||
$validated = $request->validate([
|
||||
'position' => ['required', 'integer', 'min:0', 'max:100'],
|
||||
]);
|
||||
|
||||
if (! $user->cover_hash || ! $user->cover_ext) {
|
||||
return response()->json(['error' => 'No cover image to update.'], 422);
|
||||
}
|
||||
|
||||
$user->forceFill([
|
||||
'cover_position' => (int) $validated['position'],
|
||||
])->save();
|
||||
|
||||
return response()->json([
|
||||
'success' => true,
|
||||
'cover_position' => (int) $user->cover_position,
|
||||
]);
|
||||
}
|
||||
|
||||
public function destroy(Request $request): JsonResponse
|
||||
{
|
||||
$user = $request->user();
|
||||
if (! $user) {
|
||||
return response()->json(['error' => 'Unauthorized'], 401);
|
||||
}
|
||||
|
||||
$this->deleteCoverFile((string) $user->cover_hash, (string) $user->cover_ext);
|
||||
|
||||
$user->forceFill([
|
||||
'cover_hash' => null,
|
||||
'cover_ext' => null,
|
||||
'cover_position' => 50,
|
||||
])->save();
|
||||
|
||||
return response()->json([
|
||||
'success' => true,
|
||||
'cover_url' => null,
|
||||
'cover_position' => 50,
|
||||
]);
|
||||
}
|
||||
|
||||
private function storageRoot(): string
|
||||
{
|
||||
return rtrim((string) config('uploads.storage_root'), DIRECTORY_SEPARATOR);
|
||||
}
|
||||
|
||||
private function coverDirectory(string $hash): string
|
||||
{
|
||||
$p1 = substr($hash, 0, 2);
|
||||
$p2 = substr($hash, 2, 2);
|
||||
|
||||
return $this->storageRoot()
|
||||
. DIRECTORY_SEPARATOR . 'covers'
|
||||
. DIRECTORY_SEPARATOR . $p1
|
||||
. DIRECTORY_SEPARATOR . $p2;
|
||||
}
|
||||
|
||||
private function coverPath(string $hash, string $ext): string
|
||||
{
|
||||
return $this->coverDirectory($hash) . DIRECTORY_SEPARATOR . $hash . '.' . $ext;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{hash: string, ext: string}
|
||||
*/
|
||||
private function storeCoverFile(UploadedFile $file): array
|
||||
{
|
||||
$this->assertImageManager();
|
||||
|
||||
$uploadPath = (string) ($file->getRealPath() ?: $file->getPathname());
|
||||
if ($uploadPath === '' || ! is_readable($uploadPath)) {
|
||||
throw new RuntimeException('Unable to resolve uploaded image path.');
|
||||
}
|
||||
|
||||
$raw = file_get_contents($uploadPath);
|
||||
if ($raw === false || $raw === '') {
|
||||
throw new RuntimeException('Unable to read uploaded image.');
|
||||
}
|
||||
|
||||
$finfo = new \finfo(FILEINFO_MIME_TYPE);
|
||||
$mime = strtolower((string) $finfo->buffer($raw));
|
||||
if (! in_array($mime, self::ALLOWED_MIME_TYPES, true)) {
|
||||
throw new RuntimeException('Unsupported image mime type.');
|
||||
}
|
||||
|
||||
$size = @getimagesizefromstring($raw);
|
||||
if (! is_array($size) || ($size[0] ?? 0) < 1 || ($size[1] ?? 0) < 1) {
|
||||
throw new RuntimeException('Uploaded file is not a valid image.');
|
||||
}
|
||||
|
||||
$width = (int) ($size[0] ?? 0);
|
||||
$height = (int) ($size[1] ?? 0);
|
||||
if ($width < self::MIN_UPLOAD_WIDTH || $height < self::MIN_UPLOAD_HEIGHT) {
|
||||
throw new RuntimeException(sprintf(
|
||||
'Image is too small. Minimum required size is %dx%d.',
|
||||
self::MIN_UPLOAD_WIDTH,
|
||||
self::MIN_UPLOAD_HEIGHT,
|
||||
));
|
||||
}
|
||||
|
||||
$ext = $mime === 'image/jpeg' ? 'jpg' : ($mime === 'image/png' ? 'png' : 'webp');
|
||||
$image = $this->manager->read($raw);
|
||||
$processed = $image->cover(self::TARGET_WIDTH, self::TARGET_HEIGHT, 'center');
|
||||
$encoded = $this->encodeByExtension($processed, $ext);
|
||||
|
||||
$hash = hash('sha256', $encoded);
|
||||
$dir = $this->coverDirectory($hash);
|
||||
if (! File::exists($dir)) {
|
||||
File::makeDirectory($dir, 0755, true);
|
||||
}
|
||||
|
||||
File::put($this->coverPath($hash, $ext), $encoded);
|
||||
|
||||
return ['hash' => $hash, 'ext' => $ext];
|
||||
}
|
||||
|
||||
private function encodeByExtension($image, string $ext): string
|
||||
{
|
||||
return match ($ext) {
|
||||
'jpg' => (string) $image->encode(new JpegEncoder(85)),
|
||||
'png' => (string) $image->encode(new PngEncoder()),
|
||||
default => (string) $image->encode(new WebpEncoder(85)),
|
||||
};
|
||||
}
|
||||
|
||||
private function deleteCoverFile(string $hash, string $ext): void
|
||||
{
|
||||
$trimHash = trim($hash);
|
||||
$trimExt = strtolower(trim($ext));
|
||||
|
||||
if ($trimHash === '' || $trimExt === '') {
|
||||
return;
|
||||
}
|
||||
|
||||
$path = $this->coverPath($trimHash, $trimExt);
|
||||
if (is_file($path)) {
|
||||
@unlink($path);
|
||||
}
|
||||
}
|
||||
|
||||
private function assertImageManager(): void
|
||||
{
|
||||
if ($this->manager !== null) {
|
||||
return;
|
||||
}
|
||||
|
||||
throw new RuntimeException('Image processing is not available on this environment.');
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user