[+] добавил самописный шаблон фронта

[-] удалил ошметки старого шаблона фронта
This commit is contained in:
rsgrinko committed 2023-07-24 16:51:44 +03:00
1 parent 95a3ff5b36
commit b66f3e28d0
115 files changed
+820 -17126

No files matched your search

+67 -21
View File
@@ -21,9 +21,6 @@
namespace Core;
use Core\DataBases\DB;
use Core\Helpers\Cache;
use Core\Helpers\Files;
use Core\Helpers\SystemFunctions;
use Core\Models\{Posts, User};
@@ -39,29 +36,78 @@
public static function index()
{
global $twig, $USER;
$finish_time = microtime(true);
$delta = round($finish_time - START_TIME, 3);
if ($delta < 0.001) {
$delta = 0.001;
}
echo $twig->render(
'index.twig',
[
'isAuthorized' => User::isAuthorized(),
'isAdmin' => User::isAuthorized() && $USER->isAdmin(),
'userDataTable' => User::isAuthorized() ? str_replace(
'<table style="',
'<table style="width:100%;',
SystemFunctions::arrayToTable($USER->getAllUserData(), 'Информация о текущем пользователе')
) : '',
'statString' => 'Использовано ОЗУ: '
. round(memory_get_usage() / 1024 / 1024, 2) . ' МБ / БД: '
. round(DB::$workingTime,3) . ' сек (' . DB::$quantity . ' шт.) / Кэш: '
. Files::convertBytes(Cache::getCacheSize())
. ' / Генерация: ' . $delta . ' сек',
]
]
);
}
/**
* Информация о сборке
* я
* @return void
* @throws CoreException
*/
public static function info()
{
global $twig, $USER;
$buildInfo = [
'Версия ядра' => CORE_VERSION,
'Лимит пагинации' => PAGINATION_LIMIT,
'Время для расчета онлайна' => USER_ONLINE_TIME,
'Время жизни кеша' => CACHE_TTL,
'E-Mail сайта' => SERVER_EMAIL,
'Имя отправителя сайта' => SERVER_EMAIL_NAME,
];
echo $twig->render(
'info.twig',
[
'isAuthorized' => User::isAuthorized(),
'isAdmin' => User::isAuthorized() && $USER->isAdmin(),
'data' => $buildInfo,
]
);
}
/**
* Отрисовка диалогов
*
* @return void
* @throws CoreException
*/
public static function dialogs()
{
global $twig, $USER;
echo $twig->render(
'dialogs.twig',
[
'isAuthorized' => User::isAuthorized(),
'isAdmin' => User::isAuthorized() && $USER->isAdmin(),
'dialogs' => $USER->getDialogs(),
]
);
}
/**
* Отрисовка диалога
*
* @return void
* @throws CoreException
*/
public static function dialog(int $id)
{
global $twig, $USER;
echo $twig->render(
'dialog.twig',
[
'isAuthorized' => User::isAuthorized(),
'isAdmin' => User::isAuthorized() && $USER->isAdmin(),
'messages' => $USER->getMessages($id, true),
'userId' => $USER->getId(),
]
);
}
+126
View File
@@ -0,0 +1,126 @@
<?php
namespace Core\Models;
use Core\CoreException;
use Core\DataBases\DB;
use Core\Helpers\Cache;
class Dialog
{
/** @var string Таблица с диалогами */
const TABLE_DIALOGS = DB_TABLE_PREFIX . 'dialogs';
/** @var string Таблица с сообщениями */
const TABLE_MESSAGES = DB_TABLE_PREFIX . 'messages';
/**
* @var User $user Объект пользователя
*/
private User $user;
public function __construct(User $user)
{
$this->user = $user;
}
/**
* Получение идентификатора диалога
*
* @param int $userOne Пользователь 1
* @param int $userTwo Пользователь 2
*
* @return int|null
* @throws CoreException
*/
private static function getDialogId(int $userOne, int $userTwo): ?int
{
$DB = DB::getInstance();
$dialogId = $DB->query(
'SELECT `id` FROM ' . self::TABLE_DIALOGS
. ' WHERE (`send`="' . $userOne . '" and `receive`="' . $userTwo
. '") OR (`send`="' . $userTwo . '" and `receive`="' . $userOne . '")'
);
if (!$dialogId) {
return null;
}
return (int)$dialogId[0]['id'];
}
/**
* Пометить диалог прочитанным
*
* @return void
* @throws CoreException
*/
private static function markDialogViewed(int $dialogId): void
{
$DB = DB::getInstance();
$dialogId = $DB->update(self::TABLE_DIALOGS, ['id' => $dialogId], ['viewed' => CODE_VALUE_Y]);
}
/**
* Получение диалогов
*
* @return array
* @throws CoreException
*/
public function getDialogs(): array
{
/** @var $DB DB Объект базы данных */
$DB = DB::getInstance();
$dialogs = $DB->query(
'SELECT * FROM ' . self::TABLE_DIALOGS . ' WHERE `send`="' . $this->user->getId() . '" OR `receive`="' . $this->user->getId() . '"'
);
if (empty($dialogs)) {
return [];
}
return $dialogs;
}
/**
* Получение сообщений диалога
*
* @param int $dialogId
*
* @return array
* @throws CoreException
*/
public function getMessages(int $dialogId, bool $markDialogViewed = false): array
{
/** @var $DB DB Объект базы данных */
$DB = DB::getInstance();
$messages = $DB->query('SELECT * FROM ' . self::TABLE_MESSAGES . ' WHERE `dialog_id`="' . $dialogId . '"');
if ($markDialogViewed) {
self::markDialogViewed($dialogId);
}
if (empty($messages)) {
return [];
}
return $messages;
}
/**
* Отправка сообщения
*
* @throws CoreException
*/
public function sendMessage(int $to, string $message)
{
if (!User::isUserExistsByParams(['id' => $to])) {
throw new CoreException('Пользователь с идентификатором ' . $to . ' отсутствует в базе', CoreException::ERROR_USER_NOT_FOUND);
}
/** @var $DB DB Объект базы данных */
$DB = DB::getInstance();
$dialogId = self::getDialogId($this->user->getId(), $to);
if (empty($dialogId)) {
$dialogId = $DB->addItem(self::TABLE_DIALOGS, ['viewed'=> CODE_VALUE_N, 'send' => $this->user->getId(), 'receive' => $to]);
} else {
$DB->update(self::TABLE_DIALOGS, ['id' => $dialogId], ['viewed'=> CODE_VALUE_N, 'send' => $this->user->getId(), 'receive' => $to]);
}
$DB->addItem(self::TABLE_MESSAGES, ['dialog_id' => $dialogId, 'user_from' => $this->user->getId(), 'user_to' => $to, 'text' => $message]);
}
}
+72 -2
View File
@@ -53,6 +53,13 @@
*/
public ?Mail $mailObject = null;
/**
* Объект Dialog
*
* @var Dialog|null
*/
public ?Dialog $dialogObject = null;
/**
* Объект мета данных
*
@@ -113,17 +120,30 @@
/**
* Получение всех полей пользователя
*
* @param bool $onlySecureData Флаг получения только безопасных данных
*
* @return array|null
* @throws CoreException
*/
public function getAllUserData(): ?array
public function getAllUserData(bool $onlySecureData = false): ?array
{
$cacheId = md5('User_getAllUserData_' . $this->id);
$onlySecureDataCacheKey = (int)$onlySecureData;
$cacheId = md5('User_getAllUserData_' . $onlySecureDataCacheKey . '_' . $this->id);
if (Cache::check($cacheId)) {
$result = Cache::get($cacheId);
} else {
$result = (DB::getInstance())->getItem(self::TABLE, ['id' => $this->id]);
$result = array_merge($result, ['roles' => $this->getRolesObject()->getRoles()]);
// В случае запроса безопасных данных убираем лишнее
if ($onlySecureData) {
foreach($result as $key => $value) {
if (in_array($key, ['password', 'email_confirmed', 'verification_code', 'token', 'roles', ''], true)) {
unset($result[$key]);
}
}
}
Cache::set($cacheId, $result);
}
@@ -749,6 +769,19 @@
return $this->mailObject;
}
/**
* Получить объект для работы с диалогами
*
* @return Dialog
*/
public function getDialogObject(): Dialog
{
if (empty($this->dialogObject)) {
$this->dialogObject = (new Dialog($this));
}
return $this->dialogObject;
}
/**
* Экспорт всех данных из таблицы пользователей
*
@@ -857,4 +890,41 @@
$res = $DB->query($sql);
return (int)$res[0]['count'];
}
/**
* Получение диалогов
*
* @return array
* @throws CoreException
*/
public function getDialogs(): array
{
$dialogs = $this->getDialogObject()->getDialogs();
foreach ($dialogs as $key => $dialog) {
$dialogs[$key]['send_user_data'] = (new self((int)$dialog['send']))->getAllUserData(true);
$dialogs[$key]['receive_user_data'] = (new self((int)$dialog['receive']))->getAllUserData(true);
}
return $dialogs;
}
/**
* Получение диалогов
*
* @param int $dialogId Идентификатор диалога
* @param bool $markViewed Пометить прочитанным
*
* @return array
* @throws CoreException
*/
public function getMessages(int $dialogId, bool $markViewed = false): array
{
$messages = $this->getDialogObject()->getMessages($dialogId, $markViewed);
foreach ($messages as $key => $message) {
$messages[$key]['user_from_data'] = (new self((int)$message['user_from']))->getAllUserData(true);
$messages[$key]['user_to_data'] = (new self((int)$message['user_to']))->getAllUserData(true);
}
return $messages;
}
}
+7 -1
View File
@@ -23,6 +23,12 @@
use Core\Models\Router;
Router::route('/', '\Core\App::index');
Router::route('/test', '\Core\App::test');
Router::route('/info', '\Core\App::info');
Router::route('/dialogs', '\Core\App::dialogs');
Router::route('/dialog/(\d+)', '\Core\App::dialog');
Router::route('/404', function () {
header('HTTP/1.0 404 Not Found');
@@ -37,7 +43,7 @@
});
Router::route('/test', '\Core\App::test');
Router::route('/test/(\d+)', '\Core\App::test');