имправление косяка с непрочитанными сообщениями в диалоге + добавил CLAUDE.md для возможности работы с агентом
This commit is contained in:
1 parent
3743db98b6
commit
7340f59033
10 files changed
+655
-8
No files matched your search
@@ -0,0 +1,176 @@
|
||||
# CLAUDE.md
|
||||
|
||||
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
|
||||
|
||||
## Project overview
|
||||
|
||||
Delta Framework — a custom, self-written PHP framework (not built on Laravel/Symfony/etc.). Code, comments, and
|
||||
commit messages are predominantly in Russian. No frontend build system (no npm/webpack) — the public site uses
|
||||
server-rendered Twig templates with a hand-written CSS design system, the admin panel uses plain PHP/jQuery pages.
|
||||
|
||||
## Commands
|
||||
|
||||
```bash
|
||||
# Install dependencies
|
||||
composer install
|
||||
|
||||
# Run all tests (as used in .gitlab-ci.yml)
|
||||
vendor/bin/phpunit --testdox tests
|
||||
|
||||
# Run a single test file / method
|
||||
vendor/bin/phpunit tests/UserTest.php
|
||||
vendor/bin/phpunit --filter testGetAllUserData tests/UserTest.php
|
||||
|
||||
# Static analysis (dev dependency, used by .github/workflows/psalm.yml)
|
||||
vendor/bin/psalm
|
||||
|
||||
# Database migrations (Phinx, config in phinx.php, migrations in db/migrations, seeds in db/seed)
|
||||
vendor/bin/phinx migrate -e dev
|
||||
vendor/bin/phinx migrate -e prod
|
||||
vendor/bin/phinx seed:run -e dev
|
||||
|
||||
# Quick syntax/render sanity check without a browser (no test harness renders Twig otherwise):
|
||||
php -l core/lib/Core/App.class.php
|
||||
php -r '$root="."; require $root."/vendor/autoload.php"; $t=new Twig\Environment(new Twig\Loader\FilesystemLoader($root."/templates"),["strict_variables"=>false]); echo $t->render("index.twig", [...]);'
|
||||
```
|
||||
|
||||
There is no local dev server script — this is a classic Apache/nginx + PHP-FPM app; `.htaccess` handles rewriting
|
||||
to `index.php`. In this project's actual dev setup, edits made on disk are synced to a live `dev.it-stories.ru`
|
||||
host automatically — that host is useful for verifying behavior end-to-end (e.g. via `curl` with a cookie jar to
|
||||
exercise session-authenticated POST flows) when something can't be confirmed from code alone.
|
||||
|
||||
## Architecture
|
||||
|
||||
### Entry points
|
||||
- `index.php` — sets `USE_ROUTER = true` and requires `core/bootstrap.php`. This is the single entry point for the
|
||||
public site (all requests are rewritten here, then dispatched by the router).
|
||||
- `core/api.php` — REST API entry point. Dispatches to `Core\Api\ApiController` methods by `$_REQUEST['method']`,
|
||||
authenticates via `$_REQUEST['token']` against `User::getByToken()`, except for methods listed in `$noAuthMethods`
|
||||
(includes `createUser`/`getToken`, so account creation and login-for-a-token both work unauthenticated).
|
||||
- `core/cron.php` — scans `core/cronTasks/*.php` (except `init.php`) and `exec()`s each one as a detached background
|
||||
PHP process. This is the mechanism for scheduled/background jobs, not a job scheduler library.
|
||||
- `admin/index.php` and siblings (`admin/users.php`, `admin/posts.php`, etc.) — the admin panel is a separate set of
|
||||
plain PHP pages (not routed through `core/routes.php`), sharing `admin/inc/bootstrap.php`, `header.php`, `footer.php`.
|
||||
AJAX handlers live in `admin/ajax/`.
|
||||
|
||||
### Bootstrap and config loading order (`core/bootstrap.php`)
|
||||
1. `vendor/autoload.php` (Composer PSR-4: `Core\` → `core/lib/`)
|
||||
2. Optional root-level `config.local.php` if present — this is the mechanism for running multiple sites/environments
|
||||
off one codebase (mount shared `/core/`, `/uploads/`, `/admin/` and override settings per site).
|
||||
3. `core/config.php` — defines all configuration as global constants, each guarded by `if (!defined(...))` so
|
||||
`config.local.php` values (defined earlier) take precedence.
|
||||
4. A second, custom `spl_autoload_register` autoloader loads any `Core\*` class from `core/lib/**/*.class.php` or
|
||||
`**/*.php` — this exists alongside the Composer PSR-4 autoloader because most classes use the `.class.php` suffix,
|
||||
which Composer's PSR-4 mapping alone won't resolve.
|
||||
5. If `CORE_FULL_LOAD` (i.e. not a cron process) and `USE_ROUTER === true`: initializes Twig
|
||||
(`PATH_TO_TEMPLATES` = `/templates`), requires `core/routes.php`, calls `Router::execute()`, then `die()`.
|
||||
|
||||
`IS_CRON_PROCESS` (if defined true before bootstrap) skips UTM tracking, cache flush/logout handling, and DDoS
|
||||
protection setup — cron tasks include `bootstrap.php` with this flag set.
|
||||
|
||||
### Routing (`core/routes.php`, `Core\Models\Router`)
|
||||
Routes are registered with `Router::route(string $pattern, $callback, bool $usePagination = false)`. `$pattern` is a
|
||||
path like `/users/(\d+)` (regex groups become positional args passed to the callback). `$callback` is either a
|
||||
`'\Core\App::method'` string or a closure. `$usePagination = true` additionally matches `/pattern/page/(\d+)`.
|
||||
`Router::execute()` matches against `parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)` (the query string is stripped
|
||||
before matching), so routes work correctly even when hit with `?foo=bar` — pagination on `/users` uses a query
|
||||
string (`?page=N`) precisely because of this. Unmatched routes fall through to whatever route is registered as
|
||||
`/404`. The default controller for site routes is `Core\App` (`core/lib/Core/App.class.php`); its private `render()`
|
||||
merges page-specific template vars with common layout vars from `getLayoutParams()` (auth state, current user +
|
||||
avatar, memory/time usage, unread messages, etc.) before handing off to Twig.
|
||||
|
||||
Route groups beyond the obvious CRUD-ish ones:
|
||||
- `/dialog/(\d+)/messages` (GET) — JSON endpoint returning a freshly rendered message-list HTML fragment + counts,
|
||||
used by both `chat.js`'s AJAX-send flow and its polling loop (see Frontend section below).
|
||||
- `/profile`, `/profile/personal`, `/profile/password`, `/profile/avatar`, `/profile/resend-verification` — the
|
||||
self-service account settings area (`App::profile*` methods), all POST-and-redirect-back-to-`/profile` with a
|
||||
one-shot flash message stored in `$_SESSION['profileMessage']`.
|
||||
|
||||
### Database layer (`Core\Database\DataBase`)
|
||||
Singleton facade (`DataBase::getInstance($driver)`) wrapping a `DatabaseDriverInterface` implementation, selected in
|
||||
the constructor via a `match` on driver name (currently only `'mysql'` → `Core\Database\Drivers\MySqlDriver`; the
|
||||
`match` structure is meant for adding other drivers under `core/lib/Core/Database/Drivers/`). The facade exposes
|
||||
`query`, `add`, `update`, `delete`, `get`, `getList`, `getCount`, and transaction methods
|
||||
(`startTransaction`/`commitTransaction`/`rollbackTransaction`), all delegating to the underlying driver. Table names
|
||||
throughout the codebase are prefixed with `DB_TABLE_PREFIX` (e.g. `Core\Models\MQ::TABLE = DB_TABLE_PREFIX . 'threads'`).
|
||||
|
||||
`MySqlDriver::update()`/`delete()` always return `false` in practice (they infer success from `fetchAll()` on a
|
||||
non-SELECT statement, which is always empty) — don't branch on `DataBase::update()`'s return value; a thrown
|
||||
`DatabaseException` is the only reliable failure signal. Known dormant bug: `User::update()`'s cache invalidation
|
||||
key doesn't match the keys `User::getAllUserData()` actually caches under (it's missing the `onlySecureData` flag
|
||||
component), so cached user data is never properly invalidated on write — currently harmless because `USE_CACHE` is
|
||||
off by default, but will surface stale data (stale password/email/etc. via `getLogin()`/`getEmail()`/`getAllUserData()`)
|
||||
if caching is ever turned on. Fix by aligning the cache key format in `update()` with `getAllUserData()`'s.
|
||||
|
||||
### Models (`core/lib/Core/Models/`)
|
||||
Plain classes (not an ORM) wrapping `DataBase` calls per feature area:
|
||||
- `User`/`UserModel`/`UserMeta` — auth, profile, presence. `isOnline($id)`/`getOnlineCount()` compute presence from
|
||||
`last_active` + `USER_ONLINE_TIME`; `last_active` is only ever refreshed as a side effect of `isAuthorized()`
|
||||
(both its cookie- and session-based branches). `changePassword()`/`changeEmail()` are the self-service versions
|
||||
used by `/profile` (as opposed to `resetPassword()`, which force-generates and emails a random password). **Gotcha:**
|
||||
`changePassword()` must refresh `$_SESSION['password']` after a successful change, or the very next request's
|
||||
`isAuthorized()` session-consistency check (which compares a double-hash of the current DB password against the
|
||||
hash captured at login) will silently log the user out — this is exactly the kind of bug that looks like "wrong
|
||||
current password" on the *next* attempt when it isn't.
|
||||
- `Dialog` — private messages; `getLastMessage($dialogId)` backs the inbox-style previews in the dialogs list.
|
||||
- `Posts`, `Roles`, `File`, `UTM` (marketing tag capture, runs on every full-load request), and `MQ`/`MQResponse` (a
|
||||
DB-backed message-queue/task-runner used by the admin "Менеджер очереди" panel and by `MQTasks.class.php`).
|
||||
- `Core\DataObjects\AbstractModel`/`AbstractCollection`/`ModelCollection` provide a lightweight base for
|
||||
model/collection behavior used by newer models.
|
||||
|
||||
### Frontend (`templates/`, `assets/`)
|
||||
Server-rendered Twig, one shared layout, no client-side framework or build step.
|
||||
- `templates/layout.twig` is the page shell: a centered "card" (`.shell`) with a gradient header/footer and an icon
|
||||
nav, floating on a plain page background — not a full-bleed app chrome. Every page renders inside `.shell-content`.
|
||||
- `templates/_icons.twig` holds every icon as a Twig macro emitting inline SVG (no icon font, no CDN). **Import it
|
||||
per-template** — `{% import '_icons.twig' as icons %}` at the top of *each* template that uses `icons.xxx()`, since
|
||||
Twig imports are not inherited from the parent template through `{% extends %}`.
|
||||
- `assets/css/style.css` is a single hand-written stylesheet using CSS custom properties (`:root` design tokens:
|
||||
colors, radii, shadows, the `--gradient-brand` used everywhere for primary accents). Reusable component classes:
|
||||
`.page-head` (page title + icon), `.section`/`.section-title` (content grouping — deliberately *not* its own
|
||||
bordered box, to avoid a "card inside a card" look now that `.shell` already frames the page), `.info-list` /
|
||||
`.meta-grid` (key/value display), `.status` + `.avatar-wrap`/`.avatar-status-dot` (online/offline presence dot
|
||||
overlaid on an avatar), `.pill`/`.nav-badge` (counts), `.dialog-list`/`.dialog-row` (messenger-style inbox rows).
|
||||
When adding a new panel-like UI element, avoid giving it its own `border`/`box-shadow` if it already lives inside
|
||||
`.shell-content` — that's the recurring mistake that produces the nested-window look.
|
||||
- Dialogs/chat (`dialog.twig`, `dialogs.twig`, `templates/_messageList.twig`, `assets/js/chat.js`): the message-list
|
||||
markup (grouping consecutive messages from the same sender, day separators, per-type rendering for
|
||||
text/image/file) lives in exactly one place, `_messageList.twig`, which is rendered both for the normal full-page
|
||||
load and, standalone, by `App::outputDialogJson()` for AJAX responses — keep it that way rather than duplicating
|
||||
render logic in JS. `chat.js` handles AJAX send (`FormData`, no full-page reload), textarea auto-resize,
|
||||
Enter-to-send (Shift+Enter for newline), and polls `/dialog/(\d+)/messages` every few seconds for new messages,
|
||||
only re-scrolling to bottom if the user was already scrolled near the bottom.
|
||||
- Avatars: `File`-backed images are optional per user — every place that renders an avatar (nav, dialogs list, chat
|
||||
header, profile) must handle the "no `image_id`" case by falling back to an initial-letter badge; see any existing
|
||||
`{% if x.avatar %}...{% else %}...{% endif %}` block for the pattern (and use `name|default(login)`, not
|
||||
`nameForDisplay`, for the initial — the latter is a formatted `"[id] (login) name"` string).
|
||||
|
||||
### Helpers (`core/lib/Core/Helpers/`)
|
||||
Cross-cutting utilities: `Cache` (file-backed, gated by `USE_CACHE`/`CACHE_DIR`/`CACHE_TTL`, initialized once in
|
||||
bootstrap), `Log`, `Mail`, `Captcha`, `DDosProtection` (basic rate limiting per `USE_DDOS_PROTECTION`), `Registry`
|
||||
(simple static key/value store used e.g. to stash the current route callback), `Sanitize`, `Files`, `Thumbs`, `Zip`,
|
||||
`SystemFunctions`, `Pagination` (`execute()`/`getLimit()` compute the SQL `LIMIT` offset; `getPage()`/`getTotalPages()`
|
||||
getters exist for rendering prev/next controls — call `execute()` before either getter).
|
||||
|
||||
### External services (`core/lib/Core/ExternalServices/`)
|
||||
Thin clients for Telegram (`Telegram`, `Telegram2`, `TelegramSender`, `TelegramActions` — note there are parallel/
|
||||
legacy variants, check which is actually wired up before extending), `ChatGPT`, `RemoteHosts`, and an HTTP
|
||||
`Request`/`RequestOLD` pair (prefer `Request/` over the OLD variant for new code).
|
||||
|
||||
### Configuration constants
|
||||
`core/config.php` defines all runtime configuration as global constants (`DB_HOST`, `CACHE_*`, `TELEGRAM_*`,
|
||||
`USE_CAPTCHA`, `USE_DDOS_PROTECTION`, `CRYPTO_KEY`, etc.), each wrapped in `if (!defined(...))` so a `config.local.php`
|
||||
at the project root can override any subset before `core/config.php` runs. `Core\SystemConfig::getValue($name)` is a
|
||||
thin `constant()` wrapper used where a config value needs to be fetched dynamically by name rather than referenced
|
||||
directly. Note: this repo currently has real-looking secrets (DB password, Telegram bot token, crypto key) committed
|
||||
directly in `core/config.php` and `phinx.php` — don't add more secrets this way; if touching this area, prefer
|
||||
environment-driven config and flag the existing hardcoded values rather than propagating the pattern.
|
||||
|
||||
### Testing
|
||||
PHPUnit tests live in `tests/` (currently minimal — see `tests/UserTest.php`). CI (`.gitlab-ci.yml`) runs
|
||||
`./vendor/bin/phpunit --testdox tests` on every push; a separate GitHub Actions workflow
|
||||
(`.github/workflows/psalm.yml`) runs Psalm's security scan on `main` and PRs into it. There's no automated test
|
||||
coverage for routes/templates — when changing `App.class.php` controllers or Twig templates, sanity-check with
|
||||
`php -l` plus a throwaway Twig render (see Commands above) before considering the change done, and prefer verifying
|
||||
session-dependent flows (login, password change, AJAX endpoints) against the live `dev.it-stories.ru` sync target
|
||||
with `curl` and a cookie jar rather than guessing from code alone.
|
||||
@@ -217,6 +217,21 @@ a {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.nav-profile-link {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 6px 10px 6px 6px;
|
||||
border-radius: 999px;
|
||||
text-decoration: none;
|
||||
transition: background var(--transition);
|
||||
}
|
||||
|
||||
.nav-profile-link:hover,
|
||||
.nav-profile-link.active {
|
||||
background: rgba(255, 255, 255, 0.14);
|
||||
}
|
||||
|
||||
.user-avatar {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
@@ -1024,6 +1039,28 @@ textarea:focus,
|
||||
margin-top: 8px;
|
||||
}
|
||||
|
||||
.profile-avatar-form {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 20px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.profile-avatar-controls {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.confirm-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
flex-wrap: wrap;
|
||||
margin: -6px 0 14px;
|
||||
}
|
||||
|
||||
.info-list {
|
||||
display: grid;
|
||||
grid-template-columns: 190px 1fr;
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
$(document).ready(function () {
|
||||
let $panel = $('#chatPanel');
|
||||
if ($panel.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
let dialogId = $panel.data('dialog-id'),
|
||||
$messageBox = $('#messageBox'),
|
||||
$form = $('#chatComposeForm'),
|
||||
$textarea = $('#chatMessageInput'),
|
||||
$fileInput = $('#chatFileInput'),
|
||||
$fileLabel = $('#chatFileLabel'),
|
||||
$fileLabelDefault = $fileLabel.html(),
|
||||
$sendButton = $('#chatSendButton'),
|
||||
$sendButtonDefault = $sendButton.html(),
|
||||
$companionStatus = $('#companionStatus'),
|
||||
$companionStatusText = $('#companionStatusText'),
|
||||
$messagesCountText = $('#messagesCountText'),
|
||||
pollTimer = null;
|
||||
|
||||
function isNearBottom() {
|
||||
return $messageBox[0].scrollHeight - $messageBox.scrollTop() - $messageBox.outerHeight() < 80;
|
||||
}
|
||||
|
||||
function scrollToBottom() {
|
||||
$messageBox.scrollTop($messageBox[0].scrollHeight);
|
||||
}
|
||||
|
||||
function resizeTextarea() {
|
||||
$textarea.css('height', 'auto');
|
||||
$textarea.css('height', Math.min($textarea[0].scrollHeight, 200) + 'px');
|
||||
}
|
||||
|
||||
function applyDialogState(data) {
|
||||
$panel.attr('data-messages-count', data.messagesCount);
|
||||
$messagesCountText.text(data.messagesCount);
|
||||
$companionStatus.toggleClass('is-online', !!data.companionOnline);
|
||||
$companionStatusText.text(data.companionOnline ? 'Онлайн' : 'Не в сети');
|
||||
}
|
||||
|
||||
// Первичный скролл к последнему сообщению
|
||||
scrollToBottom();
|
||||
|
||||
// Автоувеличение textarea
|
||||
$textarea.on('input', resizeTextarea);
|
||||
resizeTextarea();
|
||||
|
||||
// Отправка по Enter, перенос строки по Shift+Enter
|
||||
$textarea.on('keydown', function (e) {
|
||||
if (e.key === 'Enter' && !e.shiftKey) {
|
||||
e.preventDefault();
|
||||
$form.trigger('submit');
|
||||
}
|
||||
});
|
||||
|
||||
// Отправка формы через AJAX, без перезагрузки страницы
|
||||
$form.on('submit', function (e) {
|
||||
e.preventDefault();
|
||||
|
||||
if ($sendButton.prop('disabled')) {
|
||||
return;
|
||||
}
|
||||
|
||||
let hasMessage = $textarea.val().trim().length > 0,
|
||||
hasFile = $fileInput[0].files.length > 0;
|
||||
|
||||
if (!hasMessage && !hasFile) {
|
||||
return;
|
||||
}
|
||||
|
||||
let formData = new FormData($form[0]);
|
||||
$sendButton.prop('disabled', true).html('Отправка...');
|
||||
|
||||
$.ajax({
|
||||
url: $form.attr('action'),
|
||||
method: 'POST',
|
||||
data: formData,
|
||||
processData: false,
|
||||
contentType: false,
|
||||
headers: {'X-Requested-With': 'XMLHttpRequest'},
|
||||
dataType: 'json'
|
||||
}).done(function (data) {
|
||||
if (data && data.success) {
|
||||
$messageBox.html(data.html);
|
||||
applyDialogState(data);
|
||||
scrollToBottom();
|
||||
$textarea.val('');
|
||||
resizeTextarea();
|
||||
$fileInput.val('');
|
||||
$fileLabel.html($fileLabelDefault);
|
||||
}
|
||||
}).always(function () {
|
||||
$sendButton.prop('disabled', false).html($sendButtonDefault);
|
||||
$textarea.trigger('focus');
|
||||
});
|
||||
});
|
||||
|
||||
// Периодический опрос новых сообщений
|
||||
pollTimer = setInterval(function () {
|
||||
let currentCount = parseInt($panel.attr('data-messages-count'), 10);
|
||||
let wasNearBottom = isNearBottom();
|
||||
|
||||
$.getJSON('/dialog/' + dialogId + '/messages').done(function (data) {
|
||||
if (!data || !data.success) {
|
||||
return;
|
||||
}
|
||||
applyDialogState(data);
|
||||
if (data.messagesCount !== currentCount) {
|
||||
$messageBox.html(data.html);
|
||||
if (wasNearBottom) {
|
||||
scrollToBottom();
|
||||
}
|
||||
}
|
||||
});
|
||||
}, 6000);
|
||||
|
||||
$(window).on('beforeunload', function () {
|
||||
if (pollTimer) {
|
||||
clearInterval(pollTimer);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -59,6 +59,7 @@
|
||||
'isAuthorized' => User::isAuthorized(),
|
||||
'isAdmin' => User::isAuthorized() && $USER->isAdmin(),
|
||||
'userData' => User::isAuthorized() ? $USER->getAllUserData(true) : [],
|
||||
'userAvatar' => User::isAuthorized() ? $USER->getImage() : null,
|
||||
'currentYear' => date('Y'),
|
||||
'newMessages' => User::isAuthorized() ? $USER->getDialogObject()->getUnviewedMessagesCount() : 0,
|
||||
];
|
||||
@@ -348,4 +349,143 @@
|
||||
}
|
||||
header('Location: /dialog/' . $dialogId);
|
||||
}
|
||||
|
||||
public static function profile()
|
||||
{
|
||||
/** @var User $USER */
|
||||
global $USER;
|
||||
if (empty($USER)) {
|
||||
header('Location: /login');
|
||||
return;
|
||||
}
|
||||
|
||||
$message = $_SESSION['profileMessage'] ?? null;
|
||||
unset($_SESSION['profileMessage']);
|
||||
|
||||
self::render('profile.twig', [
|
||||
'profileData' => $USER->getAllUserData(true),
|
||||
'roles' => $USER->getRolesObject()->getFullRoles(),
|
||||
'avatar' => $USER->getImage(),
|
||||
'emailConfirmed' => $USER->isEmailConfirmed(),
|
||||
'message' => $message,
|
||||
]);
|
||||
}
|
||||
|
||||
public static function profileUpdatePersonal()
|
||||
{
|
||||
/** @var User $USER */
|
||||
global $USER;
|
||||
if (empty($USER)) {
|
||||
header('Location: /login');
|
||||
return;
|
||||
}
|
||||
|
||||
$name = trim((string)($_REQUEST['name'] ?? ''));
|
||||
$email = trim((string)($_REQUEST['email'] ?? ''));
|
||||
|
||||
try {
|
||||
if ($name !== '') {
|
||||
$USER->update(['name' => $name]);
|
||||
}
|
||||
if ($email !== '' && $email !== $USER->getEmail()) {
|
||||
$USER->changeEmail($email);
|
||||
self::setProfileMessage('success', 'Данные обновлены. На новый E-Mail отправлен код подтверждения.');
|
||||
} else {
|
||||
self::setProfileMessage('success', 'Данные успешно обновлены.');
|
||||
}
|
||||
} catch (CoreException $e) {
|
||||
self::setProfileMessage('error', $e->getMessage());
|
||||
}
|
||||
|
||||
header('Location: /profile');
|
||||
}
|
||||
|
||||
public static function profileUpdatePassword()
|
||||
{
|
||||
/** @var User $USER */
|
||||
global $USER;
|
||||
if (empty($USER)) {
|
||||
header('Location: /login');
|
||||
return;
|
||||
}
|
||||
|
||||
$currentPassword = (string)($_REQUEST['currentPassword'] ?? '');
|
||||
$newPassword = (string)($_REQUEST['newPassword'] ?? '');
|
||||
$confirmPassword = (string)($_REQUEST['confirmPassword'] ?? '');
|
||||
|
||||
if ($newPassword === '' || $newPassword !== $confirmPassword) {
|
||||
self::setProfileMessage('error', 'Новый пароль пуст или не совпадает с подтверждением.');
|
||||
} elseif (!$USER->changePassword($currentPassword, $newPassword)) {
|
||||
self::setProfileMessage('error', 'Текущий пароль указан неверно.');
|
||||
} else {
|
||||
self::setProfileMessage('success', 'Пароль успешно изменён.');
|
||||
}
|
||||
|
||||
header('Location: /profile');
|
||||
}
|
||||
|
||||
public static function profileUpdateAvatar()
|
||||
{
|
||||
/** @var User $USER */
|
||||
global $USER;
|
||||
if (empty($USER)) {
|
||||
header('Location: /login');
|
||||
return;
|
||||
}
|
||||
|
||||
if (empty($_FILES['avatar']['tmp_name'])) {
|
||||
self::setProfileMessage('error', 'Файл не выбран.');
|
||||
header('Location: /profile');
|
||||
return;
|
||||
}
|
||||
|
||||
if (!in_array($_FILES['avatar']['type'], ['image/jpeg', 'image/png', 'image/gif', 'image/webp'], true)) {
|
||||
self::setProfileMessage('error', 'Аватар должен быть изображением (JPEG, PNG, GIF или WEBP).');
|
||||
header('Location: /profile');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
$fileObject = new File();
|
||||
$fileObject->saveFile($_FILES['avatar']['tmp_name'], $_FILES['avatar']['name'], true);
|
||||
$USER->update(['image_id' => $fileObject->getId()]);
|
||||
self::setProfileMessage('success', 'Аватар обновлён.');
|
||||
} catch (CoreException $e) {
|
||||
self::setProfileMessage('error', 'Не удалось загрузить файл.');
|
||||
}
|
||||
|
||||
header('Location: /profile');
|
||||
}
|
||||
|
||||
public static function profileResendVerification()
|
||||
{
|
||||
/** @var User $USER */
|
||||
global $USER;
|
||||
if (empty($USER)) {
|
||||
header('Location: /login');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
$USER->sendVerificationCode();
|
||||
self::setProfileMessage('success', 'Письмо с кодом подтверждения отправлено повторно.');
|
||||
} catch (CoreException $e) {
|
||||
self::setProfileMessage('error', 'Не удалось отправить письмо подтверждения.');
|
||||
}
|
||||
|
||||
header('Location: /profile');
|
||||
}
|
||||
|
||||
/**
|
||||
* Сохранение сообщения для отображения на странице личного кабинета
|
||||
*
|
||||
* @param string $type Тип сообщения (success|error)
|
||||
* @param string $text Текст сообщения
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private static function setProfileMessage(string $type, string $text): void
|
||||
{
|
||||
$_SESSION['profileMessage'] = ['type' => $type, 'text' => $text];
|
||||
}
|
||||
}
|
||||
@@ -65,12 +65,9 @@
|
||||
private function markDialogViewed(int $dialogId): void
|
||||
{
|
||||
/** @var $DB DataBase Объект базы данных */
|
||||
$DB = DataBase::getInstance();
|
||||
$dialogData = $DB->get(self::TABLE_DIALOGS, ['id' => $dialogId]);
|
||||
if ($this->user->getId() === (int)$dialogData['receive']) {
|
||||
$DB->update(self::TABLE_DIALOGS, ['id' => $dialogId], ['viewed' => CODE_VALUE_Y]);
|
||||
$DB->update(self::TABLE_MESSAGES, ['dialog_id' => $dialogId, 'user_to' => $this->user->getId(), 'viewed' => CODE_VALUE_N], ['viewed' => CODE_VALUE_Y]);
|
||||
}
|
||||
$DB = DataBase::getInstance();
|
||||
$DB->update(self::TABLE_DIALOGS, ['id' => $dialogId], ['viewed' => CODE_VALUE_Y]);
|
||||
$DB->update(self::TABLE_MESSAGES, ['dialog_id' => $dialogId, 'user_to' => $this->user->getId(), 'viewed' => CODE_VALUE_N], ['viewed' => CODE_VALUE_Y]);
|
||||
}
|
||||
|
||||
public function createDialog(int $userId): ?int
|
||||
|
||||
@@ -889,6 +889,62 @@
|
||||
)->setTemplateVars(['TITLE' => 'Подтверждение E-Mail'])->send()[0];
|
||||
}
|
||||
|
||||
/**
|
||||
* Смена пароля пользователем (с проверкой текущего пароля)
|
||||
*
|
||||
* @param string $currentPassword Текущий пароль
|
||||
* @param string $newPassword Новый пароль
|
||||
*
|
||||
* @return bool
|
||||
* @throws CoreException
|
||||
*/
|
||||
public function changePassword(string $currentPassword, string $newPassword): bool
|
||||
{
|
||||
$currentData = $this->getAllUserData();
|
||||
if ($currentData['password'] !== self::passwordEncryption($currentPassword)) {
|
||||
return false;
|
||||
}
|
||||
$this->update(['password' => self::passwordEncryption($newPassword)]);
|
||||
Log::logToFile('Пользователь сменил пароль', 'User.log', ['userId' => $this->id]);
|
||||
|
||||
// Обновляем хеш пароля, сохранённый в сессии при авторизации, иначе isAuthorized()
|
||||
// разлогинит пользователя на следующем же запросе, так как пароль в БД уже другой
|
||||
if (isset($_SESSION['id']) && (int)$_SESSION['id'] === $this->id) {
|
||||
$_SESSION['password'] = self::passwordEncryption(self::passwordEncryption($newPassword));
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Смена E-Mail пользователем (с обязательной повторной верификацией)
|
||||
*
|
||||
* @param string $newEmail Новый E-Mail
|
||||
*
|
||||
* @return bool
|
||||
* @throws CoreException
|
||||
*/
|
||||
public function changeEmail(string $newEmail): bool
|
||||
{
|
||||
$newEmail = Sanitize::sanitizeEmail($newEmail);
|
||||
if ($newEmail === $this->getEmail()) {
|
||||
return true;
|
||||
}
|
||||
if (self::isUserExistsByParams(['email' => $newEmail])) {
|
||||
throw new CoreException('Пользователь с данным E-Mail уже существует', CoreException::ERROR_CREATE_USER);
|
||||
}
|
||||
|
||||
$verificationCode = md5(self::$cryptoSalt . $newEmail . $this->getLogin() . time());
|
||||
$this->update([
|
||||
'email' => $newEmail,
|
||||
'email_confirmed' => CODE_VALUE_N,
|
||||
'verification_code' => $verificationCode,
|
||||
]);
|
||||
Log::logToFile('Пользователь сменил E-Mail', 'User.log', ['userId' => $this->id, 'newEmail' => $newEmail]);
|
||||
$this->sendVerificationCode();
|
||||
return true;
|
||||
}
|
||||
|
||||
public function resetPassword(): bool
|
||||
{
|
||||
$newPassword = SystemFunctions::generatePassword();
|
||||
|
||||
@@ -44,6 +44,12 @@
|
||||
Router::route('/users/(\d+)/sendMessage', '\Core\App::sendMessage');
|
||||
Router::route('/users/(\d+)/dialog', '\Core\App::goToDialog');
|
||||
|
||||
Router::route('/profile', '\Core\App::profile');
|
||||
Router::route('/profile/personal', '\Core\App::profileUpdatePersonal');
|
||||
Router::route('/profile/password', '\Core\App::profileUpdatePassword');
|
||||
Router::route('/profile/avatar', '\Core\App::profileUpdateAvatar');
|
||||
Router::route('/profile/resend-verification', '\Core\App::profileResendVerification');
|
||||
|
||||
|
||||
Router::route('/test', '\Core\App::test', true);
|
||||
Router::route('/test/(\d+)', '\Core\App::test');
|
||||
|
||||
@@ -43,3 +43,9 @@
|
||||
{% macro arrowRight(class) %}{{ _self.base('<path d="M5 12h14"/><path d="M13 6l6 6-6 6"/>', class) }}{% endmacro %}
|
||||
|
||||
{% macro user(class) %}{{ _self.base('<circle cx="12" cy="8" r="3.4"/><path d="M6 19c0-3.3 2.7-5.5 6-5.5s6 2.2 6 5.5"/>', class) }}{% endmacro %}
|
||||
|
||||
{% macro sliders(class) %}{{ _self.base('<line x1="4" y1="6" x2="20" y2="6"/><circle cx="9" cy="6" r="2" fill="currentColor" stroke="none"/><line x1="4" y1="12" x2="20" y2="12"/><circle cx="15" cy="12" r="2" fill="currentColor" stroke="none"/><line x1="4" y1="18" x2="20" y2="18"/><circle cx="11" cy="18" r="2" fill="currentColor" stroke="none"/>', class) }}{% endmacro %}
|
||||
|
||||
{% macro lock(class) %}{{ _self.base('<rect x="5" y="11" width="14" height="9" rx="2"/><path d="M8 11V8a4 4 0 0 1 8 0v3"/>', class) }}{% endmacro %}
|
||||
|
||||
{% macro camera(class) %}{{ _self.base('<path d="M4 8h3l1.5-2h7L17 8h3a1 1 0 0 1 1 1v9a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V9a1 1 0 0 1 1-1z"/><circle cx="12" cy="13" r="3.3"/>', class) }}{% endmacro %}
|
||||
+10
-2
@@ -39,8 +39,16 @@
|
||||
|
||||
<div class="nav-user">
|
||||
{% if isAuthorized %}
|
||||
<span class="user-avatar">{{ (userData.name|default(userData.login|default('U')))|slice(0, 1)|upper }}</span>
|
||||
<span class="user-name">{{ userData.name }}</span>
|
||||
<a class="nav-profile-link {% if currentPage == 'profile' %}active{% endif %}" href="/profile" title="Личный кабинет">
|
||||
<span class="user-avatar">
|
||||
{% if userAvatar %}
|
||||
<img src="{{ userAvatar.path }}" alt="{{ userData.name }}">
|
||||
{% else %}
|
||||
{{ (userData.name|default(userData.login|default('U')))|slice(0, 1)|upper }}
|
||||
{% endif %}
|
||||
</span>
|
||||
<span class="user-name">{{ userData.name }}</span>
|
||||
</a>
|
||||
<a class="nav-link nav-link-icon" href="/logout" title="Выход">{{ icons.logout() }}</a>
|
||||
{% else %}
|
||||
<a class="nav-link nav-link-guest" href="/login">{{ icons.login() }}<span>Войти</span></a>
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
{% extends 'layout.twig' %}
|
||||
{% import '_icons.twig' as icons %}
|
||||
{% block title %}Личный кабинет{% endblock %}
|
||||
{% block main %}
|
||||
<div class="page-head">
|
||||
<div class="page-head-icon">{{ icons.sliders() }}</div>
|
||||
<div>
|
||||
<h1>Личный кабинет</h1>
|
||||
<p class="page-subtitle">Управление профилем, аватаром и безопасностью аккаунта</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{% if message %}
|
||||
<div class="alert {% if message.type == 'success' %}alert-success{% else %}alert-error{% endif %}">
|
||||
{{ message.type == 'success' ? icons.check() : icons.warning() }}
|
||||
<span>{{ message.text }}</span>
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
<div class="section">
|
||||
<div class="section-title">
|
||||
<h2>{{ icons.camera() }} Аватар</h2>
|
||||
</div>
|
||||
<form method="POST" action="/profile/avatar" enctype="multipart/form-data" class="profile-avatar-form">
|
||||
<div class="profile-hero-avatar">
|
||||
{% if avatar %}
|
||||
<img src="{{ avatar.path }}" alt="{{ profileData.name }}">
|
||||
{% else %}
|
||||
{{ (profileData.name|default(profileData.login))|slice(0, 1)|upper }}
|
||||
{% endif %}
|
||||
</div>
|
||||
<div class="profile-avatar-controls">
|
||||
<label class="input-file">
|
||||
<input type="file" name="avatar" accept="image/jpeg,image/png,image/gif,image/webp">
|
||||
<span>{{ icons.camera() }} Выбрать файл</span>
|
||||
</label>
|
||||
<button class="button" type="submit">Загрузить</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<div class="section">
|
||||
<div class="section-title">
|
||||
<h2>{{ icons.user() }} Личные данные</h2>
|
||||
</div>
|
||||
<form method="POST" action="/profile/personal">
|
||||
<input class="input" type="text" name="name" value="{{ profileData.name }}" placeholder="Имя">
|
||||
<input class="input" type="email" name="email" value="{{ profileData.email }}" placeholder="E-Mail">
|
||||
|
||||
<div class="confirm-row">
|
||||
{% if emailConfirmed %}
|
||||
<span class="confirm-badge is-yes">{{ icons.check() }} E-Mail подтверждён</span>
|
||||
{% else %}
|
||||
<span class="confirm-badge is-no">{{ icons.warning() }} E-Mail не подтверждён</span>
|
||||
<button class="button button-ghost" type="submit" form="resendVerificationForm">Отправить код повторно</button>
|
||||
{% endif %}
|
||||
</div>
|
||||
|
||||
<button class="button" type="submit">Сохранить</button>
|
||||
</form>
|
||||
{% if not emailConfirmed %}
|
||||
<form method="POST" action="/profile/resend-verification" id="resendVerificationForm"></form>
|
||||
{% endif %}
|
||||
</div>
|
||||
|
||||
<div class="section">
|
||||
<div class="section-title">
|
||||
<h2>{{ icons.lock() }} Смена пароля</h2>
|
||||
</div>
|
||||
<form method="POST" action="/profile/password">
|
||||
<input class="input" type="password" name="currentPassword" placeholder="Текущий пароль" autocomplete="current-password">
|
||||
<input class="input" type="password" name="newPassword" placeholder="Новый пароль" autocomplete="new-password">
|
||||
<input class="input" type="password" name="confirmPassword" placeholder="Повторите новый пароль" autocomplete="new-password">
|
||||
<button class="button" type="submit">Сменить пароль</button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<div class="section">
|
||||
<div class="section-title">
|
||||
<h2>{{ icons.info() }} Информация об аккаунте</h2>
|
||||
</div>
|
||||
<dl class="info-list">
|
||||
<dt>{{ icons.hash() }} ID</dt>
|
||||
<dd>{{ profileData.id }}</dd>
|
||||
<dt>{{ icons.user() }} Логин</dt>
|
||||
<dd>{{ profileData.login }}</dd>
|
||||
<dt>{{ icons.clock() }} Регистрация</dt>
|
||||
<dd>{{ profileData.date_created }}</dd>
|
||||
<dt>{{ icons.shield() }} Роли</dt>
|
||||
<dd>
|
||||
{% for role in roles %}
|
||||
<span class="role-badge">{{ role.name }}</span>
|
||||
{% else %}
|
||||
—
|
||||
{% endfor %}
|
||||
</dd>
|
||||
</dl>
|
||||
</div>
|
||||
{% endblock %}
|
||||
Reference in new issue
Block a user