diff --git a/.gitignore b/.gitignore index 57872d0..83cf55e 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,25 @@ /vendor/ + +# Настройки IDE (содержат внутренние адреса и пути окружения) +/.idea/ + +# Локальная конфигурация и секреты — не коммитим никогда +/config.local.php +/.env + +# Загружаемый пользователями контент (файлы из репозитория остаются отслеживаемыми) +/uploads/* +!/uploads/.htaccess +!/uploads/*.png + +# Кэш ядра +/core/cache/* +!/core/cache/.gitkeep + +# Логи ядра (index.php-заглушка остаётся) +/core/log/* +!/core/log/index.php + +# Локальные утилиты и черновики +/composer.phar +/_scratch/ diff --git a/.idea/.gitignore b/.idea/.gitignore deleted file mode 100644 index 13566b8..0000000 --- a/.idea/.gitignore +++ /dev/null @@ -1,8 +0,0 @@ -# Default ignored files -/shelf/ -/workspace.xml -# Editor-based HTTP Client requests -/httpRequests/ -# Datasource local storage ignored files -/dataSources/ -/dataSources.local.xml diff --git a/.idea/dataSources.xml b/.idea/dataSources.xml deleted file mode 100644 index 2321224..0000000 --- a/.idea/dataSources.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - - - mysql.8 - true - com.mysql.cj.jdbc.Driver - jdbc:mysql://10.10.10.85:3306/delta - $ProjectFileDir$ - - - sqlite.xerial - true - org.sqlite.JDBC - jdbc:sqlite:D:\phpstorm\delta-project\test.db.db - $ProjectFileDir$ - - - \ No newline at end of file diff --git a/.idea/delta-project.iml b/.idea/delta-project.iml deleted file mode 100644 index 5ad3877..0000000 --- a/.idea/delta-project.iml +++ /dev/null @@ -1,100 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/.idea/deployment.xml b/.idea/deployment.xml deleted file mode 100644 index e01aef9..0000000 --- a/.idea/deployment.xml +++ /dev/null @@ -1,17 +0,0 @@ - - - - - \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml deleted file mode 100644 index af519c4..0000000 --- a/.idea/modules.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/.idea/php.xml b/.idea/php.xml deleted file mode 100644 index fd76f4b..0000000 --- a/.idea/php.xml +++ /dev/null @@ -1,259 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - /etc/php74w/php.d/1-ioncubeloader.ini, /etc/php74w/php.d/10-opcache.ini, /etc/php74w/php.d/15-xdebug.ini, /etc/php74w/php.d/20-bcmath.ini, /etc/php74w/php.d/20-bz2.ini, /etc/php74w/php.d/20-calendar.ini, /etc/php74w/php.d/20-ctype.ini, /etc/php74w/php.d/20-curl.ini, /etc/php74w/php.d/20-dba.ini, /etc/php74w/php.d/20-dom.ini, /etc/php74w/php.d/20-enchant.ini, /etc/php74w/php.d/20-exif.ini, /etc/php74w/php.d/20-ffi.ini, /etc/php74w/php.d/20-fileinfo.ini, /etc/php74w/php.d/20-ftp.ini, /etc/php74w/php.d/20-gd.ini, /etc/php74w/php.d/20-gettext.ini, /etc/php74w/php.d/20-gmp.ini, /etc/php74w/php.d/20-iconv.ini, /etc/php74w/php.d/20-imap.ini, /etc/php74w/php.d/20-intl.ini, /etc/php74w/php.d/20-json.ini, /etc/php74w/php.d/20-ldap.ini, /etc/php74w/php.d/20-mbstring.ini, /etc/php74w/php.d/20-mysqlnd.ini, /etc/php74w/php.d/20-odbc.ini, /etc/php74w/php.d/20-pdo.ini, /etc/php74w/php.d/20-pgsql.ini, /etc/php74w/php.d/20-phar.ini, /etc/php74w/php.d/20-posix.ini, /etc/php74w/php.d/20-pspell.ini, /etc/php74w/php.d/20-shmop.ini, /etc/php74w/php.d/20-simplexml.ini, /etc/php74w/php.d/20-snmp.ini, /etc/php74w/php.d/20-soap.ini, /etc/php74w/php.d/20-sockets.ini, /etc/php74w/php.d/20-sodium.ini, /etc/php74w/php.d/20-sqlite3.ini, /etc/php74w/php.d/20-sysvmsg.ini, /etc/php74w/php.d/20-sysvsem.ini, /etc/php74w/php.d/20-sysvshm.ini, /etc/php74w/php.d/20-tidy.ini, /etc/php74w/php.d/20-tokenizer.ini, /etc/php74w/php.d/20-xml.ini, /etc/php74w/php.d/20-xmlwriter.ini, /etc/php74w/php.d/20-xsl.ini, /etc/php74w/php.d/30-mysqli.ini, /etc/php74w/php.d/30-pdo_dblib.ini, /etc/php74w/php.d/30-pdo_firebird.ini, /etc/php74w/php.d/30-pdo_mysql.ini, /etc/php74w/php.d/30-pdo_odbc.ini, /etc/php74w/php.d/30-pdo_pgsql.ini, /etc/php74w/php.d/30-pdo_sqlite.ini, /etc/php74w/php.d/30-xmlreader.ini, /etc/php74w/php.d/30-xmlrpc.ini, /etc/php74w/php.d/40-apcu.ini, /etc/php74w/php.d/40-brotli.ini, /etc/php74w/php.d/40-env.ini, /etc/php74w/php.d/40-ffmpeg.ini, /etc/php74w/php.d/40-gearman.ini, /etc/php74w/php.d/40-geoip.ini, /etc/php74w/php.d/40-igbinary.ini, /etc/php74w/php.d/40-imagick.ini, /etc/php74w/php.d/40-mailparse.ini, /etc/php74w/php.d/40-mcrypt.ini, /etc/php74w/php.d/40-memcache.ini, /etc/php74w/php.d/40-msgpack.ini, /etc/php74w/php.d/40-ncurses.ini, /etc/php74w/php.d/40-psr.ini, /etc/php74w/php.d/40-smbclient.ini, /etc/php74w/php.d/40-sqlsrv.ini, /etc/php74w/php.d/40-ssh2.ini, /etc/php74w/php.d/40-swoole.ini, /etc/php74w/php.d/40-uploadprogress.ini, /etc/php74w/php.d/40-v8js.ini, /etc/php74w/php.d/40-yaml.ini, /etc/php74w/php.d/40-zephir_parser.ini, /etc/php74w/php.d/40-zip.ini, /etc/php74w/php.d/50-apc.ini, /etc/php74w/php.d/50-memcached.ini, /etc/php74w/php.d/50-phalcon.ini, /etc/php74w/php.d/50-redis.ini - /etc/php74w/php.ini - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml deleted file mode 100644 index 94a25f7..0000000 --- a/.idea/vcs.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/.idea/webServers.xml b/.idea/webServers.xml deleted file mode 100644 index ef93629..0000000 --- a/.idea/webServers.xml +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/README.md b/README.md index 615576d..ca6ae31 100644 --- a/README.md +++ b/README.md @@ -33,9 +33,6 @@ Delta Framework - простой фреймворк для разработки ### Менеджер очереди ![Дашбоарт](./uploads/mq.png) -### Командная строка -![Дашбоарт](./uploads/phpcmd.png) - ### Список пользователей ![Дашбоарт](./uploads/userslist.png) diff --git a/admin/inc/header.php b/admin/inc/header.php index 4b5c0c7..5ffe100 100644 --- a/admin/inc/header.php +++ b/admin/inc/header.php @@ -255,7 +255,6 @@
  • Список ролей
  • Кэширование
  • Диспетчер очереди
  • -
  • Командная PHP строка
  • В никуда
  • diff --git a/admin/phpcmd.php b/admin/phpcmd.php deleted file mode 100644 index 1e9f64a..0000000 --- a/admin/phpcmd.php +++ /dev/null @@ -1,183 +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. - */ - - use Core\CoreException; - use Core\Models\{User, Roles}; - - require_once __DIR__ . '/inc/header.php'; - - global $USER; - if ($USER->isAdmin() === false) { - header('Location: ./'); - die(); - } - - if (isset($_REQUEST['execute']) && $_REQUEST['execute'] == 'Y') { - $_SESSION['phpcmd_query'] = $_REQUEST['query']; - - if (isset($_REQUEST['save']) and $_REQUEST['save'] == 'Y') { - $arQuery = explode(PHP_EOL, $_REQUEST['query']); - if (stristr($arQuery[0], '//title: ')) { - $queryName = str_replace('//title: ', '', $arQuery[0]); - } else { - $queryName = 'PHP код ' . date('d.m H:i'); - } - $USER->getMetaObject()->addMeta('code', serialize(['name' => $queryName, 'code' => $_REQUEST['query']])); - } - } - - if (isset($_REQUEST['delMeta'])) { - $USER->getMetaObject()->deleteMeta($_REQUEST['delMeta']); - } -?> - - -
    -
    -
    -
    - -
    - getMetaObject()->getMetaByName('code'); - if (!empty($userCodes)) { - foreach ($userCodes as $code) { - $element = unserialize($code['value']); - ?> -
    - - -
    - -
    - -
    - - -
    -
    - - > - -
    -
    - - -
    -
    - -
    -
    - Результат

    '; - - $execResult = ''; - try { - ob_start(); - eval($_REQUEST['query']); - $execResult = ob_get_clean(); - if (isset($_REQUEST['use_pre']) and $_REQUEST['use_pre'] == 'Y') { - echo '

    ' . $execResult . '
    '; - } else { - echo $execResult; - } - } catch (ParseError $p) { - echo '

    '; - CoreException::showDetailTraceFromException($p); - echo '

    '; - } catch (CoreException $e) { - echo '

    '; - $e->showDetailTrace(); - echo '

    '; - } catch (Throwable $e) { - echo '

    '; - CoreException::showDetailTraceFromException($e); - echo '

    '; - } - echo '

    '; - } - ?> -
    -
    -
    - - - \ No newline at end of file diff --git a/composer.json b/composer.json index d444055..668b7b7 100644 --- a/composer.json +++ b/composer.json @@ -15,6 +15,7 @@ } ], "require": { + "php": ">=8.4", "twig/twig": "^3.0", "sentry/sdk": "^3.2", "ext-iconv": "*", diff --git a/config.local.example.php b/config.local.example.php new file mode 100644 index 0000000..5e67dc5 --- /dev/null +++ b/config.local.example.php @@ -0,0 +1,43 @@ + 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(); diff --git a/core/cache/test.tmp b/core/cache/test.tmp deleted file mode 100644 index e69de29..0000000 diff --git a/core/config.php b/core/config.php index ed31ae8..0e5f6cc 100644 --- a/core/config.php +++ b/core/config.php @@ -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); + } diff --git a/core/lib/Core/App.class.php b/core/lib/Core/App.class.php index 17b3c24..c54fe87 100644 --- a/core/lib/Core/App.class.php +++ b/core/lib/Core/App.class.php @@ -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(); diff --git a/core/lib/Core/ExternalServices/RequestOLD.class.php b/core/lib/Core/ExternalServices/RequestOLD.class.php deleted file mode 100644 index 44879a4..0000000 --- a/core/lib/Core/ExternalServices/RequestOLD.class.php +++ /dev/null @@ -1,181 +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\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; - } - } \ No newline at end of file diff --git a/core/lib/Core/ExternalServices/Telegram.class.php b/core/lib/Core/ExternalServices/Telegram.class.php deleted file mode 100644 index 7dc0cb4..0000000 --- a/core/lib/Core/ExternalServices/Telegram.class.php +++ /dev/null @@ -1,375 +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. - */ - - /** - * Класс для работы с API телеграмм - * Поддерживает: - * - отправка сообщений с разметкой html - * - редактирование отправленных сообщений - * - работу с inline класиатурами (в сообщении) - * - работу с быстрыми клавиатурами (меню бота) - * - отправка сообщений с изображением с разметкой html - * - отправка файлов - * - получение информации о группе или канале - * - получение файлов по идентификатору - * - имитация действий (набирает сообщение, записывает голосовое и т.д.) - * - отправка местоположений - * - обработка callback запросов - * - обработка inline событий - * - * @version 2.5.1 - * @author Roman Grinko - */ - - 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); - } - - /** - * Отправка в чат имитаций событий - *
    -         * typing для набора текста
    -         * upload_photo для загрузки фото
    -         * record_video или upload_video для видео
    -         * record_voice или upload_voice для голосовых
    -         * upload_document здля загрузки документов
    -         * choose_sticker для выбора стикера
    -         * find_location для местоположения
    -         * record_video_note или upload_video_note для видеосообщений
    -         * 
    - * - * @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 - *
    -         * $arData = [
    -         *              [
    -         *                'title' => 'Title1',
    -         *                'description' => 'description1',
    -         *                'message_text' => 'Message1',
    -         *                'thumb_url' => 'http://example.com/1.jpg'
    -         *              ],
    -         *           ]
    -         * 
    - * - * @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, '
    ');
    -            $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);
    -        }
    -    }
    diff --git a/core/lib/Core/ExternalServices/TelegramActions.class.php b/core/lib/Core/ExternalServices/TelegramActions.class.php
    deleted file mode 100644
    index 19ec93c..0000000
    --- a/core/lib/Core/ExternalServices/TelegramActions.class.php
    +++ /dev/null
    @@ -1,396 +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.
    -     */
    -
    -    /**
    -     * Класс-обработчик команд Telegram
    -     * Поддерживает:
    -     * - работа с простыми командами
    -     * - выделение аргументов команды
    -     * - определение типа события (сообщение, локация, фото, докемент...)
    -     * - работа с инлайн и callback запросами
    -     * - работа с инлайн клавиатурами (под сообщением)
    -     * - работа с клавиатурами (меню)
    -     * - обработка неизвестной команды
    -     *
    -     * @version 1.0.1
    -     * @author  Roman Grinko 
    -     */
    -
    -    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 .= '' . print_r(self::$data, true) . '';
    -            }*/
    -            //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()
    -            );
    -        }
    -    }
    \ No newline at end of file
    diff --git a/core/lib/Core/Helpers/Cache/Cache.class.php b/core/lib/Core/Helpers/Cache/Cache.class.php
    deleted file mode 100644
    index c1c1f01..0000000
    --- a/core/lib/Core/Helpers/Cache/Cache.class.php
    +++ /dev/null
    @@ -1,77 +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\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)
    -        {
    -
    -        }
    -
    -    }
    diff --git a/core/routes.php b/core/routes.php
    index e59f73a..068ca07 100644
    --- a/core/routes.php
    +++ b/core/routes.php
    @@ -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;
    -    });
    diff --git a/db/cleanup/2026-08-14_stage0.sql b/db/cleanup/2026-08-14_stage0.sql
    new file mode 100644
    index 0000000..e8d0816
    --- /dev/null
    +++ b/db/cleanup/2026-08-14_stage0.sql
    @@ -0,0 +1,18 @@
    +-- Этап 0 архитектурного рефакторинга: чистка данных.
    +--
    +-- Выполнять на базе приложения (та, что задана в config.local.php как DB_NAME).
    +-- Phinx-миграцией не оформлено сознательно: окружения в phinx.php указывают на другие базы,
    +-- чем использует само приложение, и до унификации конфигурации на Этапе 2 запуск миграции
    +-- ушёл бы не в ту базу.
    +--
    +-- Запуск:
    +--   mysql -u  -p  < db/cleanup/2026-08-14_stage0.sql
    +
    +-- 1. Сниппеты кода, сохранённые удалённой веб-консолью admin/phpcmd.php.
    +--    Перед удалением можно посмотреть, что именно удалится:
    +--    SELECT id, user_id, LEFT(value, 120) FROM d_user_meta WHERE name = 'code';
    +DELETE FROM `d_user_meta` WHERE `name` = 'code';
    +
    +-- 2. Пустые таблицы-остатки экспериментов на MyISAM.
    +DROP TABLE IF EXISTS `test__table`;
    +DROP TABLE IF EXISTS `test__table2`;
    diff --git a/docs/ARCHITECTURE_PLAN.md b/docs/ARCHITECTURE_PLAN.md
    index e1bc821..13538eb 100644
    --- a/docs/ARCHITECTURE_PLAN.md
    +++ b/docs/ARCHITECTURE_PLAN.md
    @@ -257,6 +257,10 @@ public function updatePassword(Request $request): Response
     Снимает Д3.
     
     - [ ] `src/Config/Env.php` — парсер `.env` (без внешних зависимостей либо `vlucas/phpdotenv`).
    +- [ ] **`.env` не класть в корень проекта без защиты.** Проверено на Этапе 0: docroot dev-хоста совпадает
    +      с корнем проекта, nginx исполняет только `*.php`, а любой другой файл отдаёт сырым текстом
    +      (`config.local.php.example` открывался по URL как обычный текст). До переноса docroot в `public/`
    +      на Этапе 3 либо держать `.env` уровнем выше корня, либо закрыть его правилом в конфиге nginx.
     - [ ] `src/Config/Config.php` — `get('database.host', $default)`, источник — файлы `config/*.php`,
           читающие `env()`.
     - [ ] Создать `config/app.php`, `config/database.php`, `config/mail.php`, `config/telegram.php`,
    @@ -421,3 +425,44 @@ public function updatePassword(Request $request): Response
     - Внешние ключи в БД — отдельная задача, не блокирующая рефакторинг ядра.
     - Чистка таблиц-парсеров без префикса (`podslyshano`, `spider`, `bashorg`, `jokes`, `myslo`) — отдельная
       задача уровня данных, кроме `test__table`/`test__table2` (удалить в рамках Этапа 0).
    +
    +---
    +
    +## 9. Журнал выполнения
    +
    +### Этап 0 — выполнен 2026-08-14
    +
    +Сделано:
    +
    +- Удалена веб-консоль `admin/phpcmd.php` вместе с пунктом меню в `admin/inc/header.php` и скриншотом в
    +  `README.md`. SQL на удаление сохранённых сниппетов — `db/cleanup/2026-08-14_stage0.sql`.
    +- Удалены скретч-файлы из корня docroot: `test.php`, `testMvc.php`, `testWait.php`, `webApp.php`,
    +  `meshtasticForward.php`, `composer.phar`.
    +- Удалён мёртвый код (у каждого подтверждено 0 ссылок по проекту): `TelegramActions.class.php`,
    +  `Telegram.class.php`, `RequestOLD.class.php`, `Helpers/Cache/Cache.class.php`, `templates/index_lll.twig`,
    +  `templates/test.twig`, маршруты `/test` и метод `App::test()`, пункт меню «Тестовая» в `layout.twig`.
    +- Секреты вынесены в `config.local.php` (вне git) с шаблоном `config.local.example.php`; в `core/config.php`
    +  и `phinx.php` остались пустые значения по умолчанию и явная диагностика при отсутствии реквизитов.
    +  `CRYPTO_KEY` переведён из `const` в `define()` — как `const` он не мог быть переопределён локальным
    +  конфигом. **Ротация утёкших значений остаётся за владельцем проекта: они сохранились в истории git.**
    +- `.idea/` снят с отслеживания: в публичном репозитории лежали внутренние адреса окружения и путь к docroot.
    +- Twig: `debug` и `cache` завязаны на `DEBUG` вместо жёсткого `debug => true`.
    +- В `composer.json` зафиксировано `"php": ">=8.4"` (на dev-хосте 8.4.23).
    +- Исправлен путь к сидам в `phinx.php`: `db/seeds` → `db/seed` (каталог называется иначе, чем было указано).
    +
    +Обнаружено по ходу и учтено в плане:
    +
    +- **Сервер — nginx (openresty), а не Apache.** Значит `uploads/.htaccess` с `SetHandler none` не читается
    +  вообще, и защита загруженных файлов от исполнения, описанная в аудите, на dev-хосте фактически
    +  отсутствует. Приоритет валидации загрузок в `UploadedFile` (Этап 3) повышается.
    +- Любой файл в корне проекта, не оканчивающийся на `.php`, отдаётся веб-сервером как сырой текст —
    +  учтено в требованиях к размещению `.env` на Этапе 2.
    +- Конфигурация `phinx.php` указывает на другие базы, чем использует само приложение
    +  (`rsgrinko_test`/`rsgrinko_delta` против `delta`), — расхождение снимается при унификации
    +  конфигурации на Этапе 2.
    +- Локальный PHP CLI — 8.3.19 при целевых 8.4, поэтому `php -l` локально не проверит синтаксис,
    +  специфичный для 8.4.
    +
    +Проверка: `php -l` по всем изменённым файлам, `phpunit` зелёный, ответы всех маршрутов сайта сверены с
    +слепком до изменений — расхождение ровно 365 байт на страницу (удалённый пункт меню), удалённые URL
    +отдают 404.
    diff --git a/phinx.php b/phinx.php
    index 2daaa41..c023a4c 100644
    --- a/phinx.php
    +++ b/phinx.php
    @@ -1,29 +1,43 @@
      [
                 'migrations' => '%%PHINX_CONFIG_DIR%%/db/migrations',
    -            'seeds' => '%%PHINX_CONFIG_DIR%%/db/seeds'
    +            'seeds' => '%%PHINX_CONFIG_DIR%%/db/seed'
             ],
             'environments' => [
                 'default_migration_table' => 'd_phinxlog',
                 'default_environment' => 'dev',
                 'prod' => [
                     'adapter' => 'mysql',
    -                'host' => 'localhost',
    -                'name' => 'rsgrinko_delta',
    -                'user' => 'rsgrinko_delta',
    -                'pass' => '2670135',
    +                'host' => PHINX_PROD_HOST,
    +                'name' => PHINX_PROD_NAME,
    +                'user' => PHINX_PROD_USER,
    +                'pass' => PHINX_PROD_PASS,
                     'port' => '3306',
                     'charset' => 'utf8',
                 ],
                 'dev' => [
                     'adapter' => 'mysql',
    -                'host' => 'it-stories.ru',
    -                'name' => 'rsgrinko_test',
    -                'user' => 'rsgrinko_test',
    -                'pass' => '2670135',
    +                'host' => PHINX_DEV_HOST,
    +                'name' => PHINX_DEV_NAME,
    +                'user' => PHINX_DEV_USER,
    +                'pass' => PHINX_DEV_PASS,
                     'port' => '3306',
                     'charset' => 'utf8',
                 ]
    diff --git a/templates/index_lll.twig b/templates/index_lll.twig
    deleted file mode 100644
    index 108a3d9..0000000
    --- a/templates/index_lll.twig
    +++ /dev/null
    @@ -1,82 +0,0 @@
    -
    -
    -
    -    
    -    
    -    
    -    
    -    
    -    Главная тестовая
    -
    -
    -
    - - - -
    -
    -
    - - {% if isAuthorized %} -

    Добро пожаловать!

    - {{ userDataTable |raw }} - {% else %} -

    Вы не авторизованы :(

    - {% endif %} - -
    -
    -
    -
    - - - - \ No newline at end of file diff --git a/templates/layout.twig b/templates/layout.twig index eed2028..452e32a 100644 --- a/templates/layout.twig +++ b/templates/layout.twig @@ -35,7 +35,6 @@ {% endif %} {{ icons.users() }}Пользователи {{ icons.info() }}Информация - {{ icons.flask() }}Тестовая