имправление косяка с непрочитанными сообщениями в диалоге + добавил CLAUDE.md для возможности работы с агентом
This commit is contained in:
1 parent
3743db98b6
commit
7340f59033
10 files changed
+655
-8
No files matched your search
@@ -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');
|
||||
|
||||
Reference in new issue
Block a user