[*] небольшой рефакторинг SystemFunctions.class.php

[*] исправлен прогресс бар в диспетчере очереди (теперь показывает проценты корректно и меняет цвет в зависимости от нагрузки)
This commit is contained in:
rsgrinko committed 2023-10-08 00:42:36 +03:00
1 parent 9decebf051
commit cf50026ce5
9 files changed
+231 -225

No files matched your search

+13 -4
View File
@@ -196,12 +196,21 @@
<?php <?php
$result['memory'] = ob_get_clean(); $result['memory'] = ob_get_clean();
ob_start(); 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 class="progress">
<div style="width: <?= round(($memory['free'] + $memory['swapFree']) / ($memory['total'] + $memory['swapTotal']) * 100, 2); ?>%" aria-valuemax="100" aria-valuemin="0" <div style="width: <?= round($memory->usedPercent, 2); ?>%" aria-valuemax="100" aria-valuemin="0"
aria-valuenow="40" role="progressbar" class="progress-bar progress-bar-warning"> aria-valuenow="<?= round($memory->usedPercent); ?>" role="progressbar" class="progress-bar <?= $progressClass; ?>">
<span class="sr-only">40% Complete (success)</span> <span><?= round($memory->usedPercent, 2); ?>%</span>
</div> </div>
</div> </div>
<?php <?php
+2 -2
View File
@@ -19,7 +19,7 @@
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/ */
use Core\Helpers\SystemFunctions; use Core\Helpers\Captcha;
use Core\Models\User; use Core\Models\User;
use Core\CoreException; use Core\CoreException;
@@ -27,7 +27,7 @@
$captchaCorrect = true; $captchaCorrect = true;
if (USE_CAPTCHA) { if (USE_CAPTCHA) {
$captchaCorrect = isset($_REQUEST['captchaCode']) && SystemFunctions::isValidCaptcha($_REQUEST['captchaCode']); $captchaCorrect = isset($_REQUEST['captchaCode']) && Captcha::isValidCaptcha($_REQUEST['captchaCode']);
} }
if (User::isAuthorized()) { if (User::isAuthorized()) {
+2 -2
View File
@@ -19,7 +19,7 @@
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/ */
use Core\Helpers\SystemFunctions; use Core\Helpers\Captcha;
use Core\Models\User; use Core\Models\User;
use Core\CoreException; use Core\CoreException;
@@ -27,7 +27,7 @@
$captchaCorrect = true; $captchaCorrect = true;
if (USE_CAPTCHA) { if (USE_CAPTCHA) {
$captchaCorrect = isset($_REQUEST['captchaCode']) && SystemFunctions::isValidCaptcha($_REQUEST['captchaCode']); $captchaCorrect = isset($_REQUEST['captchaCode']) && Captcha::isValidCaptcha($_REQUEST['captchaCode']);
} }
if (User::isAuthorized()) { if (User::isAuthorized()) {
+1 -1
View File
@@ -726,7 +726,7 @@ h4, .h4 {
-moz-border-radius: 3px; -moz-border-radius: 3px;
-webkit-border-radius: 3px; -webkit-border-radius: 3px;
border-radius: 3px; border-radius: 3px;
height: 15px; /*height: 15px;*/
margin-bottom: 15px; margin-bottom: 15px;
} }
+2 -2
View File
@@ -20,8 +20,8 @@
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/ */
use Core\Helpers\SystemFunctions; use Core\Helpers\Captcha;
require_once __DIR__ . '/bootstrap.php'; require_once __DIR__ . '/bootstrap.php';
SystemFunctions::showCaptcha(); Captcha::showCaptcha();
+40
View File
@@ -0,0 +1,40 @@
<?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\DTO\System;
/**
* DTO Оперативная память
*/
class Memory {
/** @var int $total Общий объем */
public int $total = 0;
/** @var int $used Использовано */
public int $used = 0;
/** @var int $free Свободно */
public int $free = 0;
/** @var float $usedPercent Использовано в процентах */
public float $usedPercent = 0;
}
+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;
}
}
+58 -212
View File
@@ -23,6 +23,7 @@
use Core\CoreException; use Core\CoreException;
use Core\DTO\System\Memory;
/** /**
* Класс вспомогательных методов * Класс вспомогательных методов
@@ -154,88 +155,17 @@
public static function generatePassword(int $number = 10, bool $useSpecialChars = true): string public static function generatePassword(int $number = 10, bool $useSpecialChars = true): string
{ {
$number = ($number > 0) ? $number : 1; $number = ($number > 0) ? $number : 1;
$arChars = [ $arChars = [
'a', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
'b', 'k', 'l', 'm', 'n', 'o', 'p', 'r', 's', 't', 'u',
'c', 'v', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F',
'd', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
'e', 'R', 'S', 'T', 'U', 'V', 'X', 'Y', 'Z', '1', '2',
'f', '3', '4', '5', '6', '7', '8', '9', '0',
'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 = [ $arSpecialChars = [
'(', '(', ')', '[', ']', '!', '?', '&', '^', '%', '@',
')', '*', '$', '<', '>', '/', '|', '+', '-', '{', '}',
'[',
']',
'!',
'?',
'&',
'^',
'%',
'@',
'*',
'$',
'<',
'>',
'/',
'|',
'+',
'-',
'{',
'}',
'~', '~',
]; ];
@@ -243,12 +173,12 @@
$arChars = array_merge($arChars, $arSpecialChars); $arChars = array_merge($arChars, $arSpecialChars);
} }
$pass = ''; $password = '';
for ($i = 0; $i < $number; $i++) { for ($i = 0; $i < $number; $i++) {
$index = rand(0, count($arChars) - 1); $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 int $value Число
* @param array $words Массив слов * @param array $words Массив слов
@@ -658,6 +588,7 @@
* @param array $arData Массив данных * @param array $arData Массив данных
* *
* @return void * @return void
* @throws \Exception
*/ */
public static function arrayToXml(array $arData = [], ?string $objectName = null): string public static function arrayToXml(array $arData = [], ?string $objectName = null): string
{ {
@@ -678,16 +609,6 @@
return $dom->saveXML(); 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; 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 * Парсинг логов nginx
* *
* @param string $logPath Путь до файла логов * @param string $logPath Путь до файла логов
* @param bool $isOnlyCount Только получение количества * @param bool $isOnlyCount Только получение количества
* @param string|null $limit Ограничение выборки "0, 10" * @param string|null $limit Ограничение выборки "0, 10"
* @param bool $isReverse Реверсировать выборку * @param bool $isReverse Перевернуть выборку
* *
* @return array|int * @return array|int
* @throws CoreException * @throws CoreException
@@ -880,7 +754,8 @@
} }
/** /**
* Возвращает кусок текстового содерживого с подсвеченной строкой * Возвращает кусок текстового содержимого с подсвеченной строкой
*
* @param string $fileText Текст * @param string $fileText Текст
* @param int $lineNum Номер строки * @param int $lineNum Номер строки
* *
@@ -921,6 +796,7 @@
$textBefore = '<div style="border:1px solid black">'; $textBefore = '<div style="border:1px solid black">';
$textAfter = '</div>'; $textAfter = '</div>';
return $textBefore . implode(PHP_EOL . PHP_EOL, $result) . $textAfter; return $textBefore . implode(PHP_EOL . PHP_EOL, $result) . $textAfter;
} }
@@ -968,6 +844,9 @@
/** /**
* Генерация кода для каптчи * Генерация кода для каптчи
*
* TODO: реализовать схожий с генерацией пароля механизм
*
* @param int $min Минимальное количество символов * @param int $min Минимальное количество символов
* @param int $max Максимальное количество символов * @param int $max Максимальное количество символов
* *
@@ -992,83 +871,50 @@
} }
/** /**
* Генерация и отображение картинки-каптчи * Получение информации о памяти сервера
* *
* @param string|null $code Код * @return Memory DTO использования памяти
*
* @return void
*/ */
public static function showCaptcha(?string $code = null): void public static function getMemoryUse(): Memory
{ {
if ($code === null) { $memoryObject = new Memory();
$code = self::generateCode(8, 8); $memoryTotal = null;
$_SESSION['captchaCode'] = $code; $memoryFree = null;
if (!is_readable('/proc/meminfo')) {
return $memoryObject;
}
$stats = @file_get_contents('/proc/meminfo');
if ($stats === false) {
return $memoryObject;
} }
$width = 80; $stats = str_replace("\r", '', $stats);
$height = 30; $stats = explode(PHP_EOL, $stats);
$img = imagecreate($width, $height); 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);
$lineColor = imagecolorallocate($img, 150, 150, 150); $memoryTotal = $memoryTotal[0];
$pixelColor = imagecolorallocate($img, 150, 150, 150); $memoryTotal *= 1024;
$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++) { if (count($statLineData) == 2 && trim($statLineData[0]) == 'MemFree') {
$x1 = rand(0, $width); $memoryFree = trim($statLineData[1]);
$x2 = rand(0, $width); $memoryFree = explode(' ', $memoryFree);
$y1 = 0; $memoryFree = $memoryFree[0];
$y2 = $height; $memoryFree *= 1024;
imageline($img, $x1, $y1, $x2, $y2, $lineColor); }
} }
// Рисуем пиксели $memoryObject->total = $memoryTotal;
for ($i = 0; $i < 200; $i++) { $memoryObject->free = $memoryFree;
imagesetpixel($img, rand() % $width, rand() % $height, $pixelColor); $memoryObject->used = $memoryTotal - $memoryFree;
} $memoryObject->usedPercent = 100 - ($memoryFree * 100 / $memoryTotal);
// Рисуем тень для кода return $memoryObject;
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;
} }
} }
+5 -2
View File
@@ -98,7 +98,6 @@
$i = 0; $i = 0;
foreach ($frazes as $post) { foreach ($frazes as $post) {
//sendTelegram($post);
$text = str_replace('<br />', PHP_EOL, $post); $text = str_replace('<br />', PHP_EOL, $post);
$text = htmlspecialchars_decode($text); $text = htmlspecialchars_decode($text);
$text = str_replace('\'', '\\\'', $text); $text = str_replace('\'', '\\\'', $text);
@@ -109,8 +108,12 @@
$itemId = $DB->addItem('bashorg', ['hash' => $hash, 'text' => $text]); $itemId = $DB->addItem('bashorg', ['hash' => $hash, 'text' => $text]);
sendTelegram('<b>Добавлена цитата ID ' . $itemId . ' (' . $page . ' страница)</b>' . PHP_EOL . $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) { if ($i < 1) {
throw new CoreException('Не найдено новых данных для добавления'); throw new CoreException('Не найдено новых данных для добавления');
} }