[+] метаданные пользователей

This commit is contained in:
rsgrinko committed 2022-07-15 23:16:36 +03:00
1 parent f74c23b527
commit d6c2a58951
7 files changed
+239 -75

No files matched your search

+6 -1
View File
@@ -24,6 +24,11 @@
*/ */
const CORE_VERSION = '1.0.0_dev'; const CORE_VERSION = '1.0.0_dev';
/**
* Флаг отладки
*/
const DEBUG = true;
/** /**
* Путь до корня проекта * Путь до корня проекта
*/ */
@@ -81,7 +86,7 @@
/** /**
* Использование кэша * Использование кэша
*/ */
const USE_CACHE = true; const USE_CACHE = false;
/** /**
* Папка кэша * Папка кэша
@@ -2,6 +2,8 @@
namespace Core\ExternalServices; namespace Core\ExternalServices;
use Core\CoreException;
class Telegram2 class Telegram2
{ {
/** @var int|null $chatId Идентификатор чата для запросов */ /** @var int|null $chatId Идентификатор чата для запросов */
@@ -16,7 +18,6 @@
/** Базовый адрес для запросов */ /** Базовый адрес для запросов */
const BASE_URL = 'api.telegram.org'; const BASE_URL = 'api.telegram.org';
/** @var string Текущая команда */ /** @var string Текущая команда */
private string $cmd; private string $cmd;
@@ -48,7 +49,6 @@
*/ */
public function __construct(string $token = TELEGRAM_BOT_TOKEN) public function __construct(string $token = TELEGRAM_BOT_TOKEN)
{ {
//$this->token = $token;
$this->url = 'https://' . self::BASE_URL . '/bot' . $token . '/'; $this->url = 'https://' . self::BASE_URL . '/bot' . $token . '/';
return $this; return $this;
} }
@@ -62,11 +62,11 @@
*/ */
public function getChat(string $channel): array public function getChat(string $channel): array
{ {
$channel = str_replace('https://t.me/', '', str_replace('@', '', $channel)); $channel = str_replace('https://t.me/', '', str_replace('@', '', $channel));
$response = [ $request = [
'chat_id' => '@' . $channel, 'chat_id' => '@' . $channel,
]; ];
return $this->setMethod('getChat')->sendRequest($response); return $this->setMethod('getChat')->sendRequest($request);
} }
/** /**
@@ -98,21 +98,26 @@
/** /**
* Отправка запроса на API Telegram * Отправка запроса на API Telegram
* *
* @param array $response Параметры * @param array $request Параметры
* *
* @return array * @return array
* @throws CoreException
*/ */
private function sendRequest(array $response): array private function sendRequest(array $request): array
{ {
$ch = curl_init($this->url . $this->method); $ch = curl_init($this->url . $this->method);
curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $response); curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false); curl_setopt($ch, CURLOPT_HEADER, false);
$res = curl_exec($ch); $res = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch); curl_close($ch);
return json_decode($res, true); $res = json_decode($res, true);
if (empty($res) || $res['ok'] !== true) {
throw new CoreException($res['description'], $res['error_code']);
}
return $res;
} }
/** /**
@@ -143,15 +148,16 @@
* @param string $text * @param string $text
* *
* @return array * @return array
* @throws CoreException
*/ */
public function updateMessage(int $messageId, string $text): array public function updateMessage(int $messageId, string $text): array
{ {
$response = [ $request = [
'chat_id' => $this->chatId, 'chat_id' => $this->chatId,
'message_id' => $messageId, 'message_id' => $messageId,
'text' => $text, 'text' => $text,
]; ];
return $this->setMethod('editMessageText')->sendRequest($response); return $this->setMethod('editMessageText')->sendRequest($request);
} }
/** /**
@@ -161,18 +167,19 @@
* @param string|null $caption Подпись * @param string|null $caption Подпись
* *
* @return array * @return array
* @throws CoreException
*/ */
public function sendPhoto(string $imagePath, ?string $caption = null): array public function sendPhoto(string $imagePath, ?string $caption = null): array
{ {
$response = [ $request = [
'chat_id' => $this->chatId, 'chat_id' => $this->chatId,
'photo' => curl_file_create($imagePath), 'photo' => curl_file_create($imagePath),
'parse_mode' => 'html', 'parse_mode' => 'html',
]; ];
if (!empty($caption)) { if (!empty($caption)) {
$response['caption'] = $this->sanitize($caption, true); $request['caption'] = $this->sanitize($caption, true);
} }
return $this->setMethod('sendPhoto')->sendRequest($response); return $this->setMethod('sendPhoto')->sendRequest($request);
} }
/** /**
@@ -181,14 +188,15 @@
* @param string $filePath Путь до файла * @param string $filePath Путь до файла
* *
* @return array * @return array
* @throws CoreException
*/ */
public function sendDocument(string $filePath): array public function sendDocument(string $filePath): array
{ {
$response = [ $request = [
'chat_id' => $this->chatId, 'chat_id' => $this->chatId,
'document' => curl_file_create($filePath), 'document' => curl_file_create($filePath),
]; ];
return $this->setMethod('sendDocument')->sendRequest($response); return $this->setMethod('sendDocument')->sendRequest($request);
} }
@@ -199,15 +207,16 @@
* @param float $longitude Долгота * @param float $longitude Долгота
* *
* @return array * @return array
* @throws CoreException
*/ */
public function sendLocation(float $latitude, float $longitude): array public function sendLocation(float $latitude, float $longitude): array
{ {
$response = [ $request = [
'chat_id' => $this->chatId, 'chat_id' => $this->chatId,
'latitude' => $latitude, 'latitude' => $latitude,
'longitude' => $longitude, 'longitude' => $longitude,
]; ];
return $this->setMethod('sendLocation')->sendRequest($response); return $this->setMethod('sendLocation')->sendRequest($request);
} }
@@ -217,20 +226,21 @@
* @param string|null $text Текст сообщения * @param string|null $text Текст сообщения
* *
* @return array * @return array
* @throws CoreException
*/ */
public function sendMessage(?string $text): array public function sendMessage(?string $text): array
{ {
$params = [ $request = [
'chat_id' => $this->chatId, 'chat_id' => $this->chatId,
'parse_mode' => 'html', 'parse_mode' => 'html',
'text' => $this->sanitize($text), 'text' => $this->sanitize($text),
]; ];
return $this->setMethod('sendMessage')->sendRequest($params); return $this->setMethod('sendMessage')->sendRequest($request);
} }
/** /**
* Инициализация * Установка параметров клиентского запроса
* *
* @param array|null $data Массив входных данных * @param array|null $data Массив входных данных
*/ */
@@ -260,17 +270,17 @@
$this->event['id'] = $data[$this->messageType]['id']; $this->event['id'] = $data[$this->messageType]['id'];
$this->event['query'] = $data[$this->messageType]['query']; $this->event['query'] = $data[$this->messageType]['query'];
$this->event['offset'] = $data[$this->messageType]['offset']; $this->event['offset'] = $data[$this->messageType]['offset'];
$this->event['user_id'] = $data[$this->messageType]['from']['id']; // идентификатор пользователя $this->event['user_id'] = $data[$this->messageType]['from']['id']; // идентификатор пользователя
$this->event['username'] = $data[$this->messageType]['from']['username']; // username пользователя $this->event['username'] = $data[$this->messageType]['from']['username']; // username пользователя
$this->event['first_name'] = $data[$this->messageType]['from']['first_name']; // имя собеседника $this->event['first_name'] = $data[$this->messageType]['from']['first_name']; // имя собеседника
$this->event['last_name'] = $data[$this->messageType]['from']['last_name']; // фамилию собеседника $this->event['last_name'] = $data[$this->messageType]['from']['last_name']; // фамилию собеседника
} else { // прямой режим работы } else { // прямой режим работы
$this->event['chat_id'] = $this->eventChatId = (int)$data[$this->messageType]['chat']['id']; // идентификатор чата $this->event['chat_id'] = $this->eventChatId = (int)$data[$this->messageType]['chat']['id']; // идентификатор чата
$this->event['user_id'] = $data[$this->messageType]['from']['id']; // идентификатор пользователя $this->event['user_id'] = $data[$this->messageType]['from']['id']; // идентификатор пользователя
$this->event['username'] = $data[$this->messageType]['from']['username']; // username пользователя $this->event['username'] = $data[$this->messageType]['from']['username']; // username пользователя
$this->event['first_name'] = $data[$this->messageType]['chat']['first_name']; // имя собеседника $this->event['first_name'] = $data[$this->messageType]['chat']['first_name']; // имя собеседника
$this->event['last_name'] = $data[$this->messageType]['chat']['last_name']; // фамилию собеседника $this->event['last_name'] = $data[$this->messageType]['chat']['last_name']; // фамилию собеседника
$this->event['chat_time'] = $data[$this->messageType]['date']; // дата сообщения $this->event['chat_time'] = $data[$this->messageType]['date']; // дата сообщения
if (!empty($data[$this->messageType]['sticker'])) { if (!empty($data[$this->messageType]['sticker'])) {
$this->eventType = 'sticker'; $this->eventType = 'sticker';
@@ -292,7 +302,7 @@
$this->event['file_id'] = $photo['file_id']; // id файла $this->event['file_id'] = $photo['file_id']; // id файла
} elseif (!empty($data[$this->messageType]['voice'])) { } elseif (!empty($data[$this->messageType]['voice'])) {
$this->eventType = 'voice'; $this->eventType = 'voice';
$this->event['file_id'] = $data[$this->messageType]['voice']['file_id']; // id файла $this->event['file_id'] = $data[$this->messageType]['voice']['file_id']; // id файла
} elseif (!empty($data[$this->messageType]['document'])) { } elseif (!empty($data[$this->messageType]['document'])) {
$this->eventType = 'document'; $this->eventType = 'document';
$this->event['caption'] = $data[$this->messageType]['caption']; // Выделим подпись к документу $this->event['caption'] = $data[$this->messageType]['caption']; // Выделим подпись к документу
+7 -2
View File
@@ -191,7 +191,7 @@
if ($param == 'key') { if ($param == 'key') {
$result = $result . $k . ', '; $result = $result . $k . ', ';
} elseif ($param == 'value') { } elseif ($param == 'value') {
$result = $result . '\'' . $v . '\', '; $result = $result . '\'' . addslashes($v) . '\', ';
} }
} }
return substr($result, 0, -2); return substr($result, 0, -2);
@@ -214,7 +214,12 @@
$stmt = $this->db->query($sql); $stmt = $this->db->query($sql);
} catch (\Throwable $t) { } catch (\Throwable $t) {
sendTelegram('SQL ERROR: ' . $sql); sendTelegram('SQL ERROR: ' . $sql);
throw new CoreException('В SQL запросе произошла ошибка', CoreException::ERROR_SQL_QUERY); if(DEBUG) {
throw new CoreException('В SQL запросе произошла ошибка. Запрос: ' . $sql, CoreException::ERROR_SQL_QUERY);
} else {
throw new CoreException('В SQL запросе произошла ошибка', CoreException::ERROR_SQL_QUERY);
}
} }
$this->lastInsertId = $this->db->lastInsertId() ?? null; $this->lastInsertId = $this->db->lastInsertId() ?? null;
+2 -1
View File
@@ -106,7 +106,7 @@
* *
* @return int|null * @return int|null
*/ */
public function removeRole(int $roleId): ?int public function deleteRole(int $roleId): ?int
{ {
$cacheId = md5('Roles_' . $this->user->getId() . '_getRoles'); $cacheId = md5('Roles_' . $this->user->getId() . '_getRoles');
Cache::delete($cacheId); Cache::delete($cacheId);
@@ -133,6 +133,7 @@
* Получение всех существующих ролей * Получение всех существующих ролей
* *
* @return array|null * @return array|null
* @throws \Core\CoreException
*/ */
public static function getAllRoles(): ?array public static function getAllRoles(): ?array
{ {
+21 -1
View File
@@ -26,7 +26,7 @@
namespace Core\Models; namespace Core\Models;
use Core\CoreException; use Core\CoreException;
use Core\Models\{DB, Roles}; use Core\Models\{DB, Roles, UserMeta};
use Core\Helpers\{Cache, Log, SystemFunctions}; use Core\Helpers\{Cache, Log, SystemFunctions};
class User class User
@@ -46,6 +46,13 @@
*/ */
public $rolesObject = null; public $rolesObject = null;
/**
* Объект мета данных
*
* @var Roles
*/
public $metaObject = null;
/** /**
* Таблица с пользователями * Таблица с пользователями
*/ */
@@ -574,6 +581,19 @@
return $this->rolesObject; return $this->rolesObject;
} }
/**
* Получить объект для работы с ролями
*
* @return UserMeta
*/
public function getMetaObject(): UserMeta
{
if (empty($this->metaObject)) {
$this->metaObject = (new UserMeta($this));
}
return $this->metaObject;
}
/** /**
* Экспорт всех данных из таблицы пользователей * Экспорт всех данных из таблицы пользователей
* *
+160
View File
@@ -0,0 +1,160 @@
<?php
namespace Core\Models;
use Core\Helpers\Cache;
class UserMeta
{
/**
* Таблица с мета полями
*/
const TABLE = 'user_meta';
/**
* @var User $user
*/
private $user = null;
public function __construct(User $user)
{
$this->user = $user;
}
/**
* Получение ролей пользователя
*
* @return array
* @throws \Core\CoreException
*/
public function getAllMeta(): array
{
$cacheId = md5('Meta_' . $this->user->getId() . '_getAllMeta');
if (Cache::check($cacheId)) {
$userMeta = Cache::get($cacheId);
} else {
/** @var $DB DB */
$DB = DB::getInstance();
$res = $DB->query('SELECT * FROM `' . self::TABLE . '` WHERE user_id=' . $this->user->getId());
$userMeta = [];
if (!empty($res)) {
foreach ($res as $meta) {
$userMeta[] = [
'id' => $meta['id'],
'type' => $meta['type'],
'name' => $meta['name'],
'value' => $meta['value'],
];
}
}
Cache::set($cacheId, $userMeta);
}
return $userMeta;
}
/**
* Получает указанные мета данные пользователя
*
* @param string $name Имя мета
*
* @return array|null
* @throws \Core\CoreException
*/
public function getMetaByName(string $name): ?array
{
$cacheId = md5('Meta_' . $this->user->getId() . '_getMetaByName');
if (Cache::check($cacheId)) {
$userMeta = Cache::get($cacheId);
} else {
/** @var $DB DB */
$DB = DB::getInstance();
$res = $DB->query('SELECT * FROM `' . self::TABLE . '` WHERE user_id=' . $this->user->getId() . ' AND name="' . $name . '"');
if (!empty($res)) {
$userMeta = [];
foreach ($res as $meta) {
$userMeta[] = [
'id' => $meta['id'],
'type' => $meta['type'],
'name' => $meta['name'],
'value' => $meta['value'],
];
}
Cache::set($cacheId, $userMeta);
}
}
return $userMeta;
}
/**
* Получает указанные мета данные пользователя
*
* @param string|null $type Тип мета
*
* @return array|null
* @throws \Core\CoreException
*/
public function getMetaByType(string $type): ?array
{
$cacheId = md5('Meta_' . $this->user->getId() . '_getMetaByType');
if (Cache::check($cacheId)) {
$userMeta = Cache::get($cacheId);
} else {
/** @var $DB DB */
$DB = DB::getInstance();
$res = $DB->query('SELECT * FROM `' . self::TABLE . '` WHERE user_id=' . $this->user->getId() . ' AND type="' . $type . '"');
if (!empty($res)) {
$userMeta = [];
foreach ($res as $meta) {
$userMeta[] = [
'id' => $meta['id'],
'type' => $meta['type'],
'name' => $meta['name'],
'value' => $meta['value'],
];
}
Cache::set($cacheId, $userMeta);
}
}
return $userMeta;
}
/**
* Добавляет пользователю указанные мета данные
*
* @param string $name Имя мета
* @param string|null $value Значение мета
* @param string $type
*
* @return int|null
* @throws \Core\CoreException
*/
public function addMeta(string $name, ?string $value = null, string $type = 'default'): ?int
{
$cacheId = md5('Meta_' . $this->user->getId() . '_getAllMeta');
Cache::delete($cacheId);
/** @var $DB DB */
$DB = DB::getInstance();
return $DB->addItem(self::TABLE, ['user_id' => $this->user->getId(), 'name' => $name, 'value' => $value, 'type' => $type]);
}
/**
* Убирает пользователю указанные мета данные
*
* @param string $name Имя мета
*
* @return int|null
* @throws \Core\CoreException
*/
public function deleteMeta(string $name): void
{
$cacheId = md5('Roles_' . $this->user->getId() . '_getRoles');
Cache::delete($cacheId);
/** @var $DB DB */
$DB = DB::getInstance();
$DB->query('DELETE FROM ' . self::TABLE . ' WHERE user_id=' . $this->user->getId() . ' AND name="' . $name . '"');
}
}
-37
View File
@@ -1,37 +0,0 @@
<?php
/**
* Copyright (c) 2022 Roman Grinko <rsgrinko@gmail.com>
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Core;
class Panel
{
public static function index()
{
global $twig;
$navbarItems = [
['name' => 'Главная', 'url' => '/', 'active' => true],
['name' => 'Админка', 'url' => '/admin', 'active' => false],
['name' => 'Командная PHP строка', 'url' => '/phpcmd.php', 'active' => false],
['name' => 'Тест', 'url' => '/test', 'active' => false],
];
echo $twig->render('admin/index.twig', ['navbarItems' => $navbarItems, 'name' => 'Roman Grinko']);
}
}