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

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

@@ -2,6 +2,8 @@
namespace Core\ExternalServices;
use Core\CoreException;
class Telegram2
{
/** @var int|null $chatId Идентификатор чата для запросов */
@@ -16,7 +18,6 @@
/** Базовый адрес для запросов */
const BASE_URL = 'api.telegram.org';
/** @var string Текущая команда */
private string $cmd;
@@ -48,7 +49,6 @@
*/
public function __construct(string $token = TELEGRAM_BOT_TOKEN)
{
//$this->token = $token;
$this->url = 'https://' . self::BASE_URL . '/bot' . $token . '/';
return $this;
}
@@ -62,11 +62,11 @@
*/
public function getChat(string $channel): array
{
$channel = str_replace('https://t.me/', '', str_replace('@', '', $channel));
$response = [
$channel = str_replace('https://t.me/', '', str_replace('@', '', $channel));
$request = [
'chat_id' => '@' . $channel,
];
return $this->setMethod('getChat')->sendRequest($response);
return $this->setMethod('getChat')->sendRequest($request);
}
/**
@@ -98,21 +98,26 @@
/**
* Отправка запроса на API Telegram
*
* @param array $response Параметры
* @param array $request Параметры
*
* @return array
* @throws CoreException
*/
private function sendRequest(array $response): array
private function sendRequest(array $request): array
{
$ch = curl_init($this->url . $this->method);
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_HEADER, false);
$res = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
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
*
* @return array
* @throws CoreException
*/
public function updateMessage(int $messageId, string $text): array
{
$response = [
$request = [
'chat_id' => $this->chatId,
'message_id' => $messageId,
'text' => $text,
];
return $this->setMethod('editMessageText')->sendRequest($response);
return $this->setMethod('editMessageText')->sendRequest($request);
}
/**
@@ -161,18 +167,19 @@
* @param string|null $caption Подпись
*
* @return array
* @throws CoreException
*/
public function sendPhoto(string $imagePath, ?string $caption = null): array
{
$response = [
$request = [
'chat_id' => $this->chatId,
'photo' => curl_file_create($imagePath),
'parse_mode' => 'html',
];
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 Путь до файла
*
* @return array
* @throws CoreException
*/
public function sendDocument(string $filePath): array
{
$response = [
$request = [
'chat_id' => $this->chatId,
'document' => curl_file_create($filePath),
];
return $this->setMethod('sendDocument')->sendRequest($response);
return $this->setMethod('sendDocument')->sendRequest($request);
}
@@ -199,15 +207,16 @@
* @param float $longitude Долгота
*
* @return array
* @throws CoreException
*/
public function sendLocation(float $latitude, float $longitude): array
{
$response = [
$request = [
'chat_id' => $this->chatId,
'latitude' => $latitude,
'longitude' => $longitude,
];
return $this->setMethod('sendLocation')->sendRequest($response);
return $this->setMethod('sendLocation')->sendRequest($request);
}
@@ -217,20 +226,21 @@
* @param string|null $text Текст сообщения
*
* @return array
* @throws CoreException
*/
public function sendMessage(?string $text): array
{
$params = [
$request = [
'chat_id' => $this->chatId,
'parse_mode' => 'html',
'text' => $this->sanitize($text),
];
return $this->setMethod('sendMessage')->sendRequest($params);
return $this->setMethod('sendMessage')->sendRequest($request);
}
/**
* Инициализация
* Установка параметров клиентского запроса
*
* @param array|null $data Массив входных данных
*/
@@ -260,17 +270,17 @@
$this->event['id'] = $data[$this->messageType]['id'];
$this->event['query'] = $data[$this->messageType]['query'];
$this->event['offset'] = $data[$this->messageType]['offset'];
$this->event['user_id'] = $data[$this->messageType]['from']['id']; // идентификатор пользователя
$this->event['username'] = $data[$this->messageType]['from']['username']; // username пользователя
$this->event['first_name'] = $data[$this->messageType]['from']['first_name']; // имя собеседника
$this->event['last_name'] = $data[$this->messageType]['from']['last_name']; // фамилию собеседника
} else { // прямой режим работы
$this->event['chat_id'] = $this->eventChatId = (int)$data[$this->messageType]['chat']['id']; // идентификатор чата
$this->event['user_id'] = $data[$this->messageType]['from']['id']; // идентификатор пользователя
$this->event['username'] = $data[$this->messageType]['from']['username']; // username пользователя
$this->event['first_name'] = $data[$this->messageType]['chat']['first_name']; // имя собеседника
$this->event['last_name'] = $data[$this->messageType]['chat']['last_name']; // фамилию собеседника
$this->event['chat_time'] = $data[$this->messageType]['date']; // дата сообщения
$this->event['user_id'] = $data[$this->messageType]['from']['id']; // идентификатор пользователя
$this->event['username'] = $data[$this->messageType]['from']['username']; // username пользователя
$this->event['first_name'] = $data[$this->messageType]['from']['first_name']; // имя собеседника
$this->event['last_name'] = $data[$this->messageType]['from']['last_name']; // фамилию собеседника
} else { // прямой режим работы
$this->event['chat_id'] = $this->eventChatId = (int)$data[$this->messageType]['chat']['id']; // идентификатор чата
$this->event['user_id'] = $data[$this->messageType]['from']['id']; // идентификатор пользователя
$this->event['username'] = $data[$this->messageType]['from']['username']; // username пользователя
$this->event['first_name'] = $data[$this->messageType]['chat']['first_name']; // имя собеседника
$this->event['last_name'] = $data[$this->messageType]['chat']['last_name']; // фамилию собеседника
$this->event['chat_time'] = $data[$this->messageType]['date']; // дата сообщения
if (!empty($data[$this->messageType]['sticker'])) {
$this->eventType = 'sticker';
@@ -292,7 +302,7 @@
$this->event['file_id'] = $photo['file_id']; // id файла
} elseif (!empty($data[$this->messageType]['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'])) {
$this->eventType = 'document';
$this->event['caption'] = $data[$this->messageType]['caption']; // Выделим подпись к документу
+7 -2
View File
@@ -191,7 +191,7 @@
if ($param == 'key') {
$result = $result . $k . ', ';
} elseif ($param == 'value') {
$result = $result . '\'' . $v . '\', ';
$result = $result . '\'' . addslashes($v) . '\', ';
}
}
return substr($result, 0, -2);
@@ -214,7 +214,12 @@
$stmt = $this->db->query($sql);
} catch (\Throwable $t) {
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;
+2 -1
View File
@@ -106,7 +106,7 @@
*
* @return int|null
*/
public function removeRole(int $roleId): ?int
public function deleteRole(int $roleId): ?int
{
$cacheId = md5('Roles_' . $this->user->getId() . '_getRoles');
Cache::delete($cacheId);
@@ -133,6 +133,7 @@
* Получение всех существующих ролей
*
* @return array|null
* @throws \Core\CoreException
*/
public static function getAllRoles(): ?array
{
+21 -1
View File
@@ -26,7 +26,7 @@
namespace Core\Models;
use Core\CoreException;
use Core\Models\{DB, Roles};
use Core\Models\{DB, Roles, UserMeta};
use Core\Helpers\{Cache, Log, SystemFunctions};
class User
@@ -46,6 +46,13 @@
*/
public $rolesObject = null;
/**
* Объект мета данных
*
* @var Roles
*/
public $metaObject = null;
/**
* Таблица с пользователями
*/
@@ -574,6 +581,19 @@
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 . '"');
}
}