8 Commits
Author SHA1 Message Date
rsgrinko a110e5d03e [*] обновлена версия до 1.0.1_dev 2023-10-11 18:08:26 +03:00
rsgrinko 52937271de [+] класс генерации фейковых UserAgent 2023-10-10 00:26:43 +03:00
rsgrinko ca18c4dc25 [+] класс внешних реквестов
[+] сбор статистики
[-] Удален класс Template.class.php в связи с выпиливанием его использования
2023-10-09 23:31:18 +03:00
rsgrinko a7cf48bac6 Merge pull request #2 from rsgrinko/rsgrinko/firReadme
Исправление README.md
2023-10-08 10:48:17 +03:00
rsgrinko b2cdbad1fa Update README.md 2023-10-08 10:47:11 +03:00
rsgrinko cf50026ce5 [*] небольшой рефакторинг SystemFunctions.class.php
[*] исправлен прогресс бар в диспетчере очереди (теперь показывает проценты корректно и меняет цвет в зависимости от нагрузки)
2023-10-08 00:42:36 +03:00
rsgrinko 9decebf051 [*] одновление данных в readme + новые скрины фронтенда 2023-10-07 16:13:46 +03:00
rsgrinko 5cd5a528f1 [*] update readme 2023-10-07 15:37:25 +03:00
23 changed files with 861 additions and 276 deletions

No files matched your search

