[+] класс внешних реквестов

[+] сбор статистики
[-] Удален класс Template.class.php в связи с выпиливанием его использования
This commit is contained in:
rsgrinko committed 2023-10-09 23:31:18 +03:00
1 parent a7cf48bac6
commit ca18c4dc25
5 files changed
+298 -200

No files matched your search

+27 -15
View File
@@ -19,13 +19,14 @@
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
use Core\Helpers\DDosProtection;
use Core\Models\User;
use Core\CoreException;
use Core\ExternalServices\Request;
use Core\Helpers\Cache;
use Core\Helpers\DDosProtection;
use Core\Models\Router;
use Core\Models\User;
use Core\Models\UTM;
use Core\Template;
use Core\CoreException;
use Core\Models\Router;
error_reporting(E_ALL & ~E_NOTICE & ~E_WARNING);
//error_reporting(E_ALL);
@@ -51,17 +52,6 @@
$sentryScope->setExtra('user_token', $_SESSION['token'] ?? '');
});
ob_start(function ($buffer) {
try {
Template::set('CLEAR_CACHE_LINK_NAME', 'Сброс файлового кэша');
Template::set('ADMIN_PANEL_LINK_NAME', 'Панель администратора');
Template::set('REFRESH_PAGE_LINK_NAME', 'Перезагрузить страницу');
Template::set('PHP_CMD_LINK_NAME', 'Командная PHP строка');
return Template::render($buffer);
} catch (Throwable $e) {
return $e->getMessage();
}
});
define('START_TIME', microtime(true)); // засекаем время старта скрипта
const CORE_LOADED = true; // флаг корректного запуска
@@ -138,6 +128,28 @@
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) {
}
}
$ddosProtectObject = new DDosProtection(basename(__FILE__));
try {
$userId = User::getCurrentUserId();
+89 -138
View File
@@ -1,6 +1,7 @@
<?php
/**
* Copyright (c) 2022 Roman Grinko <rsgrinko@gmail.com>
* Copyright (c) 2023 Roman Grinko <rsgrinko@gmail.com>
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
@@ -20,162 +21,112 @@
*/
namespace Core\ExternalServices;
use Core\CoreException;
/**
* Класс запросов к внешним системам
*/
class Request
{
private $httpStatus = null;
/** @var string $baseUrl Базовый адрес */
private string $baseUrl;
private $httpCode = null;
/** @var int $httpCode Код ответа */
private int $httpCode = 0;
private $maxRedirects = 2;
/** @var string $responseBody Тело ответа */
private string $responseBody = '';
/** @var string $responseHeader Заголовки ответа */
private string $responseHeader = '';
/** @var int[] Успешные коды ответов */
private const SUCCESS_HTTP_CODES = [
200,
202,
203,
204,
205,
206,
207,
226,
];
private $requestHeaders = [];
/**
* @var false|string
* Коструктор
*
* @param string $baseUrl Базовый адрес
*/
private $responseBody = null;
private $responseHeader = null;
private $timeout = 5;
public function __construct(string $baseUrl)
{
$this->baseUrl = $baseUrl;
return $this;
}
/**
* @return string|null
* POST запрос
*
* @param array $data Данные
*
* @return $this
*/
public function getResponseBody(): ?string
public function post(array $data = []): self
{
$ch = curl_init($this->baseUrl);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data, '', '&'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HEADER, true);
$result = curl_exec($ch);
$headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$this->responseHeader = substr($result, 0, $headerSize);
$this->responseBody = substr($result, $headerSize);
$this->httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return $this;
}
/**
* Проверка запроса на успешность выполнения
*
* @return bool Результат
*/
public function isSuccess(): bool
{
return in_array($this->httpCode, self::SUCCESS_HTTP_CODES, true);
}
/**
* Получить код ответа
*
* @return int Код ответа
*/
public function getHttpCode(): int
{
return $this->httpCode;
}
/**
* Получить тело ответа
*
* @return string Тело ответа
*/
public function getBody(): string
{
return $this->responseBody;
}
/**
* @return null
* Получить заголовки ответа
*
* @return string Заголовки ответа
*/
public function getResponseHeader()
public function getHeaders(): string
{
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;
}
}
@@ -0,0 +1,181 @@
<?php
/**
* Copyright (c) 2022 Roman Grinko <rsgrinko@gmail.com>
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Core\ExternalServices;
use Core\CoreException;
class RequestOLD
{
private $httpStatus = null;
private $httpCode = null;
private $maxRedirects = 2;
private $requestHeaders = [];
/**
* @var false|string
*/
private $responseBody = null;
private $responseHeader = null;
private $timeout = 5;
/**
* @return string|null
*/
public function getResponseBody(): ?string
{
return $this->responseBody;
}
/**
* @return null
*/
public function getResponseHeader()
{
return $this->responseHeader;
}
private $usertAgent = null;
private $requestType = null;
private $url = null;
private $params = [];
private $referer = '';
private $usePostMethod = false;
public function __construct()
{
}
public function setUrl(?string $url): self
{
$this->url = $url;
return $this;
}
public function post(): self
{
$this->usePostMethod = true;
return $this;
}
public function get(): self
{
$this->usePostMethod = true;
return $this;
}
public function setParams(?array $params = null): self
{
$this->params = $params ?: [];
return $this;
}
public function setHeaders(?array $arHeaders = null): self
{
$this->requestHeaders = $arHeaders ?: [];
return $this;
}
public function setTimeout(int $timeout): self
{
$this->timeout = $timeout;
return $this;
}
public function setMaxRedirects(int $redirects): self
{
$this->maxRedirects = $redirects;
return $this;
}
public function setReferer(?string $referer = null): self
{
$this->referer = $referer ?: '';
return $this;
}
public function setUserAgent(?string $userAgent = null): self
{
$this->userAgent = $userAgent ?: '';
return $this;
}
public function getCode(): ?int
{
return $this->httpCode;
}
public function send()
{
$res = $this->sendRequest();
return $res;
}
/**
* @throws CoreException
*/
private function sendRequest(): ?string
{
if (empty($this->url)) {
throw new ExternalServicesException('Адрес запроса не задан');
}
if ($this->usePostMethod === true) {
$ch = curl_init($this->url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $this->params);
} else {
$ch = curl_init($this->url . '?' . http_build_query($this->params));
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_REFERER, $this->referer);
curl_setopt($ch, CURLOPT_TIMEOUT, $this->timeout);
curl_setopt($ch, CURLOPT_MAXREDIRS, $this->maxRedirects);
curl_setopt($ch, CURLOPT_USERAGENT, $this->usertAgent);
curl_setopt($ch, CURLOPT_HTTPHEADER, $this->requestHeaders);
curl_setopt($ch, CURLOPT_HEADER, 1);
$res = curl_exec($ch);
$headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$this->responseHeader = substr($res, 0, $headerSize);
$this->responseBody = substr($res, $headerSize);
$this->httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return $res;
}
}
+1 -1
View File
@@ -58,7 +58,7 @@
public const EXECUTION_TASKS_LIMIT = 100;
/** Лимит количества запущенных воркеров */
public const WORKERS_LIMIT = 2;
public const WORKERS_LIMIT = 1;
/** @var DB|null $DB Объект базы */
private ?DB $DB;
-46
View File
@@ -1,46 +0,0 @@
<?php
/**
* Copyright (c) 2022 Roman Grinko <rsgrinko@gmail.com>
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Core;
use Core\Helpers\SystemFunctions;
class Template
{
private static array $arTemplateVariables = [];
public static function set(string $varName, string $varValue): void
{
$varName = '{{' . $varName . '}}';
self::$arTemplateVariables[$varName] = $varValue;
}
public static function flush(): void
{
self::$arTemplateVariables = [];
}
public static function render($buffer): ?string
{
$buffer = str_replace(array_keys(self::$arTemplateVariables), array_values(self::$arTemplateVariables), $buffer);
return $buffer;
}
}