Этап 0 рефакторинга: гигиена репозитория и вынос секретов
Удалено: - admin/phpcmd.php — веб-консоль выполнения произвольного PHP-кода, вместе с пунктом меню и скриншотом в README - скретч-файлы из корня docroot: test.php, testMvc.php, testWait.php, webApp.php, meshtasticForward.php, composer.phar - мёртвый код: TelegramActions, Telegram, RequestOLD, Helpers/Cache/Cache, index_lll.twig, test.twig, маршруты /test и метод App::test() Конфигурация: - реквизиты БД, токен бота и CRYPTO_KEY вынесены в config.local.php вне git, добавлен шаблон config.local.example.php - CRYPTO_KEY переведён из const в define: как const он не мог быть переопределён локальным конфигом - при отсутствии реквизитов приложение падает сразу с понятным текстом - phinx.php читает реквизиты оттуда же, исправлен путь к сидам - Twig debug и cache завязаны на DEBUG вместо жёсткого debug => true - в composer.json зафиксировано требование php >= 8.4 Прочее: - .idea снят с отслеживания: в публичном репозитории были внутренние адреса окружения и путь к docroot - db/cleanup/2026-08-14_stage0.sql — чистка сниппетов удалённой консоли и пустых таблиц test__table Проверено: php -l, phpunit, сверка ответов всех маршрутов с состоянием до изменений.
This commit is contained in:
1 parent
8a54b4f029
commit
9933803f36
30 files changed
+191
-1816
No files matched your search
+5
-3
@@ -164,10 +164,12 @@
|
||||
*/
|
||||
$loader = new \Twig\Loader\FilesystemLoader(PATH_TO_TEMPLATES);
|
||||
$twig = new \Twig\Environment($loader, [
|
||||
'debug' => true,
|
||||
//'cache' => CACHE_DIR,
|
||||
'debug' => DEBUG,
|
||||
'cache' => DEBUG ? false : CACHE_DIR . '/twig',
|
||||
]);
|
||||
$twig->addExtension(new \Twig\Extension\DebugExtension());
|
||||
if (DEBUG) {
|
||||
$twig->addExtension(new \Twig\Extension\DebugExtension());
|
||||
}
|
||||
require_once __DIR__ . '/routes.php';
|
||||
Router::execute();
|
||||
die();
|
||||
|
||||
Vendored
Whitespace-only changes.
+32
-8
@@ -99,19 +99,21 @@
|
||||
}
|
||||
|
||||
/**
|
||||
* Параметры SQL базы
|
||||
* Параметры SQL базы.
|
||||
* Реквизиты доступа задаются в config.local.php (вне git), здесь только безопасные значения
|
||||
* по умолчанию. Шаблон окружения — config.local.example.php.
|
||||
*/
|
||||
if (!defined('DB_HOST')) {
|
||||
define('DB_HOST', 'localhost');
|
||||
}
|
||||
if (!defined('DB_USER')) {
|
||||
define('DB_USER', 'delta');
|
||||
define('DB_USER', '');
|
||||
}
|
||||
if (!defined('DB_PASSWORD')) {
|
||||
define('DB_PASSWORD', '2670135');
|
||||
define('DB_PASSWORD', '');
|
||||
}
|
||||
if (!defined('DB_NAME')) {
|
||||
define('DB_NAME', 'delta');
|
||||
define('DB_NAME', '');
|
||||
}
|
||||
if (!defined('DB_TABLE_PREFIX')) {
|
||||
define('DB_TABLE_PREFIX', 'd_');
|
||||
@@ -132,10 +134,10 @@
|
||||
}
|
||||
|
||||
/**
|
||||
* Токен телеграм бота
|
||||
* Токен телеграм бота. Задаётся в config.local.php.
|
||||
*/
|
||||
if (!defined('TELEGRAM_BOT_TOKEN')) {
|
||||
define('TELEGRAM_BOT_TOKEN', '5357759725:AAEPGfLRaye1ZOPMBGOrBVCMhz4kE_aecME'); //delta
|
||||
define('TELEGRAM_BOT_TOKEN', '');
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -191,9 +193,13 @@
|
||||
const CODE_VALUE_N = 'N';
|
||||
|
||||
/**
|
||||
* Ключ шифрования
|
||||
* Ключ шифрования. Задаётся в config.local.php.
|
||||
* Объявлен через define(), а не const, чтобы значение из config.local.php имело приоритет:
|
||||
* const в глобальной области переопределить нельзя.
|
||||
*/
|
||||
const CRYPTO_KEY ='642a43f13133ea61cb6315bf46c89cd26346bd7b2cda43cee6d17b4a733854639b22b7688582b3cc';
|
||||
if (!defined('CRYPTO_KEY')) {
|
||||
define('CRYPTO_KEY', '');
|
||||
}
|
||||
|
||||
/**
|
||||
* Флаг использования логирования
|
||||
@@ -234,3 +240,21 @@
|
||||
* Формат даты/времени
|
||||
*/
|
||||
const DATETIME_FORMAT = 'Y-m-d H:i:s';
|
||||
|
||||
/**
|
||||
* Проверка обязательных реквизитов окружения.
|
||||
* Без config.local.php приложение не поднимется, поэтому падаем сразу и с понятным текстом,
|
||||
* а не невнятной ошибкой подключения к базе где-то в глубине запроса.
|
||||
*/
|
||||
if (DB_USER === '' || DB_NAME === '') {
|
||||
$configErrorMessage = 'Не заданы реквизиты доступа к базе данных. '
|
||||
. 'Создайте файл config.local.php в корне проекта по образцу config.local.example.php.';
|
||||
|
||||
if (PHP_SAPI === 'cli') {
|
||||
fwrite(STDERR, $configErrorMessage . PHP_EOL);
|
||||
} else {
|
||||
http_response_code(500);
|
||||
echo $configErrorMessage;
|
||||
}
|
||||
die(1);
|
||||
}
|
||||
@@ -276,13 +276,6 @@
|
||||
]);
|
||||
}
|
||||
|
||||
public static function test($a = null, $b = null, $c = null, $d = null)
|
||||
{
|
||||
ddd($_SESSION);
|
||||
print_r([$a, $b, $c, $d]);
|
||||
self::render('test.twig');
|
||||
}
|
||||
|
||||
public static function logout()
|
||||
{
|
||||
Captcha::clearSession();
|
||||
|
||||
@@ -1,181 +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\ExternalServices;
|
||||
|
||||
use Core\CoreException;
|
||||
|
||||
class RequestOLD
|
||||
{
|
||||
private $httpStatus = null;
|
||||
|
||||
private $httpCode = null;
|
||||
|
||||
private $maxRedirects = 2;
|
||||
|
||||
private $requestHeaders = [];
|
||||
|
||||
/**
|
||||
* @var false|string
|
||||
*/
|
||||
private $responseBody = null;
|
||||
|
||||
private $responseHeader = null;
|
||||
|
||||
private $timeout = 5;
|
||||
|
||||
/**
|
||||
* @return string|null
|
||||
*/
|
||||
public function getResponseBody(): ?string
|
||||
{
|
||||
return $this->responseBody;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return null
|
||||
*/
|
||||
public function getResponseHeader()
|
||||
{
|
||||
return $this->responseHeader;
|
||||
}
|
||||
|
||||
private $usertAgent = null;
|
||||
|
||||
private $requestType = null;
|
||||
|
||||
private $url = null;
|
||||
|
||||
private $params = [];
|
||||
|
||||
private $referer = '';
|
||||
|
||||
private $usePostMethod = false;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
}
|
||||
|
||||
public function setUrl(?string $url): self
|
||||
{
|
||||
$this->url = $url;
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function post(): self
|
||||
{
|
||||
$this->usePostMethod = true;
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function get(): self
|
||||
{
|
||||
$this->usePostMethod = true;
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function setParams(?array $params = null): self
|
||||
{
|
||||
$this->params = $params ?: [];
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function setHeaders(?array $arHeaders = null): self
|
||||
{
|
||||
$this->requestHeaders = $arHeaders ?: [];
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function setTimeout(int $timeout): self
|
||||
{
|
||||
$this->timeout = $timeout;
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function setMaxRedirects(int $redirects): self
|
||||
{
|
||||
$this->maxRedirects = $redirects;
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
public function setReferer(?string $referer = null): self
|
||||
{
|
||||
$this->referer = $referer ?: '';
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function setUserAgent(?string $userAgent = null): self
|
||||
{
|
||||
$this->userAgent = $userAgent ?: '';
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getCode(): ?int
|
||||
{
|
||||
return $this->httpCode;
|
||||
}
|
||||
|
||||
public function send()
|
||||
{
|
||||
$res = $this->sendRequest();
|
||||
return $res;
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws CoreException
|
||||
*/
|
||||
private function sendRequest(): ?string
|
||||
{
|
||||
if (empty($this->url)) {
|
||||
throw new ExternalServicesException('Адрес запроса не задан');
|
||||
}
|
||||
|
||||
if ($this->usePostMethod === true) {
|
||||
$ch = curl_init($this->url);
|
||||
curl_setopt($ch, CURLOPT_POST, 1);
|
||||
curl_setopt($ch, CURLOPT_POSTFIELDS, $this->params);
|
||||
} else {
|
||||
$ch = curl_init($this->url . '?' . http_build_query($this->params));
|
||||
}
|
||||
|
||||
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
|
||||
curl_setopt($ch, CURLOPT_HEADER, false);
|
||||
curl_setopt($ch, CURLOPT_REFERER, $this->referer);
|
||||
curl_setopt($ch, CURLOPT_TIMEOUT, $this->timeout);
|
||||
curl_setopt($ch, CURLOPT_MAXREDIRS, $this->maxRedirects);
|
||||
curl_setopt($ch, CURLOPT_USERAGENT, $this->usertAgent);
|
||||
curl_setopt($ch, CURLOPT_HTTPHEADER, $this->requestHeaders);
|
||||
curl_setopt($ch, CURLOPT_HEADER, 1);
|
||||
|
||||
$res = curl_exec($ch);
|
||||
|
||||
$headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
|
||||
|
||||
$this->responseHeader = substr($res, 0, $headerSize);
|
||||
$this->responseBody = substr($res, $headerSize);
|
||||
|
||||
$this->httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
||||
|
||||
curl_close($ch);
|
||||
return $res;
|
||||
}
|
||||
}
|
||||
@@ -1,375 +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.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Класс для работы с 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 int $chatId
|
||||
* @param int $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);
|
||||
}
|
||||
}
|
||||
@@ -1,396 +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.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Класс-обработчик команд 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>';
|
||||
}*/
|
||||
//ChatGPT connect...
|
||||
$gptObject = new ChatGPT();
|
||||
Telegram::sendChatAction(self::getChatId()); // печатает...
|
||||
//Telegram::execute(self::getChatId(), $message, '', self::getInlineKeyboard(), self::getKeyboard());
|
||||
Telegram::execute(self::getChatId(), htmlspecialchars($gptObject->ask($name)), '', 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()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,77 +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\Helpers\Cache;
|
||||
|
||||
/**
|
||||
* Класс для кэширования данных и работы с кэшэм
|
||||
*/
|
||||
class Cache
|
||||
{
|
||||
/** @var string[] AVAILABLE_DRIVERS Поддерживаемые драйверы */
|
||||
public const AVAILABLE_DRIVERS = [
|
||||
'FileCacheDriver',
|
||||
'MemCacheDriver',
|
||||
];
|
||||
|
||||
/** @var string DEFAULT_DRIVER Драйвер по умолчанию */
|
||||
public const DEFAULT_DRIVER = 'FileCacheDriver';
|
||||
|
||||
/** @var array|null $configParams Параметры */
|
||||
private static ?array $configParams = null;
|
||||
|
||||
/** @var self|null $this|null $currentObject Объект текущего класса */
|
||||
private static ?self $currentObject = null;
|
||||
|
||||
/** @var string|null $driver Драйвер */
|
||||
private ?string $driver = null;
|
||||
|
||||
/**
|
||||
* Инициализация кеша
|
||||
*
|
||||
* @param array $configParams Параметры
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public static function init(array $configParams): void
|
||||
{
|
||||
self::$configParams = $configParams;
|
||||
}
|
||||
public static function getInstance(): self
|
||||
{
|
||||
if (self::$currentObject === null) {
|
||||
self::$currentObject = new static(self::$configParams);
|
||||
}
|
||||
|
||||
return self::$currentObject;
|
||||
}
|
||||
|
||||
/**
|
||||
* Конструктор
|
||||
*
|
||||
* @param array|null $configParams Параметры
|
||||
*/
|
||||
private function __construct(?array $configParams)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -49,12 +49,3 @@
|
||||
Router::route('/profile/password', '\Core\App::profileUpdatePassword');
|
||||
Router::route('/profile/avatar', '\Core\App::profileUpdateAvatar');
|
||||
Router::route('/profile/resend-verification', '\Core\App::profileResendVerification');
|
||||
|
||||
|
||||
Router::route('/test', '\Core\App::test', true);
|
||||
Router::route('/test/(\d+)', '\Core\App::test');
|
||||
Router::route('/test/(\d+)/page/(\d+)', '\Core\App::test');
|
||||
|
||||
Router::route('blog/(\w+)/(\d+)', function ($category, $id) {
|
||||
echo $category . ':' . $id;
|
||||
});
|
||||
Reference in new issue
Block a user