Профиль: своя тема оформления, аватар переехал в attachments
This commit is contained in:
1 parent
bea1fe101a
commit
ac39ea289b
6 files changed
+175
-20
No files matched your search
@@ -6,6 +6,7 @@ namespace App\Controllers\Web;
|
|||||||
|
|
||||||
use Rsgrinko\Proton\Auth\Auth;
|
use Rsgrinko\Proton\Auth\Auth;
|
||||||
use Rsgrinko\Proton\Auth\Devices;
|
use Rsgrinko\Proton\Auth\Devices;
|
||||||
|
use Rsgrinko\Proton\Files\Attachment;
|
||||||
use Rsgrinko\Proton\Files\Storage;
|
use Rsgrinko\Proton\Files\Storage;
|
||||||
use Rsgrinko\Proton\Http\Controller;
|
use Rsgrinko\Proton\Http\Controller;
|
||||||
use Rsgrinko\Proton\Http\Request;
|
use Rsgrinko\Proton\Http\Request;
|
||||||
@@ -26,7 +27,7 @@ use Rsgrinko\Proton\Support\ProtonException;
|
|||||||
final class ProfileController extends Controller
|
final class ProfileController extends Controller
|
||||||
{
|
{
|
||||||
/** Встроенные поля профиля сверх минимума ядра — не путать со своими, из UserField */
|
/** Встроенные поля профиля сверх минимума ядра — не путать со своими, из 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 */
|
/** Расширение => MIME: аватар — только растровая картинка, не любой файл из files.allowed */
|
||||||
private const AVATAR_TYPES = [
|
private const AVATAR_TYPES = [
|
||||||
@@ -64,11 +65,13 @@ final class ProfileController extends Controller
|
|||||||
'position' => 'nullable|max:191',
|
'position' => 'nullable|max:191',
|
||||||
'location' => 'nullable|max:191',
|
'location' => 'nullable|max:191',
|
||||||
'bio' => 'nullable|max:500',
|
'bio' => 'nullable|max:500',
|
||||||
|
'theme' => 'nullable|in:light,dark',
|
||||||
];
|
];
|
||||||
|
|
||||||
$labels = [
|
$labels = [
|
||||||
'name' => 'Имя', 'email' => 'Почта', 'phone' => 'Телефон',
|
'name' => 'Имя', 'email' => 'Почта', 'phone' => 'Телефон',
|
||||||
'website' => 'Сайт', 'position' => 'Должность', 'location' => 'Город', 'bio' => 'О себе',
|
'website' => 'Сайт', 'position' => 'Должность', 'location' => 'Город', 'bio' => 'О себе',
|
||||||
|
'theme' => 'Тема оформления',
|
||||||
];
|
];
|
||||||
|
|
||||||
foreach ($fields as $field) {
|
foreach ($fields as $field) {
|
||||||
@@ -119,20 +122,21 @@ final class ProfileController extends Controller
|
|||||||
return $this->redirect('profile');
|
return $this->redirect('profile');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Прежние вложения убираем только после того, как новое легло на
|
||||||
|
// диск и записалось, — иначе при сбое посреди загрузки человек
|
||||||
|
// остался бы без фото вовсе
|
||||||
|
$previous = Attachment::of('avatar', $user->id());
|
||||||
|
|
||||||
try {
|
try {
|
||||||
$stored = Storage::put($file, 'avatars');
|
Attachment::attach($file, 'avatar', $user->id(), $user->id());
|
||||||
} catch (ProtonException $e) {
|
} catch (ProtonException $e) {
|
||||||
$this->flash($e->getMessage(), 'error');
|
$this->flash($e->getMessage(), 'error');
|
||||||
|
|
||||||
return $this->redirect('profile');
|
return $this->redirect('profile');
|
||||||
}
|
}
|
||||||
|
|
||||||
$previous = (string) $user->avatar_path;
|
foreach ($previous as $old) {
|
||||||
|
$old->remove();
|
||||||
$user->forceFill(['avatar_path' => $stored['path'], 'avatar_mime' => $stored['mime']])->save();
|
|
||||||
|
|
||||||
if ($previous !== '') {
|
|
||||||
Storage::delete($previous);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
Audit::action('user', $user->id(), 'сменил фото профиля');
|
Audit::action('user', $user->id(), 'сменил фото профиля');
|
||||||
@@ -147,14 +151,11 @@ final class ProfileController extends Controller
|
|||||||
*/
|
*/
|
||||||
public function avatarDelete(User $user): Response
|
public function avatarDelete(User $user): Response
|
||||||
{
|
{
|
||||||
$path = (string) $user->avatar_path;
|
if (!$user->hasAvatar()) {
|
||||||
|
|
||||||
if ($path === '') {
|
|
||||||
return $this->redirect('profile');
|
return $this->redirect('profile');
|
||||||
}
|
}
|
||||||
|
|
||||||
$user->forceFill(['avatar_path' => '', 'avatar_mime' => ''])->save();
|
Attachment::detachAll('avatar', $user->id());
|
||||||
Storage::delete($path);
|
|
||||||
|
|
||||||
Audit::action('user', $user->id(), 'убрал фото профиля');
|
Audit::action('user', $user->id(), 'убрал фото профиля');
|
||||||
|
|
||||||
@@ -171,16 +172,17 @@ final class ProfileController extends Controller
|
|||||||
public function avatar(int $id): Response
|
public function avatar(int $id): Response
|
||||||
{
|
{
|
||||||
/** @var User|null $user */
|
/** @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);
|
return new Response('', 404);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Ссылка несёт хеш пути файла (View::avatar()): пока фото не заменили,
|
// Ссылка несёт хеш пути файла (View::avatar()): пока фото не заменили,
|
||||||
// адрес не меняется, и браузеру незачем перекачивать его на каждой
|
// адрес не меняется, и браузеру незачем перекачивать его на каждой
|
||||||
// странице — без этих заголовков сессия шлёт no-store на любой ответ
|
// странице — без этих заголовков сессия шлёт 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('Cache-Control', 'private, max-age=31536000, immutable')
|
||||||
->withHeader('Pragma', 'cache')
|
->withHeader('Pragma', 'cache')
|
||||||
->withHeader('Expires', gmdate('D, d M Y H:i:s', time() + 31536000) . ' GMT');
|
->withHeader('Expires', gmdate('D, d M Y H:i:s', time() + 31536000) . ' GMT');
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ use Rsgrinko\Proton\Database\Connection;
|
|||||||
use Rsgrinko\Proton\Database\Model\Model;
|
use Rsgrinko\Proton\Database\Model\Model;
|
||||||
use Rsgrinko\Proton\Database\Model\Relations\BelongsTo;
|
use Rsgrinko\Proton\Database\Model\Relations\BelongsTo;
|
||||||
use Rsgrinko\Proton\Database\Model\Relations\HasMany;
|
use Rsgrinko\Proton\Database\Model\Relations\HasMany;
|
||||||
|
use Rsgrinko\Proton\Files\Attachment;
|
||||||
use Rsgrinko\Proton\Files\Storage;
|
use Rsgrinko\Proton\Files\Storage;
|
||||||
use Rsgrinko\Proton\Support\Str;
|
use Rsgrinko\Proton\Support\Str;
|
||||||
|
|
||||||
@@ -27,6 +28,7 @@ final class User extends Model
|
|||||||
// Профиль сверх минимума ядра: не используются нигде, кроме самой
|
// Профиль сверх минимума ядра: не используются нигде, кроме самой
|
||||||
// карточки — свободны для своих нужд в приложении поверх фреймворка
|
// карточки — свободны для своих нужд в приложении поверх фреймворка
|
||||||
'phone', 'website', 'position', 'location', 'bio',
|
'phone', 'website', 'position', 'location', 'bio',
|
||||||
|
'theme',
|
||||||
];
|
];
|
||||||
|
|
||||||
protected array $hidden = ['password_hash'];
|
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
|
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
|
public function emailVerified(): bool
|
||||||
|
|||||||
@@ -324,9 +324,10 @@ final class View
|
|||||||
$name = trim((string) ($user->name ?: $user->login));
|
$name = trim((string) ($user->name ?: $user->login));
|
||||||
|
|
||||||
if ($user->hasAvatar()) {
|
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;
|
$url = self::route('avatar.show', ['id' => $user->id()]) . '?v=' . $version;
|
||||||
|
|
||||||
return '<img class="' . $class . '" src="' . self::e($url) . '" alt="' . self::e($name) . '">';
|
return '<img class="' . $class . '" src="' . self::e($url) . '" alt="' . self::e($name) . '">';
|
||||||
|
|||||||
@@ -0,0 +1,31 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace App\Migrations;
|
||||||
|
|
||||||
|
use Rsgrinko\Proton\Database\Migration;
|
||||||
|
use Rsgrinko\Proton\Database\Schema\Blueprint;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Тема оформления — своя у каждого, не общая настройка приложения. По
|
||||||
|
* умолчанию светлая: тёмную включают в профиле, а не угадывают по системной
|
||||||
|
* настройке браузера — так дизайн панели не расходится с тем, что показали
|
||||||
|
* при согласовании.
|
||||||
|
*/
|
||||||
|
final class AddUserTheme extends Migration
|
||||||
|
{
|
||||||
|
public function up(): void
|
||||||
|
{
|
||||||
|
$this->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');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace App\Migrations;
|
||||||
|
|
||||||
|
use Rsgrinko\Proton\Database\Migration;
|
||||||
|
use Rsgrinko\Proton\Database\Schema\Blueprint;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Аватар переезжает в attachments — как и любой другой файл к записи, а не
|
||||||
|
* отдельной парой колонок на пользователе (entity = 'avatar', entity_id —
|
||||||
|
* id пользователя). Ровно это attachments уже умеет: заводить под каждый
|
||||||
|
* новый файл профиля свою пару колонок в users незачем.
|
||||||
|
*/
|
||||||
|
final class MoveAvatarToAttachments extends Migration
|
||||||
|
{
|
||||||
|
public function up(): void
|
||||||
|
{
|
||||||
|
if (!$this->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]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -92,6 +92,14 @@ use Rsgrinko\Proton\View\View;
|
|||||||
<textarea name="bio" style="min-height: 70px;"><?= View::e((string) $user->bio) ?></textarea>
|
<textarea name="bio" style="min-height: 70px;"><?= View::e((string) $user->bio) ?></textarea>
|
||||||
</label>
|
</label>
|
||||||
|
|
||||||
|
<label>
|
||||||
|
<span>Тема оформления</span>
|
||||||
|
<select name="theme">
|
||||||
|
<option value="light" <?= $user->theme() === 'light' ? 'selected' : '' ?>>Светлая</option>
|
||||||
|
<option value="dark" <?= $user->theme() === 'dark' ? 'selected' : '' ?>>Тёмная</option>
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
|
||||||
<?php foreach ($fields as $field) { ?>
|
<?php foreach ($fields as $field) { ?>
|
||||||
<?php $name = 'meta_' . $field->id(); ?>
|
<?php $name = 'meta_' . $field->id(); ?>
|
||||||
<?php $value = $metaValues[$field->id()] ?? ''; ?>
|
<?php $value = $metaValues[$field->id()] ?? ''; ?>
|
||||||
|
|||||||
Reference in new issue
Block a user