This commit is contained in:
rsgrinko committed 2022-04-18 13:59:35 +03:00
1 parent ed22916fa7
commit c1d9c174ba
7 files changed
+727 -7

No files matched your search

@@ -0,0 +1,355 @@
<?php
/**
* Класс для работы с API телеграмм
* Поддерживает:
* - отправка сообщений с разметкой html
* - редактирование отправленных сообщений
* - работу с inline класиатурами (в сообщении)
* - работу с быстрыми клавиатурами (меню бота)
* - отправка сообщений с изображением с разметкой html
* - отправка файлов
* - получение информации о группе или канале
* - получение файлов по идентификатору
* - имитация действий (набирает сообщение, записывает голосовое и т.д.)
* - отправка местоположений
* - обработка callback запросов
* - обработка inline событий
*
* @version 2.5.1
* @author Roman Grinko <rsgrinko@gmail.com>
*/
namespace Core\ExternalServices;
class Telegram
{
/**
* @var string $token Токен бота
*/
private static string $token;
/**
* @var string $url Адрес API запроса
*/
private static string $url;
const BASE_URL = 'api.telegram.org';
/**
* @var string $uploadDir Директория для загрузки и хранения файлов
*/
private static string $uploadDir;
/**
* Инициализация
*
* @param string $token Токен бота
* @param string $uploadDir Директория для загрузки и хранения файлов
*/
public static function init(string $token, string $uploadDir): void
{
self::$token = $token;
self::$url = 'https://' . self::BASE_URL . '/bot' . $token . '/';
self::$uploadDir = $uploadDir;
}
/**
* Отправка запроса на API Telegram
*
* @param string $method Используемый метод
* @param array $response Параметры
*
* @return array
*/
private static function sendRequest(string $method, array $response): array
{
$ch = curl_init(self::$url . $method);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $response);
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);
}
/**
* Получение информации о канале или группе
*
* @param string $channel Канал
*
* @return array
*/
public static function getChat(string $channel): array
{
$channel = str_replace('https://t.me/', '', str_replace('@', '', $channel));
$response = [
'chat_id' => '@' . $channel,
];
return self::sendRequest('getChat', $response);
}
/**
* Отправка изображения
*
* @param int $chatId Идентификатор чата
* @param string $imagePath Путь до изображения
*
* @return array
*/
public static function sendPhoto(int $chatId, string $imagePath): array
{
$response = [
'chat_id' => $chatId,
'photo' => curl_file_create($imagePath),
];
return self::sendRequest('sendPhoto', $response);
}
/**
* Отправка файла
*
* @param int $chatId Идентификатор чата
* @param string $filePath Путь до файла
*
* @return array
*/
public static function sendDocument(int $chatId, string $filePath): array
{
$response = [
'chat_id' => $chatId,
'document' => curl_file_create($filePath),
];
return self::sendRequest('sendDocument', $response);
}
/**
* Получить присланный файл
*
* @param string $fileId Идентификатор файла
*
* @return string|null
*/
public static function getFile(string $fileId): ?string
{
$response = [
'file_id' => $fileId,
];
$res = self::sendRequest('getFile', $response);
if ($res['ok']) {
$src = 'https://' . self::BASE_URL . '/file/bot' . self::$token . '/' . $res['result']['file_path'];
$dest = self::$uploadDir . '/' . time() . '-' . basename($src);
if (copy($src, $dest)) {
return $dest;
} else {
return null;
}
}
}
/**
* Изменяет уже отправленное сообщение на указанное
*
* @param $chatId
* @param $messageId
* @param string $text
*
* @return array
*/
public static function updateMessage(int $chatId, int $messageId, string $text): array
{
$response = [
'chat_id' => $chatId,
'message_id' => $messageId,
'text' => $text,
];
return self::sendRequest('editMessageText', $response);
}
/**
* Отправка в чат имитаций событий
* <pre>
* typing для набора текста
* upload_photo для загрузки фото
* record_video или upload_video для видео
* record_voice или upload_voice для голосовых
* upload_document здля загрузки документов
* choose_sticker для выбора стикера
* find_location для местоположения
* record_video_note или upload_video_note для видеосообщений
* </pre>
*
* @param int $chatId ID чата
* @param string $action Событие
*
* @return array
*/
public static function sendChatAction(int $chatId, string $action = 'typing'): array
{
$response = [
'chat_id' => $chatId,
'action' => $action,
];
return self::sendRequest('sendChatAction', $response);
}
/**
* Отправляет координаты с картой
*
* @param int $chatId ID чата
* @param float $latitude Широта
* @param float $longitude Долгота
*
* @return array
*/
public static function sendLocation(int $chatId, float $latitude, float $longitude): array
{
$response = [
'chat_id' => $chatId,
'latitude' => $latitude,
'longitude' => $longitude,
];
return self::sendRequest('sendLocation', $response);
}
/**
* Метод для обработки событий callback'ов
*
* @param int|null $callbackId Идентификатор callback
* @param string|null $text Текст
* @param bool $showAlert Показывать ли уведомление
* @param string|null $url Адрес
*
* @return array
*/
public static function answerCallbackQuery(?int $callbackId, ?string $text = null, bool $showAlert = false, ?string $url = null): array
{
$response = [
'callback_query_id' => $callbackId,
'text' => $text,
'show_alert' => $showAlert,
'url' => $url,
];
return self::sendRequest('answerCallbackQuery', $response);
}
/**
* Метод для обработки событий Inline режима
*
* @param int|null $inline_query_id ID запроса
* @param string $results Массив результатов запроса
* @param int $cache_time Время кэширования
* @param bool $is_personal Персонально для каждого пользователя
*
* @return array
*/
public static function answerInlineQuery(?int $inline_query_id, string $results, int $cache_time = 300, bool $is_personal = true): array
{
$response = [
'inline_query_id' => $inline_query_id,
'results' => $results,
'cache_time' => $cache_time,
'is_personal' => $is_personal,
];
return self::sendRequest('answerInlineQuery', $response);
}
/**
* Создание json с результатами для отдачи в inline
* <pre>
* $arData = [
* [
* 'title' => 'Title1',
* 'description' => 'description1',
* 'message_text' => 'Message1',
* 'thumb_url' => 'http://example.com/1.jpg'
* ],
* ]
* </pre>
*
* @param string $inlineType Тип результата
* @param array $arData Массив элементов+
*
* @return string
*/
public static function createInlineQueryResult(string $inlineType, array $arData): string
{
$result = [];
foreach ($arData as $key => $element) {
$tmpResult = [
'type' => $inlineType,
'id' => 'id_' . $key,
];
$result[] = array_merge($tmpResult, $element);
}
$result = json_encode($result);
return $result;
}
/**
* Отправка сообщение пользователю в телеграм
*
* @param int $chatId Идентификатор чата
* @param string|null $text Текст сообщения
* @param string $image Путь к картинке
* @param array $inline_keyboard Массив встроенной клавиатуры
* @param array $keyboard Массив клавиатуры
* @param array $keyboard_opt Массив клавиатуры
*
* @return array
*/
public static function execute(
int $chatId,
?string $text,
string $image = '',
array $inline_keyboard = [],
array $keyboard = [],
array $keyboard_opt = []
): array {
$params = [];
$params['chat_id'] = $chatId;
$text = substr(trim($text), 0, 4096);
$text = strip_tags($text, '<b><a><strong><i><em><u><ins><s><strike><del><s><code><pre>');
$text = mb_convert_encoding($text, 'UTF-8', 'UTF-8');
if (!empty($image)) { //text + image
$params['photo'] = curl_file_create($image);
$params['caption'] = $text;
$method = 'sendPhoto';
} else { //only text
$params['parse_mode'] = 'html';
$params['text'] = $text;
$method = 'sendMessage';
}
/* клавиатура */
if (!empty($inline_keyboard)) { // инлайн клавиатура если есть
$inlineKeyboardMarkup = ['inline_keyboard' => $inline_keyboard];
$params['reply_markup'] = json_encode($inlineKeyboardMarkup);
} else { // ставим обычную клавиатуру если есть
if (empty($keyboard_opt)) {
$keyboard_opt[0] = 'keyboard';
$keyboard_opt[1] = false;
$keyboard_opt[2] = true;
}
$options = [
$keyboard_opt[0] => $keyboard,
'one_time_keyboard' => $keyboard_opt[1],
'resize_keyboard' => $keyboard_opt[2],
];
$replyMarkups = json_encode($options);
$removeMarkups = json_encode(['remove_keyboard' => true]);
if ($keyboard == [0]) {
$params['reply_markup'] = $removeMarkups;
} else {
$params['reply_markup'] = $replyMarkups;
}
}
return self::sendRequest($method, $params);
}
}
@@ -0,0 +1,589 @@
<?php
/**
* Класс-обработчик команд Telegram
*
* Поддерживает:
* - работа с простыми командами
* - выделение аргументов команды
* - определение типа события (сообщение, локация, фото, докемент...)
* - работа с инлайн и callback запросами
* - работа с инлайн клавиатурами (под сообщением)
* - работа с клавиатурами (меню)
* - обработка неизвестной команды
*
* @version 1.0.1
* @author Roman Grinko <rsgrinko@gmail.com>
*/
namespace Core\ExternalServices;
class TelegramActions
{
/** @var string Текущая команда */
private static string $cmd;
/** @var ?string Аргументы команды */
private static ?string $params = null;
/** @var array|null $data Массив входных данных */
private static ?array $data = null;
/** @var string|null $eventType Тип события */
private static ?string $eventType = null;
/** @var array|null $event Массив собранных данных по событию */
private static ?array $event = null;
/** @var int|null $chatId Идентификатор текущего чата */
private static ?int $chatId = null;
/**
* @var string $messageType Тип текущего сообщения
*/
private static string $messageType = 'message';
/** @var array $inlineKeyboard Массив для инлайн клавиатуры */
private static array $inlineKeyboard = [];
/**
* Инициализация
*
* @param array|null $data Массив входных данных
*/
public static function init(?array $data): void
{
self::$data = $data;
/** Режим работы - инлайн или прямой */
$inlineMode = false;
if (isset($data['edited_message'])) {
self::$messageType = 'edited_message';
} elseif (isset($data['inline_query'])) {
self::$messageType = 'inline_query';
$inlineMode = true;
} elseif (isset($data['channel_post'])) {
self::$messageType = 'channel_post';
$inlineMode = true;
} else {
self::$messageType = 'message';
}
if ($inlineMode === true) // инлайн режим работы
{
self::$eventType = 'inline_query';
self::$event['id'] = $data[self::$messageType]['id'];
self::$event['query'] = $data[self::$messageType]['query'];
self::$event['offset'] = $data[self::$messageType]['offset'];
self::$event['user_id'] = $data[self::$messageType]['from']['id']; // идентификатор пользователя
self::$event['username'] = $data[self::$messageType]['from']['username']; // username пользователя
self::$event['first_name'] = $data[self::$messageType]['from']['first_name']; // имя собеседника
self::$event['last_name'] = $data[self::$messageType]['from']['last_name']; // фамилию собеседника
} else { // прямой режим работы
self::$event['chat_id'] = self::$chatId = (int)$data[self::$messageType]['chat']['id']; // идентификатор чата
self::$event['user_id'] = $data[self::$messageType]['from']['id']; // идентификатор пользователя
self::$event['username'] = $data[self::$messageType]['from']['username']; // username пользователя
self::$event['first_name'] = $data[self::$messageType]['chat']['first_name']; // имя собеседника
self::$event['last_name'] = $data[self::$messageType]['chat']['last_name']; // фамилию собеседника
self::$event['chat_time'] = $data[self::$messageType]['date']; // дата сообщения
if (!empty($data[self::$messageType]['sticker'])) {
self::$eventType = 'sticker';
self::$event['file_id'] = $data['message']['sticker']['file_id'];
self::$event['emoji'] = $data['message']['sticker']['emoji'] ?: null;
} elseif (!empty($data[self::$messageType]['contact'])) {
self::$eventType = 'contact';
self::$event['phone_number'] = $data[self::$messageType]['contact']['phone_number'];
self::$event['name'] = $data[self::$messageType]['contact']['first_name'] . ' ' . $data['message']['contact']['last_name'];
} elseif (!empty($data[self::$messageType]['location'])) {
self::$eventType = 'location';
self::$event['latitude'] = $data[self::$messageType]['location']['latitude'];
self::$event['longitude'] = $data[self::$messageType]['location']['longitude'];
} elseif (!empty($data[self::$messageType]['photo'])) {
self::$eventType = 'photo';
$photo = array_pop($data[self::$messageType]['photo']);
self::$event['caption'] = $data[self::$messageType]['caption']; // Выделим подпись к изображению
self::$event['file_id'] = $photo['file_id']; // id файла
} elseif (!empty($data[self::$messageType]['voice'])) {
self::$eventType = 'voice';
self::$event['file_id'] = $data[self::$messageType]['voice']['file_id']; // id файла
} elseif (!empty($data[self::$messageType]['document'])) {
self::$eventType = 'document';
self::$event['caption'] = $data[self::$messageType]['caption']; // Выделим подпись к документу
self::$event['file_id'] = $data[self::$messageType]['document']['file_id']; // id файла
} elseif (!empty($data) && isset($data[self::$messageType]['chat']['id']) && $data[self::$messageType]['chat']['id'] !== '') {
self::$eventType = 'message';
self::$event['message'] = $data[self::$messageType]['text']; // Выделим сообщение собеседника (регистр по умолчанию)
self::$event['msg'] = mb_strtolower(
$data[self::$messageType]['text'],
'utf8'
); // Выделим сообщение собеседника (нижний регистр)
if (substr(self::$event['msg'], 0, 1) === '/') {
self::$cmd = substr(self::$event['msg'], 1);
} else {
self::$cmd = self::$event['msg'];
}
// разбиваем запрос на непосредственно команду и ее аргументы
$arParams = explode(' ', self::$cmd);
self::$cmd = $arParams[0]; // основная команда
unset($arParams[0]);
if (!empty($arParams)) {
self::$params = implode(' ', $arParams);
}
} elseif (!empty($data) && isset($data['callback_query']['from']['id']) and $data['callback_query']['from']['id'] !== '') {
self::$eventType = 'callback';
self::$event['callback_id'] = self::$chatId = (int)$data['callback_query']['id']; // идентификатор callback
self::$event['chat_id'] = self::$chatId = (int)$data['callback_query']['message']['chat']['id']; // идентификатор чата
self::$event['user_id'] = $data['callback_query']['from']['id']; // идентификатор пользователя
self::$event['username'] = $data['callback_query']['from']['username']; // username пользователя
self::$event['first_name'] = $data['callback_query']['from']['first_name']; // имя собеседника
self::$event['last_name'] = $data['callback_query']['from']['last_name']; // фамилию собеседника
self::$event['chat_time'] = $data['callback_query']['message']['date']; // дата сообщения
self::$event['data'] = json_decode($data['callback_query']['data'], true); // Содержимое callback запроса
self::$cmd = self::$event['data']['method'];
} else {
self::$eventType = null;
}
}
}
/**
* Получение типа текущего события
*
* @return string|null
*/
public static function getEventType(): ?string
{
return self::$eventType;
}
/**
* Получить собранные данные по текущему событию
*
* @return array|null
*/
public static function getEventData(): ?array
{
return self::$event;
}
/**
* Получить id текущего чата
*
* @return int|null
*/
public static function getChatId(): ?int
{
return self::$chatId;
}
/**
* Получить текущую команду
*
* @return string
*/
private static function getCommand(): string
{
return self::$cmd;
}
/**
* Получить агрументы запроса
*
* @return ?string
*/
private static function getParams(): ?string
{
return self::$params;
}
/**
* Магический метод для неизвестного запроса
*
* @param string $name Имя метода
* @param ?array $arguments Массив аргументов метода
* @return void
*/
public static function __callStatic(string $name, ?array $arguments): void
{
$message = 'Команда ' . self::$cmd . ' не найдена.' . PHP_EOL;
if (!empty($arguments)) {
$message .= 'Аргументы: ' . implode(', ', $arguments) . PHP_EOL;
}
if (self::getEventType() !== 'callback') {
$message .= '<code>' . print_r(self::$data, true) . '</code>';
}
Telegram::sendChatAction(self::getChatId()); // печатает...
Telegram::execute(self::getChatId(), $message, '', self::getInlineKeyboard(), self::getKeyboard());
}
/**
* Непосредственное выполнение команды
*
* @return void
*/
public static function execute(): void
{
self::setInlineKeyboard(null);
$methodName = 'command' . self::$cmd;
self::$methodName();
}
/**
* Непосредственное выполнение callback
*
* @return void
*/
public static function executeCallback(): void
{
self::setInlineKeyboard(null);
$methodName = 'callback' . self::getCommand();
self::$methodName();
}
/**
* Проверка прав на доступ к боту
*
* @return bool
*/
public static function isHasAccess(): bool
{
if ((int)self::$event['chat_id'] === TELEGRAM_ADMIN_CHAT_ID) {
return true;
} else {
return false;
}
}
/**
* Получить клавиатуру
*
* @return array
*/
public static function getKeyboard(): array
{
return [
['/online', '/yastat'],
['/fail2ban', '/stat'],
['/getcam', '/clearcache'],
['/deploy']
];
}
/**
* Установка инлайн клавиатуры
*
* @param array|null $arKeyboard Массив инлайн клавиатуры
*/
private static function setInlineKeyboard(?array $arKeyboard): void
{
if (empty($arKeyboard)) {
self::$inlineKeyboard = [];
} else {
self::$inlineKeyboard = $arKeyboard;
}
}
/**
* Получение инлайн клавиатуры
*
* @return array
*/
public static function getInlineKeyboard(): array
{
return self::$inlineKeyboard;
/*return [
[
['text' => 'Кнопка 1', 'callback_data' => '/online'],
['text' => 'Кнопка 2', 'callback_data' => json_encode($arrParams, JSON_UNESCAPED_UNICODE)]
],
[
['text' => 'Кнопка 3', 'url' => 'https://it-stories.ru']
]
];*/
}
/**
* Возвращает подготовленные данные для подстановки в callback data
*
* @param string $method Метод
* @param array $params Масссив параметров
*
* @return string
*/
private static function getPreparedCallbackData(string $method, array $params = []): string
{
return json_encode(['method' => $method, 'params' => $params], JSON_UNESCAPED_UNICODE);
}
/**
* Команда /start
*
* @return void
*/
public static function commandStart(): void
{
/*self::setInlineKeyboard(
[
[
['text' => 'Руководство', 'callback_data' => self::getPreparedCallbackData('help')],
['text' => 'Панель управления', 'url' => 'https://it-stories.ru/login/']
],
[
['text' => 'test', 'callback_data' => self::getPreparedCallbackData('test')]
]
]);*/
Telegram::sendChatAction(self::getChatId()); // печатает...
Telegram::execute(self::getChatId(), 'Бот успешно запущен', '', self::getInlineKeyboard(), self::getKeyboard());
}
/**
* Команда /stop
*
* @return void
*/
public static function commandStop(): void
{
Telegram::sendChatAction(self::getChatId()); // печатает...
Telegram::execute(self::getChatId(), 'Бот Остановлен', '', self::getInlineKeyboard(), self::getKeyboard());
}
/**
* Команда /test
*
* @return void
*/
public static function commandTest(): void
{
Telegram::sendChatAction(self::getChatId()); // печатает...
Telegram::execute(self::getChatId(), 'Запущена команда test, переданы аргумент: ' . self::getParams(), '', self::getInlineKeyboard(), self::getKeyboard());
}
/**
* Команда /online
*
* @return void
*/
public static function commandOnline(): void
{
Online::removeInactive();
$result = Online::getOnline();
$message = '<b>Посетители онлайн (' . count($result) . ')</b>' . PHP_EOL;
foreach ($result as $key => $item) {
$message .= '✔ <b>Пользователь #' . ($key + 1) . '</b> '
. PHP_EOL
. '<b>IP:</b> ' . $item['ip']
. PHP_EOL
. '<b>Страница:</b> <code>' . $item['page'] . '</code>'
. PHP_EOL
. '<b>Referer:</b> <code>' . (!empty(trim($item['referer'])) ? SystemFunctions::getBaseUrl($item['referer']) : 'нет') . '</code>'
. PHP_EOL
. '<b>Бот:</b> ' . (SystemFunctions::isSearchBot($item['useragent']) ?? 'нет')
. PHP_EOL
. '<b>Последняя активность:</b> ' . SystemFunctions::secToString(time() - (int)$item['last_active'])
. PHP_EOL
. '<b>Геозона:</b> ' . SystemFunctions::gluingLocationToString(['country' => $item['country'], 'region' => $item['region'], 'city' => $item['city']])
. PHP_EOL
. PHP_EOL;
}
Telegram::sendChatAction(self::getChatId()); // печатает...
Telegram::execute(self::getChatId(), $message, '', self::getInlineKeyboard(), self::getKeyboard());
}
/**
* Команда /fail2ban
*
* @return void
*/
public static function commandFail2ban(): void
{
$result = Fail2ban::getBlockedIpList('10', 'last_active', 'DESC');
$message = '<b>Список заблокированных IP (' . Fail2ban::getBlockedIpCount() . ' из ' . Fail2ban::getAllIpCount() . ')</b>' . PHP_EOL;
foreach ($result as $key => $item) {
$message .= '🚩 <b> ' . $item['ip'] . '</b> '
. PHP_EOL
. '<b>Попыток:</b> ' . $item['attempts']
. PHP_EOL
. '<b>Активность:</b> ' . SystemFunctions::secToString(time() - $item['last_active'])
. PHP_EOL
. '<b>Геозона:</b> ' . SystemFunctions::gluingLocationToString(['country' => $item['country'], 'region' => $item['region'], 'city' => $item['city']])
. PHP_EOL
. PHP_EOL;
}
Telegram::sendChatAction(self::getChatId()); // печатает...
Telegram::execute(self::getChatId(), $message, '', self::getInlineKeyboard(), self::getKeyboard());
}
/**
* Команда /deploy
*
* @return void
*/
public static function commandDeploy(): void
{
SystemFunctions::deploymentFromGit();
Telegram::sendChatAction(self::getChatId()); // печатает...
Telegram::execute(self::getChatId(), 'Произведен деплоймент из ветки <b>master</b>', '', self::getInlineKeyboard(), self::getKeyboard());
}
/**
* Команда /stat
*
* @return void
*/
public static function commandStat(): void
{
self::setInlineKeyboard(
[
[
['text' => 'Очистка кэша', 'callback_data' => self::getPreparedCallbackData('clearcache')],
['text' => 'Сброс Opcache', 'callback_data' => self::getPreparedCallbackData('clearopcache')]
]
]);
$countCacheElements = \FCCache::getCountElements();
$cacheSize = \FCCache::getCacheSize();
$usersOnline = Online::getOnlineCount();
$countBlockedIp = Fail2ban::getBlockedIpCount();
$countAllIp = Fail2ban::getAllIpCount();
$arOpcache = opcache_get_status();
$message = '📱 <b>Статистика по проекту</b>'
. PHP_EOL
. '<b>В кэше:</b> ' . $countCacheElements . ' ' . SystemFunctions::numWord($countCacheElements, ['элемент', 'элемента', 'элементов'])
. PHP_EOL
. '<b>Размер кэша:</b> ' . SystemFunctions::convertBytes($cacheSize)
. PHP_EOL
. '<b>В Opcache:</b> ' . $arOpcache['opcache_statistics']['num_cached_scripts'] . ' ' . SystemFunctions::numWord($arOpcache['opcache_statistics']['num_cached_scripts'], ['элемент', 'элемента', 'элементов'])
. PHP_EOL
. '<b>Opcache (используется):</b> ' . SystemFunctions::convertBytes($arOpcache['memory_usage']['used_memory'])
. PHP_EOL
. '<b>Opcache (свободно):</b> ' . SystemFunctions::convertBytes($arOpcache['memory_usage']['free_memory'])
. PHP_EOL
. '<b>Opcache (битая):</b> ' . SystemFunctions::convertBytes($arOpcache['memory_usage']['wasted_memory'])
. PHP_EOL
. '<b>Opcache (всего):</b> 512Mb'
. PHP_EOL
. '<b>Онлайн на сайте:</b> ' . $usersOnline . ' ' . SystemFunctions::numWord($usersOnline, ['посетитель', 'посетителя', 'посетителей'])
. PHP_EOL
. '<b>Заблокировано:</b> ' . $countBlockedIp . ' ' . SystemFunctions::numWord($countBlockedIp, ['адрес', 'адреса', 'адресов']) . ' из ' . $countAllIp;
Telegram::sendChatAction(self::getChatId()); // печатает...
Telegram::execute(self::getChatId(), $message, '', self::getInlineKeyboard(), self::getKeyboard());
}
/**
* Команда /yastat
*
* @return void
*/
public static function commandYaStat(): void
{
$objectYandex = new Yandex(
YANDEX_APP_ID,
YANDEX_APP_SECRET,
YANDEX_REDIRECT_URL
);
$objectYandex->loadConfig()->refreshToken();
$objectYandex->save();
$query = [
'oauth_token' => $objectYandex->getAccessToken(),
'dimension_field' => 'date|day',
'period' => 'thisyear',
'entity_field' => 'page_level',
'field' => 'partner_wo_nds',
'lang' => 'ru',
'pretty' => '0'
];
$result = $objectYandex->request(
'partner2.yandex.ru',
'api/statistics2/get.json',
$query);
$day_price = [];
foreach ($result['data']['points'] as $k => $item) {
$day = date("d") - 1;
if ($day == 0) {
$day = 1;
} elseif ($day < 9) {
$day = '0' . $day;
}
if ($item['dimensions']['date'][0] == date("Y-m-") . $day) {
$day_price['yesterday'] = $item['measures'][0]['partner_wo_nds'];
}
if ($item['dimensions']['date'][0] == date("Y-m-d")) {
$day_price['today'] = $item['measures'][0]['partner_wo_nds'];
}
}
$day_price['today'] = $day_price['today'] ?? '0';
$day_price['yesterday'] = $day_price['yesterday'] ?? '0';
$message = '<b>Статистика РСЯ</b>' . PHP_EOL
. 'Доход за сегодня: ' . $day_price['today'] . ' р.' . PHP_EOL
. 'Доход за вчера: ' . $day_price['yesterday'] . ' р.' . PHP_EOL
. 'Курс доллара: ' . SystemFunctions::getExchangeRates('USD', 2) . ' р.';
Telegram::sendChatAction(self::getChatId()); // печатает...
Telegram::execute(self::getChatId(), $message, '', self::getInlineKeyboard(), self::getKeyboard());
}
/**
* Команда /getcam
*
* @return void
*/
public static function commandGetCam(): void
{
$image = SystemFunctions::getCamScreen();
Telegram::sendChatAction(self::getChatId()); // печатает...
Telegram::execute(self::getChatId(), 'Снимок сделан ' . date('d.m.Y H:i:s', strtotime('+3 hours')), $image, self::getInlineKeyboard(), self::getKeyboard());
}
/**
* Команда /clearcache
*
* @return void
*/
public static function commandClearCache(): void
{
opcache_reset();
$cacheSize = SystemFunctions::convertBytes(\FCCache::getCacheSize());
\FCCache::clearCache();
Telegram::sendChatAction(self::getChatId()); // печатает...
Telegram::execute(self::getChatId(), 'Кэш очищен. Удалено ' . $cacheSize, '', self::getInlineKeyboard(), self::getKeyboard());
}
/**
* Callback очистка кэша
*
* @return void
*/
public static function callbackClearcache(): void
{
$cacheSize = SystemFunctions::convertBytes(\FCCache::getCacheSize());
\FCCache::clearCache();
Telegram::answerCallbackQuery(self::getEventData()['callback_id'], 'Файловый кэш очищен. Удалено ' . $cacheSize, true);
}
/**
* Callback очистка Opcache
*
* @return void
*/
public static function callbackClearOpcache(): void
{
opcache_reset();
Telegram::answerCallbackQuery(self::getEventData()['callback_id'], 'Opcache очищен.', false);
}
}
+323
View File
@@ -0,0 +1,323 @@
<?php
namespace Core\Models;
/**
* Класс для работы с базой данных
*
* @author Roman Grinko <rsgrinko@gmail.com>
*/
class DB
{
/**
* @var object $db Объект базы
*/
public object $db;
private static ?object $instance = null;
/**
* @var int $quantity Количество обращений к базе
*/
public static int $quantity = 0;
/**
* @var int $workingTime Время выполнения запросов
*/
public static int $workingTime = 0;
/**
* ID последней добавленной записи
*
* @var int|null
*/
private ?string $lastInsertId = null;
/**
* Подключение к базе данных
*
* @param string $db_server Сервер
* @param string $db_user Пользователь
* @param string|null $db_pass Пароль
* @param string $db_name База
*/
public function __construct(string $db_server = DB_HOST, string $db_user = DB_USER, ?string $db_pass = DB_PASSWORD, string $db_name = DB_NAME)
{
$dsn = 'mysql:host=' . $db_server . ';dbname=' . $db_name . ';charset=utf8';
$opt = [
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
\PDO::ATTR_EMULATE_PREPARES => false,
];
$this->db = new \PDO($dsn, $db_user, $db_pass, $opt);
}
/**
* Получить объект класса
*
* @return object
*/
public static function getInstance(): object
{
if (empty(self::$instance)) {
self::$instance = new self();
}
return self::$instance;
}
/**
* Вспомогательный метод, формирует WHERE из массива
*
* @param $where
*
* @return string
*/
private function createWhere($where, $logic = 'AND'): string
{
if (!is_array($where)) {
return $where;
}
$where_string = '';
foreach ($where as $where_key => $where_item) {
if (stristr($where_item, '>')) {
$symbol = '>';
$where_item = str_replace($symbol, '', $where_item);
} elseif (stristr($where_item, '<')) {
$symbol = '<';
$where_item = str_replace($symbol, '', $where_item);
} elseif (stristr($where_item, '<=')) {
$symbol = '<=';
$where_item = str_replace($symbol, '', $where_item);
} elseif (stristr($where_item, '>=')) {
$symbol = '>=';
$where_item = str_replace($symbol, '', $where_item);
} else {
$symbol = '=';
}
$where_string = $where_string . ' (' . $where_key . $symbol . '\'' . $where_item . '\') ' . $logic;
}
return substr($where_string, 0, -4);
}
/**
* Вспомогательный метод, формирует SET из массива
*
* @param $set
*
* @return string
*/
private function createSet($set): string
{
if (!is_array($set)) {
return $set;
}
$set_string = '';
foreach ($set as $set_key => $set_item) {
$set_string = $set_string . ' ' . $set_key . '=\'' . $set_item . '\',';
}
return substr($set_string, 0, -1);
}
/**
* Вспомогательный метод для создания строки сортировки
*
* @param $sort
*
* @return string
*/
private function createSort($sort): string
{
$sort_string = '';
if (is_array($sort)) {
foreach ($sort as $k => $v) {
$sort_string = ' ORDER BY ' . $k . ' ' . $v;
}
}
return $sort_string;
}
/**
* Вспомогательный метод для построения запросов
*
* @param $data
* @param string $param
*
* @return string
*/
private function createInsertString($data, $param = 'key'): string
{
$result = '';
foreach ($data as $k => $v) {
if ($param == 'key') {
$result = $result . $k . ', ';
} elseif ($param == 'value') {
$result = $result . '\'' . $v . '\', ';
}
}
return substr($result, 0, -2);
}
/**
* Метод для простого выполнения заданного SQL запроса.
* Возвращает результат в виде массива или объекта, при неудаче возвращает null
*
* @param string $sql SQL запрос
* @param bool $returnObject Вернуть объект после выполнения
*
* @return mixed
*/
public function query(string $sql, bool $returnObject = false)
{
$startTime = microtime(true);
self::$quantity++;
$stmt = $this->db->query($sql);
$this->lastInsertId = $this->db->lastInsertId() ?? null;
$endTime = microtime(true);
self::$workingTime += ($endTime - $startTime);
if ($returnObject) {
return $stmt;
} else {
$result = $stmt->fetchAll();
return $result ?: null;
}
}
/**
* Метод для обновления записи в таблице
* Принимает 3 аргумента: имя таблицы, массив для WHERE и массив значений для обновления (ключ-значение)
*
* @param string $table
* @param array $where
* @param $set
*
* @return array|false
*/
public function update(string $table, $where, $set)
{
self::$quantity++;
$result = $this->query('UPDATE `' . $table . '` SET ' . $this->createSet($set) . ' WHERE ' . $this->createWhere($where));
return (bool)$result;
}
/**
* Получить элемент из базы
*
* @param $table
* @param $where
*
* @return array|null
*/
public function getItem($table, $where): ?array
{
self::$quantity++;
$result = $this->query('SELECT * FROM `' . $table . '` WHERE ' . $this->createWhere($where) . ' LIMIT 1');
if ($result) {
return $result[0];
} else {
return null;
}
}
/**
* Добавить элемент в базу
*
* @param $table
* @param $data
*
* @return int|null
*/
public function addItem($table, $data): ?int
{
self::$quantity++;
$this->query(
'INSERT INTO `' . $table . '` (' . $this->createInsertString($data, 'key') . ') VALUES (' . $this->createInsertString($data, 'value')
. ')'
);
return (int)$this->lastInsertId;
}
/**
* Удалить элемент из базы
*
* @param $table
* @param $where
*
* @return bool
*/
public function remove($table, $where): bool
{
self::$quantity++;
$result = $this->query('DELETE FROM `' . $table . '` WHERE ' . $this->createWhere($where));
return (bool)$result;
}
/**
* Получить элементЫ из базы
*
* @param $table
* @param $where
* @param string $sort
*
* @return array|null
*/
public function getItems($table, $where, $sort = ''): ?array
{
self::$quantity++;
$result = $this->query('SELECT * FROM `' . $table . '` WHERE ' . $this->createWhere($where) . $this->createSort($sort));
if ($result) {
return $result;
} else {
return null;
}
}
/**
* Получить все данные из таблицы
*
* @param $table
* @param string $sort
*
* @return array|null
*/
public function getAll($table, $sort = ''): ?array
{
self::$quantity++;
$result = $this->query('SELECT * FROM `' . $table . '`' . $this->createSort($sort));
if ($result) {
return $result;
} else {
return null;
}
}
/**
* Получение строки из таблицы
*
* @param $table
* @param string $sql
* @param array $params
* @param false $force
*
* @return false|mixed
*/
public function getRow($table, $sql = '', $params = [])
{
self::$quantity++;
$result = $this->query('SELECT * FROM `' . $table . '` ' . $sql . ' LIMIT 1', $params);
if ($result) {
return $result[0];
} else {
return false;
}
}
}
+382
View File
@@ -0,0 +1,382 @@
<?php
/**
* Класс для работы с пользователями
*
* @author Roman Grinko <rsgrinko@gmail.com>
*/
class User
{
/**
* ID текущего пользователя
*
* @var int
*/
public static $id;
/**
* Таблица с пользователями
*
* @var string $table
*/
public static $table;
/**
* @var string $cryptoSalt Соль для шифрования
*/
private static $cryptoSalt = 'BKH92FdiQvEW2aOy0giywXasYAMl0pFvIrlop8Sz';
/**
* Объект базы данных
*
* @var object
*/
public static $DB;
/**
* Инициализация класса
*
* @param object $DB
* @param string $table
*/
public static function init($DB, $table = 'users'): void
{
self::$table = $table;
self::$DB = $DB;
if (isset($_SESSION['authorize']) and $_SESSION['authorize'] == 'Y') {
self::$id = $_SESSION['id'];
}
}
/**
* Получение всех полей пользователя
*
* @param int $id
*
* @return array|bool
*/
public static function getFields($id = false)
{
if (empty($id) or $id === false) {
$id = self::$id;
}
if (is_array($id)) {
$where = $id;
} else {
$where = ['id' => $id];
}
$result = self::$DB->getItem(self::$table, $where);
if ($result) {
return $result;
} else {
return false;
}
}
/**
* Получение всех пользователей панели
*
* @param int $limit
* @param string $sort
*
* @return array
*/
public static function getUsers($limit = 10, $sort = 'ASC')
{
$res = self::$DB->query('SELECT * FROM `' . self::$table . '` ORDER BY `id` ' . $sort . ' LIMIT ' . $limit);
return $res;
}
/**
* Возвращает токен пользователя
*/
public static function getUserToken($userId): string
{
$result = self::$DB->getItem(self::$table, ['id' => $userId]);
if ($result) {
return $result['token'];
} else {
return '';
}
}
/**
* Создание пользовательского токена
*/
public static function createUserToken($userId): string
{
$newToken = self::generateGUID();
self::$DB->update(self::$table, ['id' => $userId], ['token' => $newToken]);
return $newToken;
}
/**
* Генерация GUID
*/
private static function generateGUID(): string
{
$uid = dechex(microtime(true) * 1000) . bin2hex(random_bytes(8));
$guid = vsprintf('RG%s-1000-%s-8%.3s-%s%s%s0', str_split($uid, 4));
return strtoupper($guid);
}
/**
* Проверка существования токена
*
* @param string $token
*
* @return bool
*/
public static function isTokenExists($token): bool
{
$result = self::$DB->getItem(self::$table, ['token' => $token]);
if ($result) {
return true;
} else {
return false;
}
}
/**
* Получение пользователя по токену
*/
public static function getUserByToken($token)
{
$result = self::$DB->getItem(self::$table, ['token' => $token]);
if ($result) {
return $result;
} else {
return false;
}
}
/**
* Проверка пользователя на онлайн
*
* @param $int $id
*/
public static function isOnline($id = false)
{
if (!$id) {
return false;
}
$res = self::$DB->query('SELECT last_active FROM `' . self::$table . '` WHERE id=' . $id);
$last_active = $res[0]['last_active'];
$timeNow = time();
if ($last_active > ($timeNow - USER_ONLINE_TIME)) {
return true;
} else {
return false;
}
}
/**
* Выполняет регистрацию пользователя в системе
*
* @param string $login
* @param string $password
* @param string $level
* @param string $name
* @param string $image
*/
public static function registration($login, $password, $email, $level = 'user', $name = '', $image = ''): void
{
self::$DB->addItem(self::$table,
[
'login' => $login,
'password' => $password,
'access_level' => $level,
'name' => $name,
'image' => $image,
'token' => '',
'email' => $email,
'last_active' => time(),
]
);
$result = self::$DB->getItem(self::$table, ['login' => $login, 'password' => $password]);
self::$id = $result['id'];
$_SESSION['id'] = $result['id'];
$_SESSION['authorize'] = 'Y';
$_SESSION['login'] = $result['login'];
$_SESSION['password'] = $result['password'];
$_SESSION['token'] = $result['token'];
$_SESSION['user'] = $result;
return;
}
/**
* Проверяет логин на существование
*
* @param string $login
*
* @return bool
*/
public static function isUserExists($login): bool
{
$result = self::$DB->getItem(self::$table, ['login' => $login]);
if ($result) {
return true;
} else {
return false;
}
}
/**
* Считает количество пользователей
*
* @return int
*/
public static function countUsers(): int
{
$result = self::$DB->getItems(self::$table, ['id' => '>0']);
if ($result) {
return count($result);
} else {
return 0;
}
}
/**
* Выполняет авторизацию пользователя в системе по ID
*
* @param int $id
*
* @return bool
*/
public static function authorize($id, $remember = false): bool
{
$result = self::$DB->getItem(self::$table, ['id' => $id], true);
if ($result) {
self::$id = $result['id'];
$_SESSION['id'] = $result['id'];
$_SESSION['authorize'] = 'Y';
$_SESSION['login'] = $result['login'];
$_SESSION['password'] = $result['password'];
$_SESSION['token'] = $result['token'];
$_SESSION['user'] = $result;
if ($remember) {
setcookie('userId', $result['id'], time() + 3600 * 24);
setcookie('userLogin', $result['login'], time() + 3600 * 24);
setcookie('token', md5(self::$cryptoSalt . $result['id'] . $result['login'] . $result['password']), time() + 3600 * 24);
}
return true;
} else {
return false;
}
}
/**
* Выполняет авторизацию пользователя в системе по логину и паролю
*
* @param string $login
* @param string $password
*
* @return bool
*/
public static function securityAuthorize($login, $password, $remember = false): bool
{
$result = self::$DB->getItem(self::$table, ['login' => $login, 'password' => $password], true);
if ($result) {
self::$id = $result['id'];
$_SESSION['id'] = $result['id'];
$_SESSION['authorize'] = 'Y';
$_SESSION['login'] = $result['login'];
$_SESSION['password'] = $result['password'];
$_SESSION['token'] = $result['token'];
$_SESSION['user'] = $result;
if ($remember) {
setcookie('userId', $result['id'], time() + 3600 * 24);
setcookie('userLogin', $result['login'], time() + 3600 * 24);
setcookie('token', md5(self::$cryptoSalt . $result['id'] . $result['login'] . $result['password']), time() + 3600 * 24);
}
return true;
} else {
return false;
}
}
/**
* Проверка на пользователя
*
* @return bool
*/
public static function isUser(): bool
{
if (!empty($_COOKIE['userId'])
&& !empty($_COOKIE['userLogin'])
&& self::isUserExists($_COOKIE['userLogin'])) {
$arUser = self::$DB->getItem(self::$table, ['id' => $_COOKIE['userId']]);
if ($_COOKIE['token'] == md5(self::$cryptoSalt . $arUser['id'] . $arUser['login'] . $arUser['password'])) {
if (empty($_SESSION['authorize'])) {
self::authorize($arUser['id']);
}
return true;
}
}
if (!isset($_SESSION['authorize']) or empty($_SESSION['authorize']) or $_SESSION['authorize'] !== 'Y') {
return false;
}
$result = self::$DB->getItem(self::$table, ['login' => $_SESSION['login']]);
if ($result) {
if ($result['password'] == $_SESSION['password']) {
self::$DB->update(self::$table, ['id' => $result['id']], ['last_active' => time()]);
self::$id = $result['id'];
$_SESSION['id'] = $result['id'];
return true;
} else {
return false;
}
} else {
return false;
}
}
/**
* Проверка на админа
*
* @return bool
*/
public static function isAdmin(): bool
{
if (self::isUser()) {
if (self::getFields(self::$id)['access_level'] == 'admin') {
return true;
} else {
return false;
}
} else {
return false;
}
}
/**
* Метод выхода из системы
*/
public static function logout(): void
{
$_SESSION['id'] = '';
$_SESSION['authorize'] = '';
$_SESSION['login'] = '';
$_SESSION['password'] = '';
$_SESSION['token'] = '';
$_SESSION['user'] = '';
setcookie('userId', '', time() - 3600);
setcookie('userLogin', '', time() - 3600);
setcookie('token', '', time() - 3600);
}
}