From 1d6124a975996015c5200d8ab766111587f334d7 Mon Sep 17 00:00:00 2001 From: rsgrinko Date: Fri, 15 Jul 2022 17:32:36 +0300 Subject: [PATCH] =?UTF-8?q?[+]=20=D0=BD=D0=BE=D0=B2=D1=8B=D0=B9=20=D0=BA?= =?UTF-8?q?=D0=BE=D0=BC=D0=B1=D0=B8=D0=BD=D0=B8=D1=80=D0=BE=D0=B2=D0=B0?= =?UTF-8?q?=D0=BD=D0=BD=D1=8B=D0=B9=20=D0=BA=D0=BB=D0=B0=D1=81=D1=81=20?= =?UTF-8?q?=D0=B4=D0=BB=D1=8F=20=D1=80=D0=B0=D0=B1=D0=BE=D1=82=D1=8B=20?= =?UTF-8?q?=D1=81=20=D1=82=D0=B5=D0=BB=D0=B5=D0=B3=D1=80=D0=B0=D0=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/config.php | 8 +- .../Core/ExternalServices/Telegram2.class.php | 384 ++++++++++++++++++ core/partizan.php | 103 ----- telegramHandler.php | 22 + 4 files changed, 413 insertions(+), 104 deletions(-) create mode 100644 core/lib/Core/ExternalServices/Telegram2.class.php delete mode 100644 core/partizan.php create mode 100644 telegramHandler.php diff --git a/core/config.php b/core/config.php index 45115b1..fdfadf9 100644 --- a/core/config.php +++ b/core/config.php @@ -60,13 +60,19 @@ /** * Токен телеграм бота */ - const TELEGRAM_BOT_TOKEN = '5232660453:AAGfMWu6EcRfBGSSURJsEEvGPmAqhCyzYHU'; + //const TELEGRAM_BOT_TOKEN = '5357759725:AAEPGfLRaye1ZOPMBGOrBVCMhz4kE_aecME'; //its + const TELEGRAM_BOT_TOKEN = '5357759725:AAEPGfLRaye1ZOPMBGOrBVCMhz4kE_aecME'; //delta /** * ID чата канала уведомлений в телеграм */ const TELEGRAM_NOTIFICATION_CHANNEL = '-1001714289174'; + /** + * ID чата админа в телеграм + */ + const TELEGRAM_ADMIN_CHAT_ID = '412790359'; + /** * Время, в течении которого считаем пользователя онлайн, сек. */ diff --git a/core/lib/Core/ExternalServices/Telegram2.class.php b/core/lib/Core/ExternalServices/Telegram2.class.php new file mode 100644 index 0000000..e52ba72 --- /dev/null +++ b/core/lib/Core/ExternalServices/Telegram2.class.php @@ -0,0 +1,384 @@ +token = $token; + $this->url = 'https://' . self::BASE_URL . '/bot' . $token . '/'; + return $this; + } + + /** + * Получение информации о канале или группе + * + * @param string $channel Канал + * + * @return array + */ + public function getChat(string $channel): array + { + $channel = str_replace('https://t.me/', '', str_replace('@', '', $channel)); + $response = [ + 'chat_id' => '@' . $channel, + ]; + return $this->setMethod('getChat')->sendRequest($response); + } + + /** + * Установка метода + * + * @param string $method Метод + * + * @return $this + */ + private function setMethod(string $method): self + { + $this->method = $method; + return $this; + } + + /** + * Установка идентификатора чата + * + * @param int $chatId Метод + * + * @return $this + */ + public function setChat(int $chatId): self + { + $this->chatId = $chatId; + return $this; + } + + /** + * Отправка запроса на API Telegram + * + * @param array $response Параметры + * + * @return array + */ + private function sendRequest(array $response): array + { + $ch = curl_init($this->url . $this->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|null $text Текст + * @param bool $isCaption Является ли текст описанием изображения + * + * @return string|null + */ + private function sanitize(?string $text, bool $isCaption = false): ?string + { + if (empty($text)) { + return null; + } + + $text = strip_tags($text, '
');
+            $text = substr(trim($text), 0, $isCaption ? 1024 : 4096);
+            //$text = mb_convert_encoding($text, 'UTF-8', 'UTF-8');
+
+            return $text;
+        }
+
+        /**
+         * Отправка изображения
+         *
+         * @param string      $imagePath Путь до изображения
+         * @param string|null $caption   Подпись
+         *
+         * @return array
+         */
+        public function sendPhoto(string $imagePath, ?string $caption = null): array
+        {
+            $response = [
+                'chat_id'    => $this->chatId,
+                'photo'      => curl_file_create($imagePath),
+                'parse_mode' => 'html',
+            ];
+            if (!empty($caption)) {
+                $response['caption'] = $this->sanitize($caption, true);
+            }
+            return $this->setMethod('sendPhoto')->sendRequest($response);
+        }
+
+        /**
+         * Отправка файла
+         *
+         * @param string $filePath Путь до файла
+         *
+         * @return array
+         */
+        public function sendDocument(string $filePath): array
+        {
+            $response = [
+                'chat_id'  => $this->chatId,
+                'document' => curl_file_create($filePath),
+            ];
+            return $this->setMethod('sendDocument')->sendRequest($response);
+        }
+
+
+        /**
+         * Отправляет координаты с картой
+         *
+         * @param float $latitude  Широта
+         * @param float $longitude Долгота
+         *
+         * @return array
+         */
+        public function sendLocation(float $latitude, float $longitude): array
+        {
+            $response = [
+                'chat_id'   => $this->chatId,
+                'latitude'  => $latitude,
+                'longitude' => $longitude,
+            ];
+            return $this->setMethod('sendLocation')->sendRequest($response);
+        }
+
+
+        /**
+         * Отправка сообщение пользователю в телеграм
+         *
+         * @param string|null $text Текст сообщения
+         *
+         * @return array
+         */
+        public function sendMessage(?string $text): array
+        {
+            $params = [
+                'chat_id'    => $this->chatId,
+                'parse_mode' => 'html',
+                'text'       => $this->sanitize($text),
+            ];
+
+            return $this->setMethod('sendMessage')->sendRequest($params);
+        }
+
+        /**
+         * Инициализация
+         *
+         * @param array|null $data Массив входных данных
+         */
+        public function setRemoteRequest(?array $data): self
+        {
+            $this->data = $data;
+            /** Режим работы - инлайн или прямой */
+            $inlineMode = false;
+
+
+            if (isset($data['edited_message'])) {
+                $this->messageType = 'edited_message';
+            } elseif (isset($data['inline_query'])) {
+                $this->messageType = 'inline_query';
+                $inlineMode        = true;
+            } elseif (isset($data['channel_post'])) {
+                $this->messageType = 'channel_post';
+                $inlineMode        = true;
+            } else {
+                $this->messageType = 'message';
+            }
+
+
+            if ($inlineMode === true) // инлайн режим работы
+            {
+                $this->eventType           = 'inline_query';
+                $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'];                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       // дата сообщения
+
+                if (!empty($data[$this->messageType]['sticker'])) {
+                    $this->eventType        = 'sticker';
+                    $this->event['file_id'] = $data['message']['sticker']['file_id'];
+                    $this->event['emoji']   = $data['message']['sticker']['emoji'] ?: null;
+                } elseif (!empty($data[$this->messageType]['contact'])) {
+                    $this->eventType             = 'contact';
+                    $this->event['phone_number'] = $data[$this->messageType]['contact']['phone_number'];
+                    $this->event['name']         = $data[$this->messageType]['contact']['first_name'] . ' '
+                                                   . $data['message']['contact']['last_name'];
+                } elseif (!empty($data[$this->messageType]['location'])) {
+                    $this->eventType          = 'location';
+                    $this->event['latitude'] = $data[$this->messageType]['location']['latitude'];
+                    $this->event['longitude'] = $data[$this->messageType]['location']['longitude'];
+                } elseif (!empty($data[$this->messageType]['photo'])) {
+                    $this->eventType        = 'photo';
+                    $photo           = array_pop($data[$this->messageType]['photo']);
+                    $this->event['caption'] = $data[$this->messageType]['caption'];                   // Выделим подпись к изображению
+                    $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 файла
+                } elseif (!empty($data[$this->messageType]['document'])) {
+                    $this->eventType        = 'document';
+                    $this->event['caption'] = $data[$this->messageType]['caption'];                   // Выделим подпись к документу
+                    $this->event['file_id'] = $data[$this->messageType]['document']['file_id'];       // id файла
+                } elseif (!empty($data) && isset($data[$this->messageType]['chat']['id']) && $data[$this->messageType]['chat']['id'] !== '') {
+                    $this->eventType        = 'message';
+                    $this->event['message'] = $data[$this->messageType]['text'];                      // Выделим сообщение собеседника (регистр по умолчанию)
+                    $this->event['msg']     = mb_strtolower(
+                        $data[$this->messageType]['text'],
+                        'utf8'
+                    );                                                                                // Выделим сообщение собеседника (нижний регистр)
+
+                    if (substr($this->event['msg'], 0, 1) === '/') {
+                        $this->cmd = substr($this->event['msg'], 1);
+                    } else {
+                        $this->cmd = $this->event['msg'];
+                    }
+
+                    // разбиваем запрос на непосредственно команду и ее аргументы
+                    $arParams  = explode(' ', $this->cmd);
+                    $this->cmd = $arParams[0]; // основная команда
+                    unset($arParams[0]);
+                    if (!empty($arParams)) {
+                        $this->params = implode(' ', $arParams);
+                    }
+                } elseif (!empty($data) && isset($data['callback_query']['from']['id']) and $data['callback_query']['from']['id'] !== '') {
+                    $this->eventType            = 'callback';
+                    $this->event['callback_id'] = $this->eventChatId = (int)$data['callback_query']['id'];                    // идентификатор callback
+                    $this->event['chat_id']     = $this->eventChatId = (int)$data['callback_query']['message']['chat']['id']; // идентификатор чата
+                    $this->event['user_id']     = $data['callback_query']['from']['id'];                                      // идентификатор пользователя
+                    $this->event['username']    = $data['callback_query']['from']['username'];                                // username пользователя
+                    $this->event['first_name']  = $data['callback_query']['from']['first_name'];                              // имя собеседника
+                    $this->event['last_name']   = $data['callback_query']['from']['last_name'];                               // фамилию собеседника
+                    $this->event['chat_time']   = $data['callback_query']['message']['date'];                                 // дата сообщения
+                    $this->event['data']        = json_decode(
+                        $data['callback_query']['data'],
+                        true
+                    );                                                                                                   // Содержимое callback запроса
+                    $this->cmd                  = $this->event['data']['method'];
+                } else {
+                    $this->eventType = null;
+                }
+            }
+            return $this;
+        }
+
+        /**
+         * Получение общего типа текущего события
+         *
+         * @return string|null
+         */
+        public function getEventType(): ?string
+        {
+            return $this->eventType;
+        }
+
+
+        /**
+         * Получение конкретного типа
+         *
+         * @return string|null
+         */
+        public function getMessageType(): ?string
+        {
+            return $this->messageType;
+        }
+
+        /**
+         * Получить собранные данные по текущему событию
+         *
+         * @return array|null
+         */
+        public function getEventData(): ?array
+        {
+            return $this->event;
+        }
+
+        /**
+         * Получить id чата, породившего событие
+         *
+         * @return int|null
+         */
+        public function getEventChatId(): ?int
+        {
+            return $this->eventChatId;
+        }
+
+        /**
+         * Получить текущую команду
+         *
+         * @return string
+         */
+        public function getCommand(): string
+        {
+            return $this->cmd;
+        }
+
+        /**
+         * Получить агрументы запроса
+         *
+         * @return ?string
+         */
+        public function getParams(): ?string
+        {
+            return $this->params;
+        }
+    }
\ No newline at end of file
diff --git a/core/partizan.php b/core/partizan.php
deleted file mode 100644
index 2b8de05..0000000
--- a/core/partizan.php
+++ /dev/null
@@ -1,103 +0,0 @@
-
-     * 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.
-     */
-    if (count($argv) < 2) {
-        die('Не выбрано действие. Для справки наберите php -f partizan.php -?' . PHP_EOL);
-    }
-    switch ($argv[1]) {
-        case 'migrate':
-            define('DB_HOST', 'localhost');
-            define('DB_USER', 'rsgrinko_delta');
-            define('DB_PASSWORD', '2670135');
-            define('DB_NAME', 'rsgrinko_delta');
-            define('DB_TABLE_VERSIONS', 'versions');
-
-            function connectDB()
-            {
-                $errorMessage = 'Невозможно подключиться к серверу базы данных';
-                $conn         = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
-                if (!$conn) {
-                    throw new Exception($errorMessage);
-                } else {
-                    $query = $conn->query('set names utf8');
-                    if (!$query) {
-                        throw new Exception($errorMessage);
-                    } else {
-                        return $conn;
-                    }
-                }
-            }
-
-            function getMigrationFiles($conn)
-            {
-                $sqlFolder = 'migrations/';
-                $allFiles  = glob($sqlFolder . '*.sql');
-
-                $query          = sprintf('show tables from `%s` like "%s"', DB_NAME, DB_TABLE_VERSIONS);
-                $data           = $conn->query($query);
-                $firstMigration = !$data->num_rows;
-
-                if ($firstMigration) {
-                    return $allFiles;
-                }
-
-                $versionsFiles = [];
-                $query         = sprintf('select `name` from `%s`', DB_TABLE_VERSIONS);
-                $data          = $conn->query($query)->fetch_all(MYSQLI_ASSOC);
-                foreach ($data as $row) {
-                    array_push($versionsFiles, $sqlFolder . $row['name']);
-                }
-                return array_diff($allFiles, $versionsFiles);
-            }
-
-
-            function migrate($conn, $file)
-            {
-                $command = sprintf('mysql -u%s -p%s -h %s -D %s < %s', DB_USER, DB_PASSWORD, DB_HOST, DB_NAME, $file);
-                shell_exec($command);
-                $baseName = basename($file);
-                $query    = sprintf('insert into `%s` (`name`) values("%s")', DB_TABLE_VERSIONS, $baseName);
-                $conn->query($query);
-            }
-
-            $conn  = connectDB();
-            $files = getMigrationFiles($conn);
-            if (empty($files)) {
-                echo 'Ваша база данных в актуальном состоянии.';
-            } else {
-                echo 'Начинаем миграцию...' . PHP_EOL;
-
-                // Накатываем миграцию для каждого файла
-                foreach ($files as $file) {
-                    migrate($conn, $file);
-                    // Выводим название выполненного файла
-                    echo basename($file) . PHP_EOL;
-                }
-
-                echo PHP_EOL . 'Миграция завершена.';
-            }
-
-
-            break;
-        default:
-            echo 'Неизвестная команда' . PHP_EOL;
-            break;
-    }
\ No newline at end of file
diff --git a/telegramHandler.php b/telegramHandler.php
new file mode 100644
index 0000000..1214740
--- /dev/null
+++ b/telegramHandler.php
@@ -0,0 +1,22 @@
+setRemoteRequest($data);
+
+    $tg->setChat(TELEGRAM_ADMIN_CHAT_ID)->sendMessage(print_r($tg->getChat('bitrix'), true));
+  //$tg->setChat(TELEGRAM_ADMIN_CHAT_ID)->sendLocation( '54.007143', '38.046204');
+
+
+   // sendTelegram(print_r($data, true));
\ No newline at end of file