diff --git a/core/bootstrap.php b/core/bootstrap.php index 722367b..c6acf8d 100644 --- a/core/bootstrap.php +++ b/core/bootstrap.php @@ -29,41 +29,26 @@ use Core\SystemConfig; error_reporting(E_ALL & ~E_NOTICE & ~E_WARNING); - //error_reporting(E_ALL); - - if (session_status() == PHP_SESSION_NONE) { - session_start(); - } date_default_timezone_set('Europe/Moscow'); - define('START_MEMORY', memory_get_usage()); + if (session_status() === PHP_SESSION_NONE) { + session_start(); + } require_once __DIR__ . '/../vendor/autoload.php'; - \Sentry\init( - [ - 'dsn' => 'https://8657ac1a900c44e5bc51714bb4c00dbb@o1303100.ingest.sentry.io/6541634', - 'error_types' => E_ALL & ~E_NOTICE, - ] - ); - - Sentry\configureScope(function (Sentry\State\Scope $sentryScope) { - $sentryScope->setExtra('user_id', $_SESSION['id'] ?? ''); - $sentryScope->setExtra('user_login', $_SESSION['login'] ?? ''); - $sentryScope->setExtra('user_token', $_SESSION['token'] ?? ''); - }); - + define('START_MEMORY', memory_get_usage()); define('START_TIME', microtime(true)); // засекаем время старта скрипта const CORE_LOADED = true; // флаг корректного запуска if (empty($_SERVER['SERVER_NAME'])) { $_SERVER['SERVER_NAME'] = 'localhost'; } + if (empty($_SERVER['DOCUMENT_ROOT'])) { $_SERVER['DOCUMENT_ROOT'] = __DIR__. '/../'; } - // Если имеется файл локальной конфигурации - подключаем его if (file_exists($_SERVER['DOCUMENT_ROOT'] . '/config.local.php')) { require_once $_SERVER['DOCUMENT_ROOT'] . '/config.local.php'; @@ -72,6 +57,12 @@ // Подключим основной файл конфигурации require_once __DIR__ . '/config.php'; + $isCronProcess = false; + if (defined('IS_CRON_PROCESS') && IS_CRON_PROCESS === true) { + $isCronProcess = true; + } + define('CORE_FULL_LOAD', !$isCronProcess); + /** * Отладочная функция: вывести данные * @param mixed $data Данные @@ -115,58 +106,38 @@ // Инициализация кеша Cache::init(CACHE_DIR, USE_CACHE); - // Обработка UTM меток - (new UTM())->save(); + if (CORE_FULL_LOAD) { + // Обработка UTM меток + (new UTM())->save(); - // очистка кэша - if (isset($_REQUEST['clear_cache']) && $_REQUEST['clear_cache'] === CODE_VALUE_Y) { - Cache::flush(); - } - - // выход из системы - if (isset($_REQUEST['logout']) && $_REQUEST['logout'] === CODE_VALUE_Y) { - User::logout(); - } - - /** - * Для сбора статистики запусков - * - * git clone присутствуют, а обратной связи нет. Грустненько... - */ - if (gethostname() !== 'sun.local') { - $array = [ - 'SERVER_NAME' => $_SERVER['SERVER_NAME'], - 'HOST' => $_SERVER['HTTP_HOST'], - 'REQUEST_URI' => $_SERVER['REQUEST_URI'], - 'HOSTNAME' => gethostname(), - 'PHP' => phpversion(), - 'DELTA_VERSION' => CORE_VERSION, - ]; - - $requestObject = new Request('https://it-stories.ru/custom/delta.php'); - try { - $requestObject->post($array); - } catch (Throwable $e) { + // очистка кэша + if (isset($_REQUEST['clear_cache']) && $_REQUEST['clear_cache'] === CODE_VALUE_Y) { + Cache::flush(); } - } - $ddosProtectObject = new DDosProtection(basename(__FILE__)); - try { - $userId = User::getCurrentUserId(); - } catch (CoreException $e) { - $userId = null; - } - if (!empty($userId)) { + // выход из системы + if (isset($_REQUEST['logout']) && $_REQUEST['logout'] === CODE_VALUE_Y) { + User::logout(); + } + + $ddosProtectObject = new DDosProtection(basename(__FILE__)); try { - $USER = new User($userId); - $ddosProtectObject->setUserId($userId); + $userId = User::getCurrentUserId(); } catch (CoreException $e) { + $userId = null; + } + if (!empty($userId)) { + try { + $USER = new User($userId); + $ddosProtectObject->setUserId($userId); + } catch (CoreException $e) { + $USER = null; + } + } else { $USER = null; } - } else { - $USER = null; + $ddosProtectObject->checkDDos(); } - $ddosProtectObject->checkDDos(); // debug function sendTelegram(?string $message, ?string $file = null): void @@ -183,7 +154,7 @@ /** * Запускаем маршрутизатор если не сказано иного */ - if (defined('USE_ROUTER') && USE_ROUTER === true) { + if (CORE_FULL_LOAD && defined('USE_ROUTER') && USE_ROUTER === true) { /** * Инициализация шаблонизатора */ @@ -196,4 +167,4 @@ require_once __DIR__ . '/routes.php'; Router::execute(); die(); - } \ No newline at end of file + } diff --git a/core/config.php b/core/config.php index 1875aea..ed31ae8 100644 --- a/core/config.php +++ b/core/config.php @@ -105,13 +105,13 @@ define('DB_HOST', 'localhost'); } if (!defined('DB_USER')) { - define('DB_USER', 'rsgrinko_delta'); + define('DB_USER', 'delta'); } if (!defined('DB_PASSWORD')) { define('DB_PASSWORD', '2670135'); } if (!defined('DB_NAME')) { - define('DB_NAME', 'rsgrinko_delta'); + define('DB_NAME', 'delta'); } if (!defined('DB_TABLE_PREFIX')) { define('DB_TABLE_PREFIX', 'd_'); diff --git a/core/lib/Core/DataBases/DB.class.php b/core/lib/Core/DataBases/DB.class.php index 0f75a59..3b91a9f 100644 --- a/core/lib/Core/DataBases/DB.class.php +++ b/core/lib/Core/DataBases/DB.class.php @@ -293,13 +293,6 @@ try { $stmt = $this->db->query($sql); } catch (\Throwable $t) { - SystemFunctions::sendAlarm('DataBase', - '' . date('d.m.Y H:i:s') . '' . PHP_EOL - . 'SQL ERROR: ' . PHP_EOL - . $this->db->errorInfo()[2] . PHP_EOL - . 'QUERY: ' . PHP_EOL - . $sql - ); if(SystemConfig::getValue('DEBUG')) { throw new CoreException( 'В SQL запросе произошла ошибка: ' . $this->db->errorInfo()[2] diff --git a/core/lib/Core/MQTasks.class.php b/core/lib/Core/MQTasks.class.php index 6f7af4f..b121cf6 100644 --- a/core/lib/Core/MQTasks.class.php +++ b/core/lib/Core/MQTasks.class.php @@ -25,6 +25,9 @@ use Core\Helpers\Mail; use Core\Helpers\SystemFunctions; use Core\Helpers\Thumbs; + use Core\Models\MQ; + use PHPUnit\Util\Exception; + use Throwable; class MQTasks { @@ -496,4 +499,114 @@ DELETE from `jokes` WHERE `jokes`.id not in (SELECT id FROM t_temp);' return $mailObject->send(); } - } \ No newline at end of file + /** + * Запуск механизма поисковой индексации + * + * @param string $url Начальный URL + * + * @return string + * @throws CoreException + */ + public static function spider(string $url): string + { + $DB = DB::getInstance(); + + if (empty($url)) { + throw new Exception('Передан пустой url'); + } + + if ($DB->getItem('spider',['url' => $url]) !== null) { + throw new Exception('Данный url ' . $url . ' уже присутствует в базе'); + } + $defaultSocketTimeout = ini_get('default_socket_timeout'); + ini_set('default_socket_timeout', 5); + $data = file_get_contents($url); + ini_set('default_socket_timeout', $defaultSocketTimeout); + + if (!is_array($http_response_header)) { + $http_response_header = []; + } + + $headers = implode("\n", $http_response_header); + preg_match_all("/^content-type\s*:\s*(.*)$/mi", $headers, $matchesContentType); + $contentType = trim(end($matchesContentType[1])); + + $posTypeText = strpos($contentType, 'text/html'); + + if (empty($data)) { + throw new Exception('Данных по url ' . $url . ' не найдено'); + } + + if ($posTypeText === false || $posTypeText !== 0) + { + throw new Exception('Данный url ' . $url . ' не содержит текстовых данных (' . $contentType . ')'); + } + + preg_match('~