diff --git a/core/config.php b/core/config.php index fdfadf9..15183a3 100644 --- a/core/config.php +++ b/core/config.php @@ -24,6 +24,11 @@ */ const CORE_VERSION = '1.0.0_dev'; + /** + * Флаг отладки + */ + const DEBUG = true; + /** * Путь до корня проекта */ @@ -81,7 +86,7 @@ /** * Использование кэша */ - const USE_CACHE = true; + const USE_CACHE = false; /** * Папка кэша diff --git a/core/lib/Core/ExternalServices/Telegram2.class.php b/core/lib/Core/ExternalServices/Telegram2.class.php index b3a4759..140a7ea 100644 --- a/core/lib/Core/ExternalServices/Telegram2.class.php +++ b/core/lib/Core/ExternalServices/Telegram2.class.php @@ -2,6 +2,8 @@ namespace Core\ExternalServices; + use Core\CoreException; + class Telegram2 { /** @var int|null $chatId Идентификатор чата для запросов */ @@ -16,7 +18,6 @@ /** Базовый адрес для запросов */ const BASE_URL = 'api.telegram.org'; - /** @var string Текущая команда */ private string $cmd; @@ -48,7 +49,6 @@ */ public function __construct(string $token = TELEGRAM_BOT_TOKEN) { - //$this->token = $token; $this->url = 'https://' . self::BASE_URL . '/bot' . $token . '/'; return $this; } @@ -62,11 +62,11 @@ */ public function getChat(string $channel): array { - $channel = str_replace('https://t.me/', '', str_replace('@', '', $channel)); - $response = [ + $channel = str_replace('https://t.me/', '', str_replace('@', '', $channel)); + $request = [ 'chat_id' => '@' . $channel, ]; - return $this->setMethod('getChat')->sendRequest($response); + return $this->setMethod('getChat')->sendRequest($request); } /** @@ -98,21 +98,26 @@ /** * Отправка запроса на API Telegram * - * @param array $response Параметры + * @param array $request Параметры * * @return array + * @throws CoreException */ - private function sendRequest(array $response): array + private function sendRequest(array $request): array { $ch = curl_init($this->url . $this->method); curl_setopt($ch, CURLOPT_POST, 1); - curl_setopt($ch, CURLOPT_POSTFIELDS, $response); + curl_setopt($ch, CURLOPT_POSTFIELDS, $request); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HEADER, false); $res = curl_exec($ch); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); - return json_decode($res, true); + $res = json_decode($res, true); + if (empty($res) || $res['ok'] !== true) { + throw new CoreException($res['description'], $res['error_code']); + } + return $res; } /** @@ -143,15 +148,16 @@ * @param string $text * * @return array + * @throws CoreException */ public function updateMessage(int $messageId, string $text): array { - $response = [ + $request = [ 'chat_id' => $this->chatId, 'message_id' => $messageId, 'text' => $text, ]; - return $this->setMethod('editMessageText')->sendRequest($response); + return $this->setMethod('editMessageText')->sendRequest($request); } /** @@ -161,18 +167,19 @@ * @param string|null $caption Подпись * * @return array + * @throws CoreException */ public function sendPhoto(string $imagePath, ?string $caption = null): array { - $response = [ + $request = [ 'chat_id' => $this->chatId, 'photo' => curl_file_create($imagePath), 'parse_mode' => 'html', ]; if (!empty($caption)) { - $response['caption'] = $this->sanitize($caption, true); + $request['caption'] = $this->sanitize($caption, true); } - return $this->setMethod('sendPhoto')->sendRequest($response); + return $this->setMethod('sendPhoto')->sendRequest($request); } /** @@ -181,14 +188,15 @@ * @param string $filePath Путь до файла * * @return array + * @throws CoreException */ public function sendDocument(string $filePath): array { - $response = [ + $request = [ 'chat_id' => $this->chatId, 'document' => curl_file_create($filePath), ]; - return $this->setMethod('sendDocument')->sendRequest($response); + return $this->setMethod('sendDocument')->sendRequest($request); } @@ -199,15 +207,16 @@ * @param float $longitude Долгота * * @return array + * @throws CoreException */ public function sendLocation(float $latitude, float $longitude): array { - $response = [ + $request = [ 'chat_id' => $this->chatId, 'latitude' => $latitude, 'longitude' => $longitude, ]; - return $this->setMethod('sendLocation')->sendRequest($response); + return $this->setMethod('sendLocation')->sendRequest($request); } @@ -217,20 +226,21 @@ * @param string|null $text Текст сообщения * * @return array + * @throws CoreException */ public function sendMessage(?string $text): array { - $params = [ + $request = [ 'chat_id' => $this->chatId, 'parse_mode' => 'html', 'text' => $this->sanitize($text), ]; - return $this->setMethod('sendMessage')->sendRequest($params); + return $this->setMethod('sendMessage')->sendRequest($request); } /** - * Инициализация + * Установка параметров клиентского запроса * * @param array|null $data Массив входных данных */ @@ -260,17 +270,17 @@ $this->event['id'] = $data[$this->messageType]['id']; $this->event['query'] = $data[$this->messageType]['query']; $this->event['offset'] = $data[$this->messageType]['offset']; - $this->event['user_id'] = $data[$this->messageType]['from']['id']; // идентификатор пользователя - $this->event['username'] = $data[$this->messageType]['from']['username']; // username пользователя - $this->event['first_name'] = $data[$this->messageType]['from']['first_name']; // имя собеседника - $this->event['last_name'] = $data[$this->messageType]['from']['last_name']; // фамилию собеседника - } else { // прямой режим работы - $this->event['chat_id'] = $this->eventChatId = (int)$data[$this->messageType]['chat']['id']; // идентификатор чата - $this->event['user_id'] = $data[$this->messageType]['from']['id']; // идентификатор пользователя - $this->event['username'] = $data[$this->messageType]['from']['username']; // username пользователя - $this->event['first_name'] = $data[$this->messageType]['chat']['first_name']; // имя собеседника - $this->event['last_name'] = $data[$this->messageType]['chat']['last_name']; // фамилию собеседника - $this->event['chat_time'] = $data[$this->messageType]['date']; // дата сообщения + $this->event['user_id'] = $data[$this->messageType]['from']['id']; // идентификатор пользователя + $this->event['username'] = $data[$this->messageType]['from']['username']; // username пользователя + $this->event['first_name'] = $data[$this->messageType]['from']['first_name']; // имя собеседника + $this->event['last_name'] = $data[$this->messageType]['from']['last_name']; // фамилию собеседника + } else { // прямой режим работы + $this->event['chat_id'] = $this->eventChatId = (int)$data[$this->messageType]['chat']['id']; // идентификатор чата + $this->event['user_id'] = $data[$this->messageType]['from']['id']; // идентификатор пользователя + $this->event['username'] = $data[$this->messageType]['from']['username']; // username пользователя + $this->event['first_name'] = $data[$this->messageType]['chat']['first_name']; // имя собеседника + $this->event['last_name'] = $data[$this->messageType]['chat']['last_name']; // фамилию собеседника + $this->event['chat_time'] = $data[$this->messageType]['date']; // дата сообщения if (!empty($data[$this->messageType]['sticker'])) { $this->eventType = 'sticker'; @@ -292,7 +302,7 @@ $this->event['file_id'] = $photo['file_id']; // id файла } elseif (!empty($data[$this->messageType]['voice'])) { $this->eventType = 'voice'; - $this->event['file_id'] = $data[$this->messageType]['voice']['file_id']; // id файла + $this->event['file_id'] = $data[$this->messageType]['voice']['file_id']; // id файла } elseif (!empty($data[$this->messageType]['document'])) { $this->eventType = 'document'; $this->event['caption'] = $data[$this->messageType]['caption']; // Выделим подпись к документу diff --git a/core/lib/Core/Models/DB.class.php b/core/lib/Core/Models/DB.class.php index 10ff937..06aac1e 100644 --- a/core/lib/Core/Models/DB.class.php +++ b/core/lib/Core/Models/DB.class.php @@ -191,7 +191,7 @@ if ($param == 'key') { $result = $result . $k . ', '; } elseif ($param == 'value') { - $result = $result . '\'' . $v . '\', '; + $result = $result . '\'' . addslashes($v) . '\', '; } } return substr($result, 0, -2); @@ -214,7 +214,12 @@ $stmt = $this->db->query($sql); } catch (\Throwable $t) { sendTelegram('SQL ERROR: ' . $sql); - throw new CoreException('В SQL запросе произошла ошибка', CoreException::ERROR_SQL_QUERY); + if(DEBUG) { + throw new CoreException('В SQL запросе произошла ошибка. Запрос: ' . $sql, CoreException::ERROR_SQL_QUERY); + } else { + throw new CoreException('В SQL запросе произошла ошибка', CoreException::ERROR_SQL_QUERY); + } + } $this->lastInsertId = $this->db->lastInsertId() ?? null; diff --git a/core/lib/Core/Models/Roles.class.php b/core/lib/Core/Models/Roles.class.php index c8c4f1d..61b27fc 100644 --- a/core/lib/Core/Models/Roles.class.php +++ b/core/lib/Core/Models/Roles.class.php @@ -106,7 +106,7 @@ * * @return int|null */ - public function removeRole(int $roleId): ?int + public function deleteRole(int $roleId): ?int { $cacheId = md5('Roles_' . $this->user->getId() . '_getRoles'); Cache::delete($cacheId); @@ -133,6 +133,7 @@ * Получение всех существующих ролей * * @return array|null + * @throws \Core\CoreException */ public static function getAllRoles(): ?array { diff --git a/core/lib/Core/Models/User.class.php b/core/lib/Core/Models/User.class.php index 47acd28..6234dab 100644 --- a/core/lib/Core/Models/User.class.php +++ b/core/lib/Core/Models/User.class.php @@ -26,7 +26,7 @@ namespace Core\Models; use Core\CoreException; - use Core\Models\{DB, Roles}; + use Core\Models\{DB, Roles, UserMeta}; use Core\Helpers\{Cache, Log, SystemFunctions}; class User @@ -46,6 +46,13 @@ */ public $rolesObject = null; + /** + * Объект мета данных + * + * @var Roles + */ + public $metaObject = null; + /** * Таблица с пользователями */ @@ -574,6 +581,19 @@ return $this->rolesObject; } + /** + * Получить объект для работы с ролями + * + * @return UserMeta + */ + public function getMetaObject(): UserMeta + { + if (empty($this->metaObject)) { + $this->metaObject = (new UserMeta($this)); + } + return $this->metaObject; + } + /** * Экспорт всех данных из таблицы пользователей * diff --git a/core/lib/Core/Models/UserMeta.class.php b/core/lib/Core/Models/UserMeta.class.php new file mode 100644 index 0000000..d9da7e8 --- /dev/null +++ b/core/lib/Core/Models/UserMeta.class.php @@ -0,0 +1,160 @@ +user = $user; + } + + /** + * Получение ролей пользователя + * + * @return array + * @throws \Core\CoreException + */ + public function getAllMeta(): array + { + $cacheId = md5('Meta_' . $this->user->getId() . '_getAllMeta'); + if (Cache::check($cacheId)) { + $userMeta = Cache::get($cacheId); + } else { + /** @var $DB DB */ + $DB = DB::getInstance(); + + $res = $DB->query('SELECT * FROM `' . self::TABLE . '` WHERE user_id=' . $this->user->getId()); + $userMeta = []; + if (!empty($res)) { + foreach ($res as $meta) { + $userMeta[] = [ + 'id' => $meta['id'], + 'type' => $meta['type'], + 'name' => $meta['name'], + 'value' => $meta['value'], + ]; + } + } + Cache::set($cacheId, $userMeta); + } + return $userMeta; + } + + /** + * Получает указанные мета данные пользователя + * + * @param string $name Имя мета + * + * @return array|null + * @throws \Core\CoreException + */ + public function getMetaByName(string $name): ?array + { + $cacheId = md5('Meta_' . $this->user->getId() . '_getMetaByName'); + if (Cache::check($cacheId)) { + $userMeta = Cache::get($cacheId); + } else { + /** @var $DB DB */ + $DB = DB::getInstance(); + $res = $DB->query('SELECT * FROM `' . self::TABLE . '` WHERE user_id=' . $this->user->getId() . ' AND name="' . $name . '"'); + if (!empty($res)) { + $userMeta = []; + foreach ($res as $meta) { + $userMeta[] = [ + 'id' => $meta['id'], + 'type' => $meta['type'], + 'name' => $meta['name'], + 'value' => $meta['value'], + ]; + } + Cache::set($cacheId, $userMeta); + } + } + return $userMeta; + } + + /** + * Получает указанные мета данные пользователя + * + * @param string|null $type Тип мета + * + * @return array|null + * @throws \Core\CoreException + */ + public function getMetaByType(string $type): ?array + { + $cacheId = md5('Meta_' . $this->user->getId() . '_getMetaByType'); + if (Cache::check($cacheId)) { + $userMeta = Cache::get($cacheId); + } else { + /** @var $DB DB */ + $DB = DB::getInstance(); + $res = $DB->query('SELECT * FROM `' . self::TABLE . '` WHERE user_id=' . $this->user->getId() . ' AND type="' . $type . '"'); + if (!empty($res)) { + $userMeta = []; + foreach ($res as $meta) { + $userMeta[] = [ + 'id' => $meta['id'], + 'type' => $meta['type'], + 'name' => $meta['name'], + 'value' => $meta['value'], + ]; + } + Cache::set($cacheId, $userMeta); + } + } + return $userMeta; + } + + /** + * Добавляет пользователю указанные мета данные + * + * @param string $name Имя мета + * @param string|null $value Значение мета + * @param string $type + * + * @return int|null + * @throws \Core\CoreException + */ + public function addMeta(string $name, ?string $value = null, string $type = 'default'): ?int + { + $cacheId = md5('Meta_' . $this->user->getId() . '_getAllMeta'); + Cache::delete($cacheId); + + /** @var $DB DB */ + $DB = DB::getInstance(); + return $DB->addItem(self::TABLE, ['user_id' => $this->user->getId(), 'name' => $name, 'value' => $value, 'type' => $type]); + } + + + /** + * Убирает пользователю указанные мета данные + * + * @param string $name Имя мета + * + * @return int|null + * @throws \Core\CoreException + */ + public function deleteMeta(string $name): void + { + $cacheId = md5('Roles_' . $this->user->getId() . '_getRoles'); + Cache::delete($cacheId); + + /** @var $DB DB */ + $DB = DB::getInstance(); + $DB->query('DELETE FROM ' . self::TABLE . ' WHERE user_id=' . $this->user->getId() . ' AND name="' . $name . '"'); + } + } \ No newline at end of file diff --git a/core/lib/Panel.class.php b/core/lib/Panel.class.php deleted file mode 100644 index 7e462b9..0000000 --- a/core/lib/Panel.class.php +++ /dev/null @@ -1,37 +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. - */ - - namespace Core; - - class Panel - { - public static function index() - { - global $twig; - $navbarItems = [ - ['name' => 'Главная', 'url' => '/', 'active' => true], - ['name' => 'Админка', 'url' => '/admin', 'active' => false], - ['name' => 'Командная PHP строка', 'url' => '/phpcmd.php', 'active' => false], - ['name' => 'Тест', 'url' => '/test', 'active' => false], - ]; - echo $twig->render('admin/index.twig', ['navbarItems' => $navbarItems, 'name' => 'Roman Grinko']); - } - } \ No newline at end of file