diff --git a/admin/users.php b/admin/users.php index 6c5e8f2..33d333b 100644 --- a/admin/users.php +++ b/admin/users.php @@ -19,6 +19,7 @@ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ + use Core\Helpers\Pagination; use Core\Models\User; require_once __DIR__ . '/inc/header.php'; @@ -62,7 +63,10 @@ @@ -97,6 +101,7 @@ + diff --git a/core/config.php b/core/config.php index 6f5e713..2e42aea 100644 --- a/core/config.php +++ b/core/config.php @@ -59,6 +59,11 @@ */ define('LOG_PATH', $_SERVER['DOCUMENT_ROOT'] . '/core/log'); + /** + * Количество элементов на странице + */ + const PAGINATION_LIMIT = 10; + /** * Параметры SQL базы */ diff --git a/core/lib/Core/App.class.php b/core/lib/Core/App.class.php index 4d39f82..df76f0e 100644 --- a/core/lib/Core/App.class.php +++ b/core/lib/Core/App.class.php @@ -34,7 +34,17 @@ ]; $userData = $USER ? $USER->getAllUserData() : ''; $userRoles = $USER ? $USER->getRolesObject()->getFullRoles() : ''; - echo $twig->render('index.twig', ['navbarItems' => $navbarItems, 'name' => 'Roman Grinko', 'user' => $USER, 'userData' => $userData, 'userRoles' => $userRoles]); + echo $twig->render( + 'index.twig', + [ + 'navbarItems' => $navbarItems, + 'name' => $USER ? $USER->getName() : '', + 'emailConfirmed' => $USER ? $USER->isEmailConfirmed() : false, + 'user' => $USER, + 'userData' => $userData, + 'userRoles' => $userRoles + ] + ); } public static function test(int $id = 1) diff --git a/core/lib/Core/Models/Roles.class.php b/core/lib/Core/Models/Roles.class.php index e2b4944..498ccaf 100644 --- a/core/lib/Core/Models/Roles.class.php +++ b/core/lib/Core/Models/Roles.class.php @@ -21,6 +21,7 @@ namespace Core\Models; + use Core\CoreException; use Core\Helpers\Cache; use Core\Models\User; @@ -60,10 +61,11 @@ * Получение ролей пользователя * * @return array + * @throws CoreException */ public function getRoles(): array { - $cacheId = md5('Roles_' . $this->user->getId() . '_getRoles'); + $cacheId = md5(__CLASS__ . '::' . __FUNCTION__ . '_' . $this->user->getId()); if (Cache::check($cacheId)) { $userRoles = Cache::get($cacheId); } else { @@ -88,10 +90,11 @@ * @param int $roleId ID роли * * @return int|null + * @throws CoreException */ public function addRole(int $roleId): ?int { - $cacheId = md5('Roles_' . $this->user->getId() . '_getRoles'); + $cacheId = md5(__CLASS__ . '::' . __FUNCTION__ . '_' . $this->user->getId()); Cache::delete($cacheId); /** @var $DB DB */ @@ -105,10 +108,11 @@ * @param int $roleId ID роли * * @return int|null + * @throws CoreException */ public function deleteRole(int $roleId): ?int { - $cacheId = md5('Roles_' . $this->user->getId() . '_getRoles'); + $cacheId = md5(__CLASS__ . '::' . __FUNCTION__); Cache::delete($cacheId); /** @var $DB DB */ @@ -119,9 +123,11 @@ /** * Получение полной информации о ролях пользователя * + * @deprecated Реализован новый метод для получения этих данных * @return array|null + * @throws CoreException */ - public function getFullRoles(): ?array + public function getFullRolesOld(): ?array { return array_map(function ($element) { return static::getAllRoles()[$element]; @@ -129,6 +135,23 @@ $this->getRoles()); } + /** + * Получение полной информации о ролях пользователя V2 + * + * @return array|null + * @throws CoreException + */ + public function getFullRoles(): ?array + { + /** @var $DB DB */ + $DB = DB::getInstance(); + return $DB->query( + 'SELECT ' . self::ROLES_TABLE . '.id, ' . self::ROLES_TABLE . '.name, ' . self::ROLES_TABLE . '.description FROM ' + . self::USER_ROLES_TABLE . ' left JOIN ' . self::ROLES_TABLE . ' ON ' . self::USER_ROLES_TABLE . '.role_id = ' . self::ROLES_TABLE + . '.id WHERE ' . self::USER_ROLES_TABLE . '.user_id = "' . $this->user->getId() . '"' + ) ?: []; + } + /** * Получение всех существующих ролей * @@ -137,7 +160,7 @@ */ public static function getAllRoles(): ?array { - $cacheId = md5('Roles::getAllRoles'); + $cacheId = md5(__CLASS__ . '::' . __FUNCTION__); if (Cache::check($cacheId)) { $roles = Cache::get($cacheId); } else { diff --git a/core/lib/Core/Models/User.class.php b/core/lib/Core/Models/User.class.php index cf1ece8..a4d5249 100644 --- a/core/lib/Core/Models/User.class.php +++ b/core/lib/Core/Models/User.class.php @@ -93,6 +93,7 @@ * Получение аватара пользователя * * @return array|null + * @throws CoreException */ public function getImage(): ?array { @@ -113,6 +114,7 @@ * Получение всех полей пользователя * * @return array|null + * @throws CoreException */ public function getAllUserData(): ?array { @@ -121,6 +123,7 @@ $result = Cache::get($cacheId); } else { $result = (DB::getInstance())->getItem(self::TABLE, ['id' => $this->id]); + $result = array_merge($result, ['roles' => $this->getRolesObject()->getRoles()]); Cache::set($cacheId, $result); } @@ -135,6 +138,7 @@ * Получение логина текущего пользователя * * @return string|null + * @throws CoreException */ public function getLogin(): ?string { @@ -145,6 +149,7 @@ * Получение E-Mail'а текущего пользователя * * @return string|null + * @throws CoreException */ public function getEmail(): ?string { @@ -155,6 +160,7 @@ * Получение имени текущего пользователя * * @return string|null + * @throws CoreException */ public function getName(): ?string { @@ -165,6 +171,7 @@ * Получение токена текущего пользователя * * @return string|null + * @throws CoreException */ public function getToken(): ?string { @@ -172,13 +179,14 @@ } /** - * Получение времени ппоследней активности + * Получение времени последней активности * * @return string|null + * @throws CoreException */ - public function getLastActive(): ?string + public function getLastActive(): ?int { - return $this->getAllUserData() ? $this->getAllUserData()['last_active'] : null; + return $this->getAllUserData() ? (int)$this->getAllUserData()['last_active'] : null; } /** @@ -188,13 +196,14 @@ */ public function getId(): ?int { - return $this->getAllUserData() ? $this->getAllUserData()['id'] : null; + return $this->id; } /** * Получение кода верификации * * @return string|null + * @throws CoreException */ public function getVerificationCode(): ?string { @@ -362,10 +371,10 @@ 'password' => self::passwordEncryption($password), 'name' => $name, 'image_id' => 0, - 'token' => $verificationCode, + 'token' => null, 'email' => $email, 'email_confirmed' => CODE_VALUE_N, - 'verification_code' => md5(self::$cryptoSalt . $email . $login . time()), + 'verification_code' => $verificationCode, 'last_active' => time(), ]); $objectUser = null; @@ -395,6 +404,14 @@ return $userId; } + /** + * Обновление данных пользователя + * + * @param array $fields Массив полей для обновления + * + * @return bool + * @throws CoreException + */ public function update(array $fields): bool { foreach($fields as $key => $value) { @@ -439,13 +456,13 @@ } /** - * Считает количество пользователей + * Получение количества пользователей * * @return int */ - public static function countUsers(): int + public static function getAllCount(): int { - $cacheId = md5('countUsers'); + $cacheId = md5('User::getAllCount'); if (Cache::check($cacheId) && Cache::getAge($cacheId) < 300) { $result = Cache::get($cacheId); } else { @@ -587,6 +604,7 @@ * Проверка на админа * * @return bool + * @throws CoreException */ public function isAdmin(): bool { @@ -670,6 +688,7 @@ * Проверка электронной почты на подтвержденность * * @return bool + * @throws CoreException */ public function isEmailConfirmed(): bool { @@ -700,9 +719,14 @@ * Отправка кода верификации пользователю на почту * * @return void + * @throws CoreException */ public function sendVerificationCode(): void { + if (empty($this->getAllUserData()['verification_code'])) { + Log::logToFile('Ошибка отправки кода верификации: код отсутствует', 'User.log', ['userId' => $this->id]); + throw new CoreException('Ошибка отправки кода верификации: код отсутствует'); + } Log::logToFile('Выслан код верификаци', 'User.log', ['userId' => $this->id, 'code' => $this->getAllUserData()['verification_code']]); $this->getMailObject() ->setSubject('Подтверждение E-Mail') diff --git a/templates/index.twig b/templates/index.twig index 44cf19c..3bc86da 100644 --- a/templates/index.twig +++ b/templates/index.twig @@ -5,12 +5,17 @@ {% block title %}Главная страница{% endblock %} {% block content %} - тут текст главной страницы
+

Главная страница Delta Framwrork

{% if user %} - Hello, {{ user.name }}!
- Your ID: {{ user.id }}
-
{{ dump(user) }}}}
+ Добро пожаловать, {{ user.name }}!
+ Ваш ID: {{ user.id }}
+ {% if emailConfirmed == false %} + Email требует подтверждения
+ {% endif %} + + {% else %} + Вы не авторизованы в системе {% endif %} {% endblock %} \ No newline at end of file