+71 -5
View File
@@ -1,7 +1,7 @@
# Delta Framework
## Описание
Delta Framework - простой фреймворк для разработки веб проектов. Его разработка была начата в свободное от работы время и выполнялась полность в свое удовольствие.
Delta Framework - простой фреймворк для разработки веб-проектов. Его разработка была начата в свободное от работы время и выполнялась полность в свое удовольствие.
На текущий момент в нем имеется:
- [X] Авторизация
@@ -18,23 +18,82 @@ Delta Framework - простой фреймворк для разработки
- [X] Логирование
- [X] Работа с файлами
- [X] Миграции
- [X] Captcha
- [X] DDoS Guard (basic)
***
## Скрины админки
## Панель администратора
Панель находистя по адресу `/admin/` и предоставляет базовые возможности по управлению системой.
### Дашбоард
![Дашбоарт](./uploads/dashboard.PNG)
![Дашбоарт](./uploads/dashboard.png)
### Менеджер очереди
![Дашбоарт](./uploads/mq.PNG)
![Дашбоарт](./uploads/mq.png)
### Командная строка
![Дашбоарт](./uploads/phpcmd.PNG)
![Дашбоарт](./uploads/phpcmd.png)
### Список пользователей
![Дашбоарт](./uploads/userslist.png)
## Пользовательская часть
Пользовательская часть построена с использованием шаблонизатора Twig.
Шаблоны располагаются в папке `/templates/`. Для приложения имеется единая точка входа - это `/index.php`.
Маршруты располагаются в файле `/core/routes.php`, а контроллером приложения по умолчанию является файл `/core/lib/App.class.php`.
### Пример нового маршрута
```
/**
* Добавим маршрут, который открывает страницу информации о конкретном пользователе
* URL может иметь вид https://site.ru/users/123
* 123 в даннмо случае идентификатор пользователя
*
* Вторым аргументом следует метод класса, который будет обрабатывать данный запрос
* В текущем примере это класс \Core\App и его метод userProfile (туда передается идентификатор пользователя из запроса)
*/
Router::route('/users/(\d+)', '\Core\App::userProfile');
/**
* Также добавим новый маршрут, который не будет вызывать метод, а сам отдаст результат
*/
Router::route('/test', function () {
echo 'This is test page!';
});
```
### Пример нового обработчика маршрута
Для примера рассмотрим как реализован маршрут с информацией о конкретном пользователе
```
/**
* В данном обработчике мы принимаем идентификатор пользователя (из примера выше)
* и показываем информацию о нем.
*
* Метод self::render() принимает в качестве аргумента файл шаблона
* и массив данных для подстановки в сам шаблон.
* Также он производит дополнение переданных данных обязательными полями,
* такими как: авторизован ли, админ ли, данные текущего пользователя...
*/
public static function userProfile(int $id)
{
$userData = (new User($id))->getAllUserData(true);
self::render('userProfile.twig', ['userData' => $userData]);
}
```
### Главная страница
![Главная](./uploads/front_main.png)
### Список пользователей
![Список пользователей](./uploads/front_users.png)
### Страница информации
![Информация](./uploads/front_info.png)
## Начало использования
Для начала получите проект любым удобным для вас способом (git clone, скачать...)
@@ -66,6 +125,13 @@ Delta Framework - простой фреймворк для разработки
vendor/bin/phinx migrate -e dev
````
Для использования некой многосайтовости предусмотрено подключение локального файла конфигурации.
Пример: вы примонтировали в рядом лежащий проект папки `/core/`, `/upload/`, `/admin/`.
Вам следует создать в корне проекта файл `config.local.php` и переопределить параметры для текущего проекта.
Файл локальной конфигурации является необязательным в случае если переопределение настроек не требуется, однако если его создать - можно точечно переопределить некоторые параметры (например, используемая БД и префикс таблиц).
Доступ к панели управления находится тут
````https://site.ru/admin/````
+13 -4
View File
@@ -196,12 +196,21 @@
<?php
$result['memory'] = ob_get_clean();
ob_start();
$memory = SystemFunctions::getHostMemoryInfo();
//$memory = SystemFunctions::getHostMemoryInfo();
$memory = SystemFunctions::getMemoryUse();
if ($memory->usedPercent < 30) {
$progressClass = 'progress-bar-success';
} elseif ($memory->usedPercent >= 50 && $memory->usedPercent < 80) {
$progressClass = 'progress-bar-warning';
} else {
$progressClass = 'progress-bar-danger';
}
?>
<div class="progress">
<div style="width: <?= round(($memory['free'] + $memory['swapFree']) / ($memory['total'] + $memory['swapTotal']) * 100, 2); ?>%" aria-valuemax="100" aria-valuemin="0"
aria-valuenow="40" role="progressbar" class="progress-bar progress-bar-warning">
<span class="sr-only">40% Complete (success)</span>
<div style="width: <?= round($memory->usedPercent, 2); ?>%" aria-valuemax="100" aria-valuemin="0"
aria-valuenow="<?= round($memory->usedPercent); ?>" role="progressbar" class="progress-bar <?= $progressClass; ?>">
<span><?= round($memory->usedPercent, 2); ?>%</span>
</div>
</div>
<?php
+2 -2
View File
@@ -19,7 +19,7 @@
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
use Core\Helpers\SystemFunctions;
use Core\Helpers\Captcha;
use Core\Models\User;
use Core\CoreException;
@@ -27,7 +27,7 @@
$captchaCorrect = true;
if (USE_CAPTCHA) {
$captchaCorrect = isset($_REQUEST['captchaCode']) && SystemFunctions::isValidCaptcha($_REQUEST['captchaCode']);
$captchaCorrect = isset($_REQUEST['captchaCode']) && Captcha::isValidCaptcha($_REQUEST['captchaCode']);
}
if (User::isAuthorized()) {
+2 -2
View File
@@ -19,7 +19,7 @@
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
use Core\Helpers\SystemFunctions;
use Core\Helpers\Captcha;
use Core\Models\User;
use Core\CoreException;
@@ -27,7 +27,7 @@
$captchaCorrect = true;
if (USE_CAPTCHA) {
$captchaCorrect = isset($_REQUEST['captchaCode']) && SystemFunctions::isValidCaptcha($_REQUEST['captchaCode']);
$captchaCorrect = isset($_REQUEST['captchaCode']) && Captcha::isValidCaptcha($_REQUEST['captchaCode']);
}
if (User::isAuthorized()) {
+1 -1
View File
@@ -726,7 +726,7 @@ h4, .h4 {
-moz-border-radius: 3px;
-webkit-border-radius: 3px;
border-radius: 3px;
height: 15px;
/*height: 15px;*/
margin-bottom: 15px;
}
+1 -1
View File
@@ -329,4 +329,4 @@ a.fileLink:before {
/* Disabled */
.input-file input[type=file]:disabled + span {
background-color: #eee;
}
}
+27 -16
View File
@@ -19,13 +19,13 @@
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
use Core\Helpers\DDosProtection;
use Core\Models\User;
use Core\Helpers\Cache;
use Core\Models\UTM;
use Core\Template;
use Core\CoreException;
use Core\ExternalServices\Request\Request;
use Core\Helpers\Cache;
use Core\Helpers\DDosProtection;
use Core\Models\Router;
use Core\Models\User;
use Core\Models\UTM;
error_reporting(E_ALL & ~E_NOTICE & ~E_WARNING);
//error_reporting(E_ALL);
@@ -51,17 +51,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 +127,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();
+2 -2
View File
@@ -20,8 +20,8 @@
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
use Core\Helpers\SystemFunctions;
use Core\Helpers\Captcha;
require_once __DIR__ . '/bootstrap.php';
SystemFunctions::showCaptcha();
Captcha::showCaptcha();
+1 -1
View File
@@ -22,7 +22,7 @@
/**
* Версия сервиса
*/
const CORE_VERSION = '1.0.0_dev';
const CORE_VERSION = '1.0.1_dev';
/**
* Флаг отладки
@@ -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
@@ -19,28 +20,21 @@
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Core;
namespace Core\DTO\System;
use Core\Helpers\SystemFunctions;
/**
* DTO Оперативная память
*/
class Memory {
/** @var int $total Общий объем */
public int $total = 0;
class Template
{
private static array $arTemplateVariables = [];
/** @var int $used Использовано */
public int $used = 0;
public static function set(string $varName, string $varValue): void
{
$varName = '{{' . $varName . '}}';
self::$arTemplateVariables[$varName] = $varValue;
}
/** @var int $free Свободно */
public int $free = 0;
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;
}
}
/** @var float $usedPercent Использовано в процентах */
public float $usedPercent = 0;
}
@@ -0,0 +1,405 @@
<?php
/**
* 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
* 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\Request;
use Core\CoreException;
use Exception;
/**
* Класс для генерации фейковых Useragent
*/
class FakeUserAgent
{
/** @var array WINDOWS_OS */
private const WINDOWS_OS = [
'[Windows; |Windows; U; |]Windows NT 6.:number0-3:;[ Win64; x64| WOW64| x64|]',
'[Windows; |Windows; U; |]Windows NT 10.:number0-5:;[ Win64; x64| WOW64| x64|]',
];
/** @var array LINUX_OS */
private const LINUX_OS = [
'[Linux; |][U; |]Linux x86_64',
'[Linux; |][U; |]Linux i:number5-6::number4-8::number0-6: [x86_64|]',
];
/** @var array MAC_OS */
private const MAC_OS = [
'Macintosh; [U; |]Intel Mac OS X :number7-9:_:number0-9:_:number0-9:',
'Macintosh; [U; |]Intel Mac OS X 10_:number0-12:_:number0-9:',
];
/** @var array ANDROID_VERSIONS Версии Android */
private const ANDROID_VERSIONS = [
'4.3.1',
'4.4',
'4.4.1',
'4.4.4',
'5.0',
'5.0.1',
'5.0.2',
'5.1',
'5.1.1',
'6.0',
'6.0.1',
'7.0',
'7.1',
'7.1.1',
];
/** @property string $androidVersion Сгенерированная версия Android */
private string $androidVersion;
/** @var array ANDROID_DEVICES Устройства Android */
private const ANDROID_DEVICES = [
'4.3' => [
'GT-I9:number2-5:00 Build/JDQ39',
'Nokia 3:number1-3:[10|15] Build/IMM76D',
'[SAMSUNG |]SM-G3:number1-5:0[R5|I|V|A|T|S] Build/JLS36C',
'Ascend G3:number0-3:0 Build/JLS36I',
'[SAMSUNG |]SM-G3:number3-6::number1-8::number0-9:[V|A|T|S|I|R5] Build/JLS36C',
'HUAWEI G6-L:number10-11: Build/HuaweiG6-L:number10-11:',
'[SAMSUNG |]SM-[G|N]:number7-9:1:number0-8:[S|A|V|T] Build/[JLS36C|JSS15J]',
'[SAMSUNG |]SGH-N0:number6-9:5[T|V|A|S] Build/JSS15J',
'Samsung Galaxy S[4|IV] Mega GT-I:number89-95:00 Build/JDQ39',
'SAMSUNG SM-T:number24-28:5[s|a|t|v] Build/[JLS36C|JSS15J]',
'HP :number63-73:5 Notebook PC Build/[JLS36C|JSS15J]',
'HP Compaq 2:number1-3:10b Build/[JLS36C|JSS15J]',
'HTC One 801[s|e] Build/[JLS36C|JSS15J]',
'HTC One max Build/[JLS36C|JSS15J]',
'HTC Xplorer A:number28-34:0[e|s] Build/GRJ90',
],
'4.4' => [
'XT10:number5-8:0 Build/SU6-7.3',
'XT10:number12-52: Build/[KXB20.9|KXC21.5]',
'Nokia :number30-34:10 Build/IMM76D',
'E:number:20-23::number0-3::number0-4: Build/24.0.[A|B].1.34',
'[SAMSUNG |]SM-E500[F|L] Build/KTU84P',
'LG Optimus G Build/KRT16M',
'LG-E98:number7-9: Build/KOT49I',
'Elephone P:number2-6:000 Build/KTU84P',
'IQ450:number0-4: Quad Build/KOT49H',
'LG-F:number2-5:00[K|S|L] Build/KOT49[I|H]',
'LG-V:number3-7::number0-1:0 Build/KOT49I',
'[SAMSUNG |]SM-J:number1-2::number0-1:0[G|F] Build/KTU84P',
'[SAMSUNG |]SM-N80:number0-1:0 Build/[KVT49L|JZO54K]',
'[SAMSUNG |]SM-N900:number5-8: Build/KOT49H',
'[SAMSUNG-|]SGH-I337[|M] Build/[JSS15J|KOT49H]',
'[SAMSUNG |]SM-G900[W8|9D|FD|H|V|FG|A|T] Build/KOT49H',
'[SAMSUNG |]SM-T5:number30-35: Build/[KOT49H|KTU84P]',
'[Google |]Nexus :number5-7: Build/KOT49H',
'LG-H2:number0-2:0 Build/KOT49[I|H]',
'HTC One[_M8|_M9|0P6B|801e|809d|0P8B2|mini 2|S][ dual sim|] Build/[KOT49H|KTU84L]',
'[SAMSUNG |]GT-I9:number3-5:0:number0-6:[V|I|T|N] Build/KOT49H',
'Lenovo P7:number7-8::number1-6: Build/[Lenovo|JRO03C]',
'LG-D95:number1-8: Build/KOT49[I|H]',
'LG-D:number1-8::number0-8:0 Build/KOT49[I|H]',
'Nexus5 V:number6-7:.1 Build/KOT49H',
'Nexus[_|] :number4-10: Build/[KOT49H|KTU84P]',
'Nexus[_S_| S ][4G |]Build/GRJ22',
'[HM NOTE|NOTE-III|NOTE2 1LTE[TD|W|T]',
'ALCATEL ONE[| ]TOUCH 70:number2-4::number0-9:[X|D|E|A] Build/KOT49H',
'MOTOROLA [MOTOG|MSM8960|RAZR] Build/KVT49L',
],
'5.0' => [
'Nokia :number10-11:00 [wifi|4G|LTE] Build/GRK39F',
'HTC 80:number1-2[s|w|e|t] Build/[LRX22G|JSS15J]',
'Lenovo A7000-a Build/LRX21M;',
'HTC Butterfly S [901|919][s|d|] Build/LRX22G',
'HTC [M8|M9|M8 Pro Build/LRX22G',
'LG-D3:number25-37: Build/LRX22G',
'LG-D72:number0-9: Build/LRX22G',
'[SAMSUNG |]SM-G4:number0-9:0 Build/LRX22[G|C]',
'[|SAMSUNG ]SM-G9[00|25|20][FD|8|F|F-ORANGE|FG|FQ|H|I|L|M|S|T] Build/[LRX21T|KTU84F|KOT49H]',
'[SAMSUNG |]SM-A:number7-8:00[F|I|T|H|] Build/[LRX22G|LMY47X]',
'[SAMSUNG-|]SM-N91[0|5][A|V|F|G|FY] Build/LRX22C',
'[SAMSUNG |]SM-[T|P][350|550|555|355|805|800|710|810|815] Build/LRX22G',
'LG-D7:number0-2::number0-9: Build/LRX22G',
'[LG|SM]-[D|G]:number8-9::number0-5::number0-9:[|P|K|T|I|F|T1] Build/[LRX22G|KOT49I|KVT49L|LMY47X]',
],
'5.1' => [
'Nexus :number5-9: Build/[LMY48B|LRX22C]',
'[|SAMSUNG ]SM-G9[28|25|20][X|FD|8|F|F-ORANGE|FG|FQ|H|I|L|M|S|T] Build/[LRX22G|LMY47X]',
'[|SAMSUNG ]SM-G9[35|350][X|FD|8|F|F-ORANGE|FG|FQ|H|I|L|M|S|T] Build/[MMB29M|LMY47X]',
'[MOTOROLA |][MOTO G|MOTO G XT1068|XT1021|MOTO E XT1021|MOTO XT1580|MOTO X FORCE XT1580|MOTO X PLAY XT1562|MOTO XT1562|MOTO XT1575|MOTO X PURE XT1575|MOTO XT1570 MOTO X STYLE] Build/[LXB22|LMY47Z|LPC23|LPK23|LPD23|LPH223]',
],
'6.0' => [
'[SAMSUNG |]SM-[G|D][920|925|928|9350][V|F|I|L|M|S|8|I] Build/[MMB29K|MMB29V|MDB08I|MDB08L]',
'Nexus :number5-7:[P|X|] Build/[MMB29K|MMB29V|MDB08I|MDB08L]',
'HTC One[_| ][M9|M8|M8 Pro] Build/MRA58K',
'HTC One[_M8|_M9|0P6B|801e|809d|0P8B2|mini 2|S][ dual sim|] Build/MRA58K',
],
'7.0' => [
'Pixel [XL|C] Build/[NRD90M|NME91E]',
'Nexus :number5-9:[X|P|] Build/[NPD90G|NME91E]',
'[SAMSUNG |]GT-I:number91-98:00 Build/KTU84P',
'Xperia [V |]Build/NDE63X',
'LG-H:number90-93:0 Build/NRD90[C|M]',
],
'7.1' => [
'Pixel [XL|C] Build/[NRD90M|NME91E]',
'Nexus :number5-9:[X|P|] Build/[NPD90G|NME91E]',
'[SAMSUNG |]GT-I:number91-98:00 Build/KTU84P',
'Xperia [V |]Build/NDE63X',
'LG-H:number90-93:0 Build/NRD90[C|M]',
],
];
/** @var array ANDROID_OS Строки названия ОС, используемые на Android */
private const ANDROID_OS = [
'Linux; Android :androidVersion:; :androidDevice:',
'Linux; U; Android :androidVersion:; :androidDevice:',
'Android; Android :androidVersion:; :androidDevice:',
];
/** @var array MOBILE_IOS Строки названия ОС, используемые на IOS */
private const MOBILE_IOS = [
'iphone' => 'iPhone; CPU iPhone OS :number7-11:_:number0-9:_:number0-9:; like Mac OS X;',
'ipad' => 'iPad; CPU iPad OS :number7-11:_:number0-9:_:number0-9: like Mac OS X;',
'ipod' => 'iPod; CPU iPod OS :number7-11:_:number0-9:_:number0-9:; like Mac OS X;',
];
/**
* Генерация случайной операционной системы
*
* @param null|string $os Операционная система
*
* @return string Строка ОС
* @throws Exception
*/
private function getOS(?string $os = null): string
{
$_os = [];
if ($os === null || in_array($os, ['chrome', 'firefox', 'explorer'])) {
$_os = $os === 'explorer' ? self::WINDOWS_OS : array_merge(self::WINDOWS_OS, self::LINUX_OS, self::MAC_OS);
} else {
$_os += constant('self::' . strtoupper($os) . '_OS');
}
// Случайный выбор ОС
$selectedOS = rtrim($_os[random_int(0, count($_os) - 1)], ';');
if (strpos($selectedOS, '[') !== false) {
$selectedOS = self::processSpinSyntax($selectedOS);
}
if (strpos($selectedOS, ':number') !== false) {
$selectedOS = self::processRandomNumbers($selectedOS);
}
if (random_int(1, 100) > 50) {
$selectedOS .= '; en-US';
}
return $selectedOS;
}
/**
* Генерация случайной мобильной ОС
* ОС можно указать android, iphone, ipad, ipod, или null для случайной генерации
*
* @param null|string $os ОС
*
* @return string Строка ОС
* @throws Exception
*/
private function getMobileOS(string $os = null): string
{
$os = strtolower($os);
$_os = [];
switch ($os) {
case'android':
$_os += self::ANDROID_OS;
break;
case 'iphone':
case 'ipad':
case 'ipod':
$_os[] = self::MOBILE_IOS[$os];
break;
default:
$_os = array_merge(self::ANDROID_OS, array_values(self::MOBILE_IOS));
}
// Выбираем случайную мобильную ОС
$selectedOS = rtrim($_os[random_int(0, count($_os) - 1)], ';');
if (strpos($selectedOS, ':androidVersion:') !== false) {
$selectedOS = $this->processAndroidVersion($selectedOS);
}
if (strpos($selectedOS, ':androidDevice:') !== false) {
$selectedOS = $this->addAndroidDevice($selectedOS);
}
if (strpos($selectedOS, ':number') !== false) {
$selectedOS = self::processRandomNumbers($selectedOS);
}
return $selectedOS;
}
/**
* @param $selectedOS
*
* @return null|string|string[]
* @throws Exception
*/
private static function processRandomNumbers($selectedOS)
{
return preg_replace_callback(
'/:number(\d+)-(\d+):/i',
function ($matches) {
return random_int($matches[1], $matches[2]);
},
$selectedOS
);
}
/**
* @param $selectedOS
*
* @return null|string|string[]
*/
private static function processSpinSyntax($selectedOS)
{
return preg_replace_callback(
'/\[([\w\-\s|;]*?)\]/i',
function ($matches) {
$shuffle = explode('|', $matches[1]);
return $shuffle[array_rand($shuffle)];
},
$selectedOS
);
}
/**
* @param $selectedOS
*
* @return null|string|string[]
*/
private function processAndroidVersion($selectedOS)
{
$this->androidVersion = $version = self::ANDROID_VERSIONS[array_rand(self::ANDROID_VERSIONS)];
return preg_replace_callback(
'/:androidVersion:/i',
function ($matches) use ($version) {
return $version;
},
$selectedOS
);
}
/**
* @param $selectedOS
*
* @return null|string|string[]
*/
private function addAndroidDevice($selectedOS)
{
$devices = self::ANDROID_DEVICES[substr($this->androidVersion, 0, 3)];
$device = $devices[array_rand($devices)];
$device = self::processSpinSyntax($device);
return preg_replace_callback('/:androidDevice:/i', function ($matches) use ($device) {
return $device;
}, $selectedOS);
}
/**
* Генерация версии Chrome
*
* @param array $version Параметры версии
*
* @return string Результат
* @throws Exception
*/
private static function chromeVersion(array $version): string
{
return random_int($version['min'], $version['max']) . '.0.' . random_int(1000, 4000) . '.' . random_int(100, 400);
}
/**
* Генерация версии Firefox
*
* @param array $version Параметры версии
*
* @return string Результат
* @throws Exception
*/
private static function firefoxVersion(array $version): string
{
return random_int($version['min'], $version['max']) . '.' . random_int(0, 9);
}
/**
* Генерация версии Windows
*
* @param array $version Параметры версии
*
* @return string Результат
* @throws Exception
*/
private static function windows(array $version): string
{
return random_int($version['min'], $version['max']) . '.' . random_int(0, 9);
}
/**
* @param string|null $userAgent
*
* @return string
* @throws Exception
*/
public function generate(?string $userAgent = null): string
{
if ($userAgent === null) {
$r = random_int(0, 100);
if ($r >= 44) {
$userAgent = array_rand(['firefox' => 1, 'chrome' => 1, 'explorer' => 1]);
} else {
$userAgent = array_rand(['iphone' => 1, 'android' => 1, 'mobile' => 1]);
}
} elseif ($userAgent == 'windows' || $userAgent == 'mac' || $userAgent == 'linux') {
$agents = ['firefox' => 1, 'chrome' => 1];
if ($userAgent == 'windows') {
$agents['explorer'] = 1;
}
$userAgent = array_rand($agents);
}
$_SESSION['agent'] = $userAgent;
if ($userAgent == 'chrome') {
return 'Mozilla/5.0 (' . $this->getOS($userAgent) . ') AppleWebKit/'
. (random_int(1, 100) > 50 ? random_int(533, 537) : random_int(600, 603))
. '.' . random_int(1, 50) . ' (KHTML, like Gecko) Chrome/'
. self::chromeVersion(['min' => 47, 'max' => 55,]) . ' Safari/'
. (random_int(1, 100) > 50 ? random_int(533, 537 ) : random_int(600, 603));
} elseif ($userAgent == 'firefox') {
return 'Mozilla/5.0 (' . $this->getOS($userAgent) . ') Gecko/'
. (random_int(1, 100) > 30 ? '20100101' : '20130401') . ' Firefox/'
. self::firefoxVersion(['min' => 45, 'max' => 74,]);
} elseif ($userAgent == 'explorer') {
return 'Mozilla / 5.0 (compatible; MSIE ' . ($int = random_int(7, 11)) . '.0; '
. $this->getOS('windows') . ' Trident / ' . ($int == 7 || $int == 8 ? '4' : ($int == 9 ? '5' : ($int== 10 ? '6' : '7'))) . '.0)';
} elseif ($userAgent == 'mobile' || $userAgent == 'android' || $userAgent == 'iphone' || $userAgent == 'ipad' || $userAgent == 'ipod') {
return 'Mozilla/5.0 (' . $this->getMobileOS($userAgent) . ') AppleWebKit/'
. (random_int(1, 100) > 50 ? random_int(533, 537) : random_int(600, 603)) . '.' . random_int(1, 50)
. ' (KHTML, like Gecko) Chrome/' . self::chromeVersion(['min' => 47, 'max' => 55,]) . ' Mobile Safari/'
. (random_int(1, 100) > 50 ? random_int(533, 537) : random_int(600, 603)) . '.' . random_int(0, 9);
}
return 'undefined';
}
}
@@ -0,0 +1,143 @@
<?php
/**
* 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
* 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\Request;
use Throwable;
/**
* Класс запросов к внешним системам
*/
class Request
{
/** @var string $baseUrl Базовый адрес */
private string $baseUrl;
/** @var int $httpCode Код ответа */
private int $httpCode = 0;
/** @var string $responseBody Тело ответа */
private string $responseBody = '';
/** @var string $responseHeader Заголовки ответа */
private string $responseHeader = '';
/** @var string[] Заголовки запроса */
private array $requestHeaders = [];
/** @var int[] Успешные коды ответов */
private const SUCCESS_HTTP_CODES = [
200,
202,
203,
204,
205,
206,
207,
226,
];
/**
* Коструктор
*
* @param string $baseUrl Базовый адрес
*/
public function __construct(string $baseUrl)
{
$this->baseUrl = $baseUrl;
try {
$this->requestHeaders = ['User-Agent: ' . (new FakeUserAgent())->generate()];
} catch (Throwable $e) {
$this->requestHeaders = ['User-Agent: Chrome'];
}
return $this;
}
/**
* POST запрос
*
* @param array $data Данные
*
* @return $this
*/
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);
curl_setopt($ch, CURLOPT_HTTPHEADER, $this->requestHeaders);
$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 string Заголовки ответа
*/
public function getHeaders(): string
{
return $this->responseHeader;
}
}
@@ -23,7 +23,7 @@
use Core\CoreException;
class Request
class RequestOLD
{
private $httpStatus = null;
+108
View File
@@ -0,0 +1,108 @@
<?php
/**
* 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
* 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;
/**
* Класс для работы с Captcha
*/
class Captcha {
/**
* Генерация и отображение картинки-каптчи
*
* @param string|null $code Код
*
* @return void
*/
public static function showCaptcha(?string $code = null): void
{
if ($code === null) {
$code = SystemFunctions::generateCode(8, 8);
$_SESSION['captchaCode'] = $code;
}
$width = 80;
$height = 30;
$img = imagecreate($width, $height);
// Задаем фон
imagecolorallocate($img, 255, 255, 255);
// Задаем цвета
$lineColor = imagecolorallocate($img, 150, 150, 150);
$pixelColor = imagecolorallocate($img, 150, 150, 150);
$whiteColor = imagecolorallocate($img, 180, 255, 180);
$blackColor = imagecolorallocate($img, 0, 0, 0);
// Рисуем линии 1
for ($i = 0; $i < 3; $i++) {
$x1 = 0;
$x2 = $width;
$y1 = rand(0, $height);
$y2 = rand(00, $height);
imageline($img, $x1, $y1, $x2, $y2, $lineColor);
}
// Рисуем линии 2
for ($i = 0; $i < 3; $i++) {
$x1 = rand(0, $width);
$x2 = rand(0, $width);
$y1 = 0;
$y2 = $height;
imageline($img, $x1, $y1, $x2, $y2, $lineColor);
}
// Рисуем пиксели
for ($i = 0; $i < 200; $i++) {
imagesetpixel($img, rand() % $width, rand() % $height, $pixelColor);
}
// Рисуем тень для кода
imagestring($img, 5, 4, 7, $code, $blackColor);
imagestring($img, 5, 6, 7, $code, $blackColor);
imagestring($img, 5, 5, 6, $code, $blackColor);
imagestring($img, 5, 5, 8, $code, $blackColor);
// Рисуем сам код
imagestring($img, 5, 5, 7, $code, $whiteColor); //main
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s', 10000) . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Content-Type: image/png');
imagepng($img);
}
/**
* Проверка кода каптчи
*
* @param int $code Код
*
* @return bool Результат валидации
*/
public static function isValidCaptcha(string $code): bool
{
return (string)$_SESSION['captchaCode'] === $code;
}
}
+62 -216
View File
@@ -23,6 +23,7 @@
use Core\CoreException;
use Core\DTO\System\Memory;
/**
* Класс вспомогательных методов
@@ -153,102 +154,31 @@
*/
public static function generatePassword(int $number = 10, bool $useSpecialChars = true): string
{
$number = ($number > 0) ? $number : 1;
$arChars = [
'a',
'b',
'c',
'd',
'e',
'f',
'g',
'h',
'i',
'j',
'k',
'l',
'm',
'n',
'o',
'p',
'r',
's',
't',
'u',
'v',
'x',
'y',
'z',
'A',
'B',
'C',
'D',
'E',
'F',
'G',
'H',
'I',
'J',
'K',
'L',
'M',
'N',
'O',
'P',
'R',
'S',
'T',
'U',
'V',
'X',
'Y',
'Z',
'1',
'2',
'3',
'4',
'5',
'6',
'7',
'8',
'9',
'0',
$number = ($number > 0) ? $number : 1;
$arChars = [
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
'k', 'l', 'm', 'n', 'o', 'p', 'r', 's', 't', 'u',
'v', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F',
'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
'R', 'S', 'T', 'U', 'V', 'X', 'Y', 'Z', '1', '2',
'3', '4', '5', '6', '7', '8', '9', '0',
];
$arSpecialChars = [
'(',
')',
'[',
']',
'!',
'?',
'&',
'^',
'%',
'@',
'*',
'$',
'<',
'>',
'/',
'|',
'+',
'-',
'{',
'}',
'~',
'(', ')', '[', ']', '!', '?', '&', '^', '%', '@',
'*', '$', '<', '>', '/', '|', '+', '-', '{', '}',
'~',
];
if ($useSpecialChars) {
$arChars = array_merge($arChars, $arSpecialChars);
}
$pass = '';
$password = '';
for ($i = 0; $i < $number; $i++) {
$index = rand(0, count($arChars) - 1);
$pass .= $arChars[$index];
$password .= $arChars[$index];
}
return $pass;
return $password;
}
@@ -369,7 +299,7 @@
/**
* Метод для склонения слов в зависимости от числа
* Пример: numWord($secs, array('секунда', 'секунды', 'секунд'))
* Пример: numWord($secs, ['секунда', 'секунды', 'секунд'])
*
* @param int $value Число
* @param array $words Массив слов
@@ -658,6 +588,7 @@
* @param array $arData Массив данных
*
* @return void
* @throws \Exception
*/
public static function arrayToXml(array $arData = [], ?string $objectName = null): string
{
@@ -678,16 +609,6 @@
return $dom->saveXML();
}
public static function showPage()
{
$loader = new \Twig\Loader\FilesystemLoader(PATH_TO_TEMPLATES);
$twig = new \Twig\Environment($loader, [
'cache' => CACHE_DIR,
]);
echo $twig->render('index.tpl', ['name' => 'Roman']);
}
/**
* Сравнение текстов
*
@@ -758,60 +679,13 @@
return $count;
}
/**
* Получение данных об оперативной памяти площадки
*
* @param bool $humanView Флаг человеческого представления данных
*
* @return int[] Данные о памяти
*/
public static function getHostMemoryInfo(bool $humanView = false): array
{
$fh = fopen('/proc/meminfo', 'rb');
$result = [
'total' => 0,
'free' => 0,
'swapTotal' => 0,
'swapFree' => 0,
];
while ($line = fgets($fh)) {
if (preg_match('/^MemTotal:\s+(\d+)\skB$/', $line, $matches)) {
$result['total'] = (int)$matches[1] * 1024;
}
unset($matches);
if (preg_match('/^MemFree:\s+(\d+)\skB$/', $line, $matches)) {
$result['free'] = (int)$matches[1] * 1024;
}
unset($matches);
if (preg_match('/^SwapFree:\s+(\d+)\skB$/', $line, $matches)) {
$result['swapTotal'] = (int)$matches[1] * 1024;
}
unset($matches);
if (preg_match('/^SwapFree:\s+(\d+)\skB$/', $line, $matches)) {
$result['swapFree'] = (int)$matches[1] * 1024;
}
unset($matches);
}
fclose($fh);
if ($humanView) {
$result = array_map(static function ($el) {
return self::convertBytes($el);
}, $result);
}
return $result;
}
/**
* Парсинг логов nginx
*
* @param string $logPath Путь до файла логов
* @param bool $isOnlyCount Только получение количества
* @param string|null $limit Ограничение выборки "0, 10"
* @param bool $isReverse Реверсировать выборку
* @param string $logPath Путь до файла логов
* @param bool $isOnlyCount Только получение количества
* @param string|null $limit Ограничение выборки "0, 10"
* @param bool $isReverse Перевернуть выборку
*
* @return array|int
* @throws CoreException
@@ -880,7 +754,8 @@
}
/**
* Возвращает кусок текстового содерживого с подсвеченной строкой
* Возвращает кусок текстового содержимого с подсвеченной строкой
*
* @param string $fileText Текст
* @param int $lineNum Номер строки
*
@@ -921,6 +796,7 @@
$textBefore = '<div style="border:1px solid black">';
$textAfter = '</div>';
return $textBefore . implode(PHP_EOL . PHP_EOL, $result) . $textAfter;
}
@@ -968,6 +844,9 @@
/**
* Генерация кода для каптчи
*
* TODO: реализовать схожий с генерацией пароля механизм
*
* @param int $min Минимальное количество символов
* @param int $max Максимальное количество символов
*
@@ -992,83 +871,50 @@
}
/**
* Генерация и отображение картинки-каптчи
* Получение информации о памяти сервера
*
* @param string|null $code Код
*
* @return void
* @return Memory DTO использования памяти
*/
public static function showCaptcha(?string $code = null): void
public static function getMemoryUse(): Memory
{
if ($code === null) {
$code = self::generateCode(8, 8);
$_SESSION['captchaCode'] = $code;
$memoryObject = new Memory();
$memoryTotal = null;
$memoryFree = null;
if (!is_readable('/proc/meminfo')) {
return $memoryObject;
}
$stats = @file_get_contents('/proc/meminfo');
if ($stats === false) {
return $memoryObject;
}
$width = 80;
$height = 30;
$img = imagecreate($width, $height);
$stats = str_replace("\r", '', $stats);
$stats = explode(PHP_EOL, $stats);
foreach ($stats as $statLine) {
$statLineData = explode(':', trim($statLine));
// Задаем фон
imagecolorallocate($img, 255, 255, 255);
// Всего
if (count($statLineData) == 2 && trim($statLineData[0]) == 'MemTotal') {
$memoryTotal = trim($statLineData[1]);
$memoryTotal = explode(' ', $memoryTotal);
$memoryTotal = $memoryTotal[0];
$memoryTotal *= 1024;
}
// Задаем цвета
$lineColor = imagecolorallocate($img, 150, 150, 150);
$pixelColor = imagecolorallocate($img, 150, 150, 150);
$whiteColor = imagecolorallocate($img, 180, 255, 180);
$blackColor = imagecolorallocate($img, 0, 0, 0);
// Рисуем линии 1
for ($i = 0; $i < 3; $i++) {
$x1 = 0;
$x2 = $width;
$y1 = rand(0, $height);
$y2 = rand(00, $height);
imageline($img, $x1, $y1, $x2, $y2, $lineColor);
// Свободно
if (count($statLineData) == 2 && trim($statLineData[0]) == 'MemFree') {
$memoryFree = trim($statLineData[1]);
$memoryFree = explode(' ', $memoryFree);
$memoryFree = $memoryFree[0];
$memoryFree *= 1024;
}
}
// Рисуем линии 2
for ($i = 0; $i < 3; $i++) {
$x1 = rand(0, $width);
$x2 = rand(0, $width);
$y1 = 0;
$y2 = $height;
imageline($img, $x1, $y1, $x2, $y2, $lineColor);
}
$memoryObject->total = $memoryTotal;
$memoryObject->free = $memoryFree;
$memoryObject->used = $memoryTotal - $memoryFree;
$memoryObject->usedPercent = 100 - ($memoryFree * 100 / $memoryTotal);
// Рисуем пиксели
for ($i = 0; $i < 200; $i++) {
imagesetpixel($img, rand() % $width, rand() % $height, $pixelColor);
}
// Рисуем тень для кода
imagestring($img, 5, 4, 7, $code, $blackColor);
imagestring($img, 5, 6, 7, $code, $blackColor);
imagestring($img, 5, 5, 6, $code, $blackColor);
imagestring($img, 5, 5, 8, $code, $blackColor);
// Рисуем сам код
imagestring($img, 5, 5, 7, $code, $whiteColor); //main
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s', 10000) . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Content-Type: image/png');
imagepng($img);
}
/**
* Проверка кода каптчи
*
* @param int $code Код
*
* @return bool Результат валидации
*/
public static function isValidCaptcha(string $code): bool
{
return (string)$_SESSION['captchaCode'] === $code;
return $memoryObject;
}
}
+5 -2
View File
@@ -98,7 +98,6 @@
$i = 0;
foreach ($frazes as $post) {
//sendTelegram($post);
$text = str_replace('<br />', PHP_EOL, $post);
$text = htmlspecialchars_decode($text);
$text = str_replace('\'', '\\\'', $text);
@@ -109,8 +108,12 @@
$itemId = $DB->addItem('bashorg', ['hash' => $hash, 'text' => $text]);
sendTelegram('<b>Добавлена цитата ID ' . $itemId . ' (' . $page . ' страница)</b>' . PHP_EOL . $text);
}
$text = null;
}
sleep(2);
$DB = null;
$hash = null;
$file = null;
//sleep(2);
if ($i < 1) {
throw new CoreException('Не найдено новых данных для добавления');
}
+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;
File renamed without changes.
Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 45 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 53 KiB

View File
File renamed without changes.
File renamed without changes.