diff --git a/app/Controllers/Web/ProfileController.php b/app/Controllers/Web/ProfileController.php index bfb6f40..96a4a72 100644 --- a/app/Controllers/Web/ProfileController.php +++ b/app/Controllers/Web/ProfileController.php @@ -6,6 +6,7 @@ namespace App\Controllers\Web; use Rsgrinko\Proton\Auth\Auth; use Rsgrinko\Proton\Auth\Devices; +use Rsgrinko\Proton\Files\Attachment; use Rsgrinko\Proton\Files\Storage; use Rsgrinko\Proton\Http\Controller; use Rsgrinko\Proton\Http\Request; @@ -26,7 +27,7 @@ use Rsgrinko\Proton\Support\ProtonException; final class ProfileController extends Controller { /** Встроенные поля профиля сверх минимума ядра — не путать со своими, из UserField */ - private const COLUMNS = ['name', 'email', 'phone', 'website', 'position', 'location', 'bio']; + private const COLUMNS = ['name', 'email', 'phone', 'website', 'position', 'location', 'bio', 'theme']; /** Расширение => MIME: аватар — только растровая картинка, не любой файл из files.allowed */ private const AVATAR_TYPES = [ @@ -64,11 +65,13 @@ final class ProfileController extends Controller 'position' => 'nullable|max:191', 'location' => 'nullable|max:191', 'bio' => 'nullable|max:500', + 'theme' => 'nullable|in:light,dark', ]; $labels = [ 'name' => 'Имя', 'email' => 'Почта', 'phone' => 'Телефон', 'website' => 'Сайт', 'position' => 'Должность', 'location' => 'Город', 'bio' => 'О себе', + 'theme' => 'Тема оформления', ]; foreach ($fields as $field) { @@ -119,20 +122,21 @@ final class ProfileController extends Controller return $this->redirect('profile'); } + // Прежние вложения убираем только после того, как новое легло на + // диск и записалось, — иначе при сбое посреди загрузки человек + // остался бы без фото вовсе + $previous = Attachment::of('avatar', $user->id()); + try { - $stored = Storage::put($file, 'avatars'); + Attachment::attach($file, 'avatar', $user->id(), $user->id()); } catch (ProtonException $e) { $this->flash($e->getMessage(), 'error'); return $this->redirect('profile'); } - $previous = (string) $user->avatar_path; - - $user->forceFill(['avatar_path' => $stored['path'], 'avatar_mime' => $stored['mime']])->save(); - - if ($previous !== '') { - Storage::delete($previous); + foreach ($previous as $old) { + $old->remove(); } Audit::action('user', $user->id(), 'сменил фото профиля'); @@ -147,14 +151,11 @@ final class ProfileController extends Controller */ public function avatarDelete(User $user): Response { - $path = (string) $user->avatar_path; - - if ($path === '') { + if (!$user->hasAvatar()) { return $this->redirect('profile'); } - $user->forceFill(['avatar_path' => '', 'avatar_mime' => ''])->save(); - Storage::delete($path); + Attachment::detachAll('avatar', $user->id()); Audit::action('user', $user->id(), 'убрал фото профиля'); @@ -171,16 +172,17 @@ final class ProfileController extends Controller public function avatar(int $id): Response { /** @var User|null $user */ - $user = User::find($id); + $user = User::find($id); + $attachment = $user?->hasAvatar() === true ? $user->avatarAttachment() : null; - if ($user === null || !$user->hasAvatar()) { + if ($attachment === null) { return new Response('', 404); } // Ссылка несёт хеш пути файла (View::avatar()): пока фото не заменили, // адрес не меняется, и браузеру незачем перекачивать его на каждой // странице — без этих заголовков сессия шлёт no-store на любой ответ - return Response::file(Storage::path((string) $user->avatar_path), (string) $user->avatar_mime ?: 'application/octet-stream') + return Response::file(Storage::path((string) $attachment->path), (string) $attachment->mime ?: 'application/octet-stream') ->withHeader('Cache-Control', 'private, max-age=31536000, immutable') ->withHeader('Pragma', 'cache') ->withHeader('Expires', gmdate('D, d M Y H:i:s', time() + 31536000) . ' GMT'); diff --git a/framework/Models/User.php b/framework/Models/User.php index 35a297c..7f2a353 100644 --- a/framework/Models/User.php +++ b/framework/Models/User.php @@ -9,6 +9,7 @@ use Rsgrinko\Proton\Database\Connection; use Rsgrinko\Proton\Database\Model\Model; use Rsgrinko\Proton\Database\Model\Relations\BelongsTo; use Rsgrinko\Proton\Database\Model\Relations\HasMany; +use Rsgrinko\Proton\Files\Attachment; use Rsgrinko\Proton\Files\Storage; use Rsgrinko\Proton\Support\Str; @@ -27,6 +28,7 @@ final class User extends Model // Профиль сверх минимума ядра: не используются нигде, кроме самой // карточки — свободны для своих нужд в приложении поверх фреймворка 'phone', 'website', 'position', 'location', 'bio', + 'theme', ]; protected array $hidden = ['password_hash']; @@ -86,15 +88,34 @@ final class User extends Model } /** - * Не просто «путь записан», а «файл правда на диске» — иначе битая + * 'light' или 'dark' — ровно два значения, никакого «как в системе»: + * оформление панели не должно расходиться с тем, что согласовали. + */ + public function theme(): string + { + return (string) $this->raw('theme') === 'dark' ? 'dark' : 'light'; + } + + /** + * Текущее фото профиля — вложение с entity `avatar`. Их может накопиться + * несколько только между загрузкой новой и удалением старой (см. + * ProfileController::avatarUpload), поэтому действующее — всегда свежее. + */ + public function avatarAttachment(): ?Attachment + { + return Attachment::of('avatar', $this->id())[0] ?? null; + } + + /** + * Не просто «вложение есть», а «файл правда на диске» — иначе битая * ссылка (файл потёрли в обход загрузки) рисуется у всех сломанной * картинкой вместо заглушки. */ public function hasAvatar(): bool { - $path = trim((string) $this->raw('avatar_path')); + $attachment = $this->avatarAttachment(); - return $path !== '' && Storage::exists($path); + return $attachment !== null && Storage::exists((string) $attachment->path); } public function emailVerified(): bool diff --git a/framework/View/View.php b/framework/View/View.php index a5f03c3..3110efc 100644 --- a/framework/View/View.php +++ b/framework/View/View.php @@ -324,9 +324,10 @@ final class View $name = trim((string) ($user->name ?: $user->login)); if ($user->hasAvatar()) { + $attachment = $user->avatarAttachment(); // Хвост в адресе — от пути файла: заменили фото — изменился путь, // изменилась и ссылка, старая копия в кэше браузера не мешает - $version = substr(md5((string) $user->raw('avatar_path')), 0, 8); + $version = substr(md5((string) $attachment->path), 0, 8); $url = self::route('avatar.show', ['id' => $user->id()]) . '?v=' . $version; return '' . self::e($name) . ''; diff --git a/migrations/20260917150000_add_user_theme.php b/migrations/20260917150000_add_user_theme.php new file mode 100644 index 0000000..fa9fc19 --- /dev/null +++ b/migrations/20260917150000_add_user_theme.php @@ -0,0 +1,31 @@ +table('users', function (Blueprint $table): void { + $table->string('theme', 5)->default('light'); + }); + } + + public function down(): void + { + $this->table('users', function (Blueprint $table): void { + $table->dropColumn('theme'); + }); + } +} diff --git a/migrations/20260917160000_move_avatar_to_attachments.php b/migrations/20260917160000_move_avatar_to_attachments.php new file mode 100644 index 0000000..c6ffc5f --- /dev/null +++ b/migrations/20260917160000_move_avatar_to_attachments.php @@ -0,0 +1,92 @@ +pretending()) { + $this->migrateExisting(); + } + + $this->table('users', function (Blueprint $table): void { + $table->dropColumn('avatar_path'); + $table->dropColumn('avatar_mime'); + }); + } + + public function down(): void + { + $this->table('users', function (Blueprint $table): void { + $table->string('avatar_path', 255)->default(''); + $table->string('avatar_mime', 100)->default(''); + }); + + if (!$this->pretending()) { + $this->restoreExisting(); + } + } + + /** + * Уже загруженные фото — в attachments, до того как колонки пропадут: + * иначе всё, что успели загрузить, потерялось бы вместе с колонками. + */ + private function migrateExisting(): void + { + $users = $this->db()->select("SELECT id, avatar_path, avatar_mime FROM users WHERE avatar_path != ''"); + + foreach ($users as $user) { + $this->statement( + 'INSERT INTO attachments (entity, entity_id, path, name, mime, size, user_id, created_at, updated_at) + VALUES (:entity, :entity_id, :path, :name, :mime, 0, :user_id, :created_at, :updated_at)', + [ + 'entity' => 'avatar', + 'entity_id' => (string) $user['id'], + 'path' => (string) $user['avatar_path'], + 'name' => basename((string) $user['avatar_path']), + 'mime' => (string) $user['avatar_mime'], + 'user_id' => $user['id'], + 'created_at' => $this->now(), + 'updated_at' => $this->now(), + ] + ); + } + } + + /** + * Откат — последнее вложение с entity = avatar обратно в колонки. + */ + private function restoreExisting(): void + { + $rows = $this->db()->select("SELECT entity_id, path, mime FROM attachments WHERE entity = 'avatar' ORDER BY id DESC"); + + $seen = []; + + foreach ($rows as $row) { + $userId = (string) $row['entity_id']; + + if (isset($seen[$userId])) { + continue; + } + + $seen[$userId] = true; + + $this->statement( + 'UPDATE users SET avatar_path = :path, avatar_mime = :mime WHERE id = :id', + ['path' => $row['path'], 'mime' => $row['mime'], 'id' => (int) $userId] + ); + } + } +} diff --git a/resources/views/profile.php b/resources/views/profile.php index b814c37..e995338 100644 --- a/resources/views/profile.php +++ b/resources/views/profile.php @@ -92,6 +92,14 @@ use Rsgrinko\Proton\View\View; + + id(); ?> id()] ?? ''; ?>