Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0c15ce2ed0 | ||
|
|
b4f506cc1f | ||
|
|
c54cb5f9e1 | ||
|
|
8cb0b860ea | ||
|
|
0146815e2d | ||
|
|
9708ec5419 | ||
|
|
12ee13c3d1 | ||
|
|
890d9b8e0d | ||
|
|
3f9dc5cd0b | ||
|
|
a110e5d03e | ||
|
|
f6d6a88332 | ||
|
|
7c99505d9b | ||
|
|
0196d50ede | ||
|
|
f12c463c7a | ||
|
|
e740b13654 | ||
|
|
9cf87af0f7 | ||
|
|
0bf6f25a88 | ||
|
|
198b088727 | ||
|
|
52937271de | ||
|
|
ca18c4dc25 | ||
|
|
a7cf48bac6 | ||
|
|
b2cdbad1fa | ||
|
|
cf50026ce5 | ||
|
|
9decebf051 | ||
|
|
5cd5a528f1 |
No files matched your search
@@ -0,0 +1,38 @@
|
||||
---
|
||||
name: Bug report
|
||||
about: Create a report to help us improve
|
||||
title: ''
|
||||
labels: ''
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
**Describe the bug**
|
||||
A clear and concise description of what the bug is.
|
||||
|
||||
**To Reproduce**
|
||||
Steps to reproduce the behavior:
|
||||
1. Go to '...'
|
||||
2. Click on '....'
|
||||
3. Scroll down to '....'
|
||||
4. See error
|
||||
|
||||
**Expected behavior**
|
||||
A clear and concise description of what you expected to happen.
|
||||
|
||||
**Screenshots**
|
||||
If applicable, add screenshots to help explain your problem.
|
||||
|
||||
**Desktop (please complete the following information):**
|
||||
- OS: [e.g. iOS]
|
||||
- Browser [e.g. chrome, safari]
|
||||
- Version [e.g. 22]
|
||||
|
||||
**Smartphone (please complete the following information):**
|
||||
- Device: [e.g. iPhone6]
|
||||
- OS: [e.g. iOS8.1]
|
||||
- Browser [e.g. stock browser, safari]
|
||||
- Version [e.g. 22]
|
||||
|
||||
**Additional context**
|
||||
Add any other context about the problem here.
|
||||
@@ -0,0 +1,20 @@
|
||||
---
|
||||
name: Feature request
|
||||
about: Suggest an idea for this project
|
||||
title: ''
|
||||
labels: ''
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
**Is your feature request related to a problem? Please describe.**
|
||||
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
|
||||
|
||||
**Describe the solution you'd like**
|
||||
A clear and concise description of what you want to happen.
|
||||
|
||||
**Describe alternatives you've considered**
|
||||
A clear and concise description of any alternative solutions or features you've considered.
|
||||
|
||||
**Additional context**
|
||||
Add any other context or screenshots about the feature request here.
|
||||
@@ -0,0 +1,38 @@
|
||||
# This workflow uses actions that are not certified by GitHub.
|
||||
# They are provided by a third-party and are governed by
|
||||
# separate terms of service, privacy policy, and support
|
||||
# documentation.
|
||||
|
||||
name: Psalm Security Scan
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ "main" ]
|
||||
pull_request:
|
||||
# The branches below must be a subset of the branches above
|
||||
branches: [ "main" ]
|
||||
schedule:
|
||||
- cron: '33 7 * * 6'
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
php-security:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read # for actions/checkout to fetch code
|
||||
security-events: write # for github/codeql-action/upload-sarif to upload SARIF results
|
||||
actions: read # only required for a private repository by github/codeql-action/upload-sarif to get the Action run status
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v3
|
||||
|
||||
- name: Psalm Security Scan
|
||||
uses: psalm/psalm-github-security-scan@f3e6fd9432bc3e44aec078572677ce9d2ef9c287
|
||||
|
||||
- name: Upload Security Analysis results to GitHub
|
||||
uses: github/codeql-action/upload-sarif@v2
|
||||
with:
|
||||
sarif_file: results.sarif
|
||||
@@ -0,0 +1,128 @@
|
||||
# Contributor Covenant Code of Conduct
|
||||
|
||||
## Our Pledge
|
||||
|
||||
We as members, contributors, and leaders pledge to make participation in our
|
||||
community a harassment-free experience for everyone, regardless of age, body
|
||||
size, visible or invisible disability, ethnicity, sex characteristics, gender
|
||||
identity and expression, level of experience, education, socio-economic status,
|
||||
nationality, personal appearance, race, religion, or sexual identity
|
||||
and orientation.
|
||||
|
||||
We pledge to act and interact in ways that contribute to an open, welcoming,
|
||||
diverse, inclusive, and healthy community.
|
||||
|
||||
## Our Standards
|
||||
|
||||
Examples of behavior that contributes to a positive environment for our
|
||||
community include:
|
||||
|
||||
* Demonstrating empathy and kindness toward other people
|
||||
* Being respectful of differing opinions, viewpoints, and experiences
|
||||
* Giving and gracefully accepting constructive feedback
|
||||
* Accepting responsibility and apologizing to those affected by our mistakes,
|
||||
and learning from the experience
|
||||
* Focusing on what is best not just for us as individuals, but for the
|
||||
overall community
|
||||
|
||||
Examples of unacceptable behavior include:
|
||||
|
||||
* The use of sexualized language or imagery, and sexual attention or
|
||||
advances of any kind
|
||||
* Trolling, insulting or derogatory comments, and personal or political attacks
|
||||
* Public or private harassment
|
||||
* Publishing others' private information, such as a physical or email
|
||||
address, without their explicit permission
|
||||
* Other conduct which could reasonably be considered inappropriate in a
|
||||
professional setting
|
||||
|
||||
## Enforcement Responsibilities
|
||||
|
||||
Community leaders are responsible for clarifying and enforcing our standards of
|
||||
acceptable behavior and will take appropriate and fair corrective action in
|
||||
response to any behavior that they deem inappropriate, threatening, offensive,
|
||||
or harmful.
|
||||
|
||||
Community leaders have the right and responsibility to remove, edit, or reject
|
||||
comments, commits, code, wiki edits, issues, and other contributions that are
|
||||
not aligned to this Code of Conduct, and will communicate reasons for moderation
|
||||
decisions when appropriate.
|
||||
|
||||
## Scope
|
||||
|
||||
This Code of Conduct applies within all community spaces, and also applies when
|
||||
an individual is officially representing the community in public spaces.
|
||||
Examples of representing our community include using an official e-mail address,
|
||||
posting via an official social media account, or acting as an appointed
|
||||
representative at an online or offline event.
|
||||
|
||||
## Enforcement
|
||||
|
||||
Instances of abusive, harassing, or otherwise unacceptable behavior may be
|
||||
reported to the community leaders responsible for enforcement at
|
||||
e-mail rsgrinko@gmail.com.
|
||||
All complaints will be reviewed and investigated promptly and fairly.
|
||||
|
||||
All community leaders are obligated to respect the privacy and security of the
|
||||
reporter of any incident.
|
||||
|
||||
## Enforcement Guidelines
|
||||
|
||||
Community leaders will follow these Community Impact Guidelines in determining
|
||||
the consequences for any action they deem in violation of this Code of Conduct:
|
||||
|
||||
### 1. Correction
|
||||
|
||||
**Community Impact**: Use of inappropriate language or other behavior deemed
|
||||
unprofessional or unwelcome in the community.
|
||||
|
||||
**Consequence**: A private, written warning from community leaders, providing
|
||||
clarity around the nature of the violation and an explanation of why the
|
||||
behavior was inappropriate. A public apology may be requested.
|
||||
|
||||
### 2. Warning
|
||||
|
||||
**Community Impact**: A violation through a single incident or series
|
||||
of actions.
|
||||
|
||||
**Consequence**: A warning with consequences for continued behavior. No
|
||||
interaction with the people involved, including unsolicited interaction with
|
||||
those enforcing the Code of Conduct, for a specified period of time. This
|
||||
includes avoiding interactions in community spaces as well as external channels
|
||||
like social media. Violating these terms may lead to a temporary or
|
||||
permanent ban.
|
||||
|
||||
### 3. Temporary Ban
|
||||
|
||||
**Community Impact**: A serious violation of community standards, including
|
||||
sustained inappropriate behavior.
|
||||
|
||||
**Consequence**: A temporary ban from any sort of interaction or public
|
||||
communication with the community for a specified period of time. No public or
|
||||
private interaction with the people involved, including unsolicited interaction
|
||||
with those enforcing the Code of Conduct, is allowed during this period.
|
||||
Violating these terms may lead to a permanent ban.
|
||||
|
||||
### 4. Permanent Ban
|
||||
|
||||
**Community Impact**: Demonstrating a pattern of violation of community
|
||||
standards, including sustained inappropriate behavior, harassment of an
|
||||
individual, or aggression toward or disparagement of classes of individuals.
|
||||
|
||||
**Consequence**: A permanent ban from any sort of public interaction within
|
||||
the community.
|
||||
|
||||
## Attribution
|
||||
|
||||
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
|
||||
version 2.0, available at
|
||||
https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
|
||||
|
||||
Community Impact Guidelines were inspired by [Mozilla's code of conduct
|
||||
enforcement ladder](https://github.com/mozilla/diversity).
|
||||
|
||||
[homepage]: https://www.contributor-covenant.org
|
||||
|
||||
For answers to common questions about this code of conduct, see the FAQ at
|
||||
https://www.contributor-covenant.org/faq. Translations are available at
|
||||
https://www.contributor-covenant.org/translations.
|
||||
@@ -1,7 +1,8 @@
|
||||
# Delta Framework
|
||||
|
||||

|
||||

|
||||
## Описание
|
||||
Delta Framework - простой фреймворк для разработки веб проектов. Его разработка была начата в свободное от работы время и выполнялась полность в свое удовольствие.
|
||||
Delta Framework - простой фреймворк для разработки веб-проектов. Его разработка была начата в свободное от работы время и выполнялась полностью в свое удовольствие.
|
||||
На текущий момент в нем имеется:
|
||||
|
||||
- [X] Авторизация
|
||||
@@ -18,23 +19,82 @@ Delta Framework - простой фреймворк для разработки
|
||||
- [X] Логирование
|
||||
- [X] Работа с файлами
|
||||
- [X] Миграции
|
||||
- [X] Captcha
|
||||
- [X] DDoS Guard (basic)
|
||||
|
||||
***
|
||||
|
||||
## Скрины админки
|
||||
## Панель администратора
|
||||
Панель находистя по адресу `/admin/` и предоставляет базовые возможности по управлению системой.
|
||||
|
||||
### Дашбоард
|
||||

|
||||

|
||||
|
||||
### Менеджер очереди
|
||||

|
||||

|
||||
|
||||
### Командная строка
|
||||

|
||||

|
||||
|
||||
### Список пользователей
|
||||

|
||||
|
||||
## Пользовательская часть
|
||||
Пользовательская часть построена с использованием шаблонизатора 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]);
|
||||
}
|
||||
```
|
||||
|
||||
### Главная страница
|
||||

|
||||
|
||||
### Список пользователей
|
||||

|
||||
|
||||
### Страница информации
|
||||

|
||||
|
||||
|
||||
## Начало использования
|
||||
|
||||
Для начала получите проект любым удобным для вас способом (git clone, скачать...)
|
||||
@@ -66,6 +126,13 @@ Delta Framework - простой фреймворк для разработки
|
||||
vendor/bin/phinx migrate -e dev
|
||||
````
|
||||
|
||||
Для использования некой многосайтовости предусмотрено подключение локального файла конфигурации.
|
||||
|
||||
Пример: вы примонтировали в рядом лежащий проект папки `/core/`, `/upload/`, `/admin/`.
|
||||
Вам следует создать в корне проекта файл `config.local.php` и переопределить параметры для текущего проекта.
|
||||
|
||||
Файл локальной конфигурации является необязательным в случае если переопределение настроек не требуется, однако если его создать - можно точечно переопределить некоторые параметры (например, используемая БД и префикс таблиц).
|
||||
|
||||
Доступ к панели управления находится тут
|
||||
````https://site.ru/admin/````
|
||||
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
# Политика безопасности
|
||||
|
||||
Безопасность очень важна для данного проекта. Если вы обнаружите какие-либо проблемы, связанные с безопасностью - сообщите, отправив электронное письмо по адресу `rsgrinko@gmail.com`, указав в теме `Delta: Безопасность`.
|
||||
Мы быстро отреагируем и исправим найденые проблемы безопасности.
|
||||
|
||||
> Пожалуйста, не проводите исследования, которые могут повлиять на других пользователей. Также, пожалуйста, делайте отчеты краткими и емкими. Если нам не удастся понять логику вашей ошибки - мы вам сообщим.
|
||||
|
||||
Delta Framerork — это проект с открытым исходным кодом, имеющий лицензию MIT, который можно использовать бесплатно и в коммерческих целях. Мы приветствуем все исправления, направленные на повышение безопасности, по электронной почте на адрес `rsgrinko@gmail.com`.
|
||||
+13
-4
@@ -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
-1
@@ -21,6 +21,7 @@
|
||||
|
||||
use Core\Helpers\Pagination;
|
||||
use Core\ExternalServices\RemoteHosts;
|
||||
use Core\SystemConfig;
|
||||
|
||||
require_once __DIR__ . '/inc/header.php';
|
||||
|
||||
@@ -66,7 +67,7 @@
|
||||
</thead>
|
||||
<tbody>
|
||||
<?php
|
||||
Pagination::execute($_REQUEST['page'], RemoteHosts::getAllCount(), PAGINATION_LIMIT);
|
||||
Pagination::execute($_REQUEST['page'], RemoteHosts::getAllCount(), SystemConfig::getValue('PAGINATION_LIMIT'));
|
||||
$limit = Pagination::getLimit();
|
||||
|
||||
$arHosts = RemoteHosts::getHosts($limit);
|
||||
|
||||
@@ -42,7 +42,7 @@
|
||||
<meta name="description" content="">
|
||||
<meta name="author" content="">
|
||||
|
||||
<title>Delta - CPanel</title>
|
||||
<title>Delta - CPanel<?= isset($pageTitle) ? ' | ' . $pageTitle : '' ?></title>
|
||||
|
||||
<link href="//<?= $_SERVER['SERVER_NAME']; ?>/admin/styles/css/style.default.css" rel="stylesheet">
|
||||
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
|
||||
@@ -59,11 +59,14 @@
|
||||
width: 100%;
|
||||
height: 70px;
|
||||
}
|
||||
.telegramAuthButtonBox {
|
||||
margin-top: 20px;
|
||||
float: right;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
|
||||
<header>
|
||||
<div class="headerwrapper">
|
||||
<div class="header-left">
|
||||
|
||||
+4
-2
@@ -20,7 +20,9 @@
|
||||
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
|
||||
use Core\Helpers\Cache;use Core\Helpers\Files;use Core\Models\{User, Roles};
|
||||
use Core\Helpers\Cache;use Core\Helpers\Files;
|
||||
use Core\SystemConfig;
|
||||
use Core\Models\{User, Roles};
|
||||
|
||||
require_once __DIR__ . '/inc/header.php';
|
||||
?>
|
||||
@@ -96,7 +98,7 @@
|
||||
<h3 class="panel-title">Отладка</h3>
|
||||
</div>
|
||||
<div class="panel-body">
|
||||
<?= DEBUG ? 'Включена' : 'Отключена' ?>
|
||||
<?= SystemConfig::getValue('DEBUG') ? 'Включена' : 'Отключена' ?>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
+101
-32
@@ -19,36 +19,83 @@
|
||||
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
|
||||
use Core\Helpers\Captcha;
|
||||
use Core\Helpers\SystemFunctions;
|
||||
use Core\Models\User;
|
||||
use Core\SystemConfig;
|
||||
use Core\Models\{User, UserMeta};
|
||||
use Core\CoreException;
|
||||
|
||||
require_once __DIR__ . '/inc/bootstrap.php';
|
||||
|
||||
$captchaCorrect = true;
|
||||
if (USE_CAPTCHA) {
|
||||
$captchaCorrect = isset($_REQUEST['captchaCode']) && SystemFunctions::isValidCaptcha($_REQUEST['captchaCode']);
|
||||
// Определяем тип авторизации
|
||||
$authType = isset($_REQUEST['authType']) && !empty($_REQUEST['authType']) ? $_REQUEST['authType'] : 'default';
|
||||
|
||||
|
||||
/**
|
||||
* array(7) {
|
||||
["id"]=> string(7) "1831337"
|
||||
["first_name"]=> string(18) "Александр"
|
||||
["last_name"]=> string(16) "Менщиков"
|
||||
["username"]=> string(5) "n0str"
|
||||
["photo_url"]=> string(36) "https://t.me/i/userpic/100/n0str.jpg"
|
||||
["auth_date"]=> string(10) "1518168109"
|
||||
["hash"]=> string(64) "abba<..>1345"
|
||||
}
|
||||
*/
|
||||
switch ($authType) {
|
||||
case 'telegram':
|
||||
$data = [
|
||||
'id' => $_REQUEST['id'],
|
||||
'first_name' => $_REQUEST['first_name'],
|
||||
'last_name' => $_REQUEST['last_name'],
|
||||
'username' => $_REQUEST['username'],
|
||||
'photo_url' => $_REQUEST['photo_url'],
|
||||
'auth_date' => $_REQUEST['auth_date'],
|
||||
'hash' => $_REQUEST['hash'],
|
||||
];
|
||||
$isCorrectTelegramAuth = SystemFunctions::checkTelegramAuthorization($data);
|
||||
if ($isCorrectTelegramAuth) {
|
||||
$res = UserMeta::getListByParams(['name' => 'telegramId', 'value' => $data['id']]);
|
||||
if (!empty($res)) {
|
||||
$userId = array_shift($res)['user_id'];
|
||||
User::authorize($userId);
|
||||
header('Location: index.php');
|
||||
die();
|
||||
}
|
||||
}
|
||||
$auth = false;
|
||||
$err_mess = true;
|
||||
break;
|
||||
case 'default':
|
||||
$captchaCorrect = true;
|
||||
if (USE_CAPTCHA) {
|
||||
$captchaCorrect = isset($_REQUEST['captchaCode']) && Captcha::isValidCaptcha($_REQUEST['captchaCode']);
|
||||
}
|
||||
|
||||
if (User::isAuthorized()) {
|
||||
$auth = true;
|
||||
} else {
|
||||
$auth = false;
|
||||
if ($captchaCorrect && !empty($_REQUEST['login'] && !empty($_REQUEST['pass']))) {
|
||||
if (User::securityAuthorize(
|
||||
$_REQUEST['login'],
|
||||
$_REQUEST['pass'],
|
||||
isset($_REQUEST['remember']) && $_REQUEST['remember'] === 'on'
|
||||
)) {
|
||||
$auth = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if ($auth === false && isset($_REQUEST['login']) && $_REQUEST['login'] !== '') {
|
||||
$err_mess = true;
|
||||
} else {
|
||||
$err_mess = false;
|
||||
}
|
||||
break;
|
||||
|
||||
}
|
||||
|
||||
if (User::isAuthorized()) {
|
||||
$auth = true;
|
||||
} else {
|
||||
$auth = false;
|
||||
if ($captchaCorrect && !empty($_REQUEST['login'] && !empty($_REQUEST['pass']))) {
|
||||
if (User::securityAuthorize(
|
||||
$_REQUEST['login'],
|
||||
$_REQUEST['pass'],
|
||||
isset($_REQUEST['remember']) && $_REQUEST['remember'] === 'on'
|
||||
)) {
|
||||
$auth = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if ($auth === false && isset($_REQUEST['login']) && $_REQUEST['login'] !== '') {
|
||||
$err_mess = true;
|
||||
} else {
|
||||
$err_mess = false;
|
||||
}
|
||||
|
||||
|
||||
if ($auth === true) {
|
||||
global $USER;
|
||||
@@ -56,6 +103,7 @@
|
||||
try {
|
||||
User::logout();
|
||||
User::authorize($_REQUEST['loginAs']);
|
||||
die();
|
||||
} catch (CoreException $e) {
|
||||
die('Авторизация не удалась');
|
||||
}
|
||||
@@ -70,23 +118,23 @@
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">
|
||||
<meta name="description" content="">
|
||||
<meta name="author" content="">
|
||||
|
||||
<title>Delta Framework - Авторизация</title>
|
||||
|
||||
<link href="//<?php echo $_SERVER['SERVER_NAME']; ?>/admin/styles/css/style.default.css" rel="stylesheet">
|
||||
|
||||
<!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
|
||||
<!--[if lt IE 9]>
|
||||
<script src="//<?= $_SERVER['SERVER_NAME']; ?>/admin/styles/js/html5shiv.js"></script>
|
||||
<script src="//<?= $_SERVER['SERVER_NAME']; ?>/admin/styles/js/respond.min.js"></script>
|
||||
<![endif]-->
|
||||
<style>
|
||||
.telegramAuthButtonBox {
|
||||
margin-top: 20px;
|
||||
float: right;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
|
||||
<body class="signin">
|
||||
|
||||
|
||||
<section>
|
||||
|
||||
<div class="panel panel-signin">
|
||||
<div class="panel-body">
|
||||
<div class="logo text-center">
|
||||
@@ -105,6 +153,7 @@
|
||||
<?php } ?>
|
||||
|
||||
<form action="login.php" method="post">
|
||||
<input type="hidden" name="authType" value="default">
|
||||
<div class="input-group mb15">
|
||||
<span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
|
||||
<input type="text" class="form-control" name="login" placeholder="Имя пользователя">
|
||||
@@ -142,6 +191,24 @@
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<h4 class="text-center mb5">Вход через сторонний сервис</h4>
|
||||
<p class="text-center">Вы можете использовать для авторизации один из вариантов ниже</p>
|
||||
|
||||
<div class="telegramAuthButtonBox">
|
||||
<script async src="https://telegram.org/js/telegram-widget.js?22" data-telegram-login="<?= SystemConfig::getValue('TELEGRAM_BOT_USERNAME') ?>" data-size="large" data-onauth="onTelegramAuth(user)" data-request-access="write"></script>
|
||||
<script type="text/javascript">
|
||||
function onTelegramAuth(user) {
|
||||
document.location.href = 'login.php?authType=telegram&hash='+ user.hash
|
||||
+ '&id=' + user.id
|
||||
+ '&auth_date=' + user.auth_date
|
||||
+ '&first_name=' + user.first_name
|
||||
+ '&last_name=' + user.last_name
|
||||
+ '&photo_url=' + user.photo_url
|
||||
+ '&username=' + user.username
|
||||
}
|
||||
</script>
|
||||
</div>
|
||||
|
||||
</div><!-- panel-body -->
|
||||
<div class="panel-footer">
|
||||
<a href="register.php" class="btn btn-primary btn-block">Регистрация в системе</a>
|
||||
@@ -162,9 +229,11 @@
|
||||
<?php if (USE_CAPTCHA) { ?>
|
||||
<script>
|
||||
$(document).ready(function () {
|
||||
var captchaSrc = $("#captchaCode").attr('src');
|
||||
$('#updateCaptcha').click(function () {
|
||||
$("#captchaCode").attr('src', captchaSrc + `?v=${new Date().getTime()}`);
|
||||
let $captchaImage = $('#captchaCode'),
|
||||
$captchaSrc = $captchaImage.attr('src'),
|
||||
$updateBtn = $('#updateCaptcha');
|
||||
$updateBtn.click(function () {
|
||||
$captchaImage.attr('src', $captchaSrc + `?v=${new Date().getTime()}`);
|
||||
});
|
||||
});
|
||||
</script>
|
||||
|
||||
+2
-1
@@ -21,6 +21,7 @@
|
||||
|
||||
use Core\Helpers\Pagination;
|
||||
use Core\Helpers\SystemFunctions;
|
||||
use Core\SystemConfig;
|
||||
|
||||
require_once __DIR__ . '/inc/header.php';
|
||||
|
||||
@@ -66,7 +67,7 @@
|
||||
<?php
|
||||
$nginxLogFile = $_SERVER['DOCUMENT_ROOT'].'/../../log/it-stories.ru_access';
|
||||
//$nginxLogFile = $_SERVER['DOCUMENT_ROOT'].'/../../log/test.log';
|
||||
Pagination::execute($_REQUEST['page'], SystemFunctions::getNginxLogData($nginxLogFile, true), PAGINATION_LIMIT);
|
||||
Pagination::execute($_REQUEST['page'], SystemFunctions::getNginxLogData($nginxLogFile, true), SystemConfig::getValue('PAGINATION_LIMIT'));
|
||||
$limit = Pagination::getLimit();
|
||||
|
||||
$arLogs = SystemFunctions::getNginxLogData($nginxLogFile, false, $limit, true);
|
||||
|
||||
+2
-1
@@ -23,6 +23,7 @@
|
||||
use Core\Models\File;
|
||||
use Core\Models\Posts;
|
||||
use Core\Models\User;
|
||||
use Core\SystemConfig;
|
||||
|
||||
require_once __DIR__ . '/inc/header.php';
|
||||
?>
|
||||
@@ -61,7 +62,7 @@
|
||||
<tbody>
|
||||
<?php
|
||||
$objectPosts = new Posts();
|
||||
Pagination::execute($_REQUEST['page'], $objectPosts->getAllCount(), PAGINATION_LIMIT);
|
||||
Pagination::execute($_REQUEST['page'], $objectPosts->getAllCount(), SystemConfig::getValue('PAGINATION_LIMIT'));
|
||||
$limit = Pagination::getLimit();
|
||||
|
||||
$arPosts = $objectPosts->getPosts($limit);
|
||||
|
||||
+15
-1
@@ -19,7 +19,7 @@
|
||||
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
|
||||
use Core\Models\{User, MQ};
|
||||
use Core\Models\{User, UserMeta};
|
||||
|
||||
require_once __DIR__ . '/inc/header.php';
|
||||
|
||||
@@ -134,6 +134,20 @@
|
||||
</div>
|
||||
</div><!-- form-group -->
|
||||
|
||||
<?php
|
||||
$telegramMetaParam = UserMeta::getListByParams(['user_id' => $objectUser->getId(), 'name' => 'telegramId']);
|
||||
if (!empty($telegramMetaParam)) {
|
||||
$telegramId = array_shift($telegramMetaParam)['value'];
|
||||
?>
|
||||
<div class="form-group">
|
||||
<label class="col-sm-4 control-label">Telegram ID</label>
|
||||
<div class="col-sm-8">
|
||||
<input type="text" name="token" value="<?= $telegramId; ?>" class="form-control" disabled>
|
||||
</div>
|
||||
</div><!-- form-group -->
|
||||
<?php } ?>
|
||||
|
||||
|
||||
<div class="panel-footer">
|
||||
<input type="submit" name="save" value="Сохранить" class="btn btn-primary">
|
||||
</div>
|
||||
|
||||
+2
-2
@@ -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
@@ -726,7 +726,7 @@ h4, .h4 {
|
||||
-moz-border-radius: 3px;
|
||||
-webkit-border-radius: 3px;
|
||||
border-radius: 3px;
|
||||
height: 15px;
|
||||
/*height: 15px;*/
|
||||
margin-bottom: 15px;
|
||||
}
|
||||
|
||||
|
||||
+2
-1
@@ -21,6 +21,7 @@
|
||||
|
||||
use Core\Helpers\Pagination;
|
||||
use Core\Models\User;
|
||||
use Core\SystemConfig;
|
||||
|
||||
require_once __DIR__ . '/inc/header.php';
|
||||
|
||||
@@ -69,7 +70,7 @@
|
||||
</thead>
|
||||
<tbody>
|
||||
<?php
|
||||
Pagination::execute($_REQUEST['page'], User::getAllCount(), PAGINATION_LIMIT);
|
||||
Pagination::execute($_REQUEST['page'], User::getAllCount(), SystemConfig::getValue('PAGINATION_LIMIT'));
|
||||
$limit = Pagination::getLimit();
|
||||
|
||||
$arUsers = User::getUsers($limit);
|
||||
|
||||
@@ -156,6 +156,10 @@ body {
|
||||
padding: 10px;
|
||||
}
|
||||
|
||||
.main .input.captchaInput {
|
||||
width: 98%;
|
||||
}
|
||||
|
||||
.main .w100 {
|
||||
width: 100%;
|
||||
}
|
||||
@@ -329,4 +333,4 @@ a.fileLink:before {
|
||||
/* Disabled */
|
||||
.input-file input[type=file]:disabled + span {
|
||||
background-color: #eee;
|
||||
}
|
||||
}
|
||||
+30
-18
@@ -19,13 +19,14 @@
|
||||
* 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;
|
||||
use Core\SystemConfig;
|
||||
|
||||
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();
|
||||
@@ -159,10 +171,10 @@
|
||||
// debug
|
||||
function sendTelegram(?string $message, ?string $file = null): void
|
||||
{
|
||||
(new \Core\ExternalServices\TelegramSender(TELEGRAM_BOT_TOKEN))->setChat(TELEGRAM_NOTIFICATION_CHANNEL)->sendMessage($message);
|
||||
(new \Core\ExternalServices\TelegramSender(SystemConfig::getValue('TELEGRAM_BOT_TOKEN')))->setChat(SystemConfig::getValue('TELEGRAM_NOTIFICATION_CHANNEL'))->sendMessage($message);
|
||||
|
||||
if (!empty($file)) {
|
||||
(new \Core\ExternalServices\TelegramSender(TELEGRAM_BOT_TOKEN))->setChat(TELEGRAM_NOTIFICATION_CHANNEL)->sendDocument($file);
|
||||
(new \Core\ExternalServices\TelegramSender(SystemConfig::getValue('TELEGRAM_BOT_TOKEN')))->setChat(SystemConfig::getValue('TELEGRAM_NOTIFICATION_CHANNEL'))->sendDocument($file);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+2
-2
@@ -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();
|
||||
+15
-3
@@ -22,13 +22,13 @@
|
||||
/**
|
||||
* Версия сервиса
|
||||
*/
|
||||
const CORE_VERSION = '1.0.0_dev';
|
||||
const CORE_VERSION = '1.0.2';
|
||||
|
||||
/**
|
||||
* Флаг отладки
|
||||
*/
|
||||
if (!defined('DEBUG')) {
|
||||
define('DEBUG', true);
|
||||
define('DEBUG', true); //SystemConfig
|
||||
}
|
||||
|
||||
|
||||
@@ -124,6 +124,13 @@
|
||||
define('PATH_TO_TEMPLATES', ROOT_PATH . '/templates');
|
||||
}
|
||||
|
||||
/**
|
||||
* Имя телеграм бота
|
||||
*/
|
||||
if (!defined('TELEGRAM_BOT_USERNAME')) {
|
||||
define('TELEGRAM_BOT_USERNAME', 'deltacore_bot');
|
||||
}
|
||||
|
||||
/**
|
||||
* Токен телеграм бота
|
||||
*/
|
||||
@@ -213,7 +220,7 @@
|
||||
* Флаг использования Captcha
|
||||
*/
|
||||
if (!defined('USE_CAPTCHA')) {
|
||||
define('USE_CAPTCHA', true);
|
||||
define('USE_CAPTCHA', false);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -222,3 +229,8 @@
|
||||
if (!defined('USE_DDOS_PROTECTION')) {
|
||||
define('USE_DDOS_PROTECTION', false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Формат даты/времени
|
||||
*/
|
||||
const DATETIME_FORMAT = 'Y-m-d H:i:s';
|
||||
+11
-36
@@ -23,45 +23,20 @@
|
||||
set_time_limit(0);
|
||||
|
||||
use Core\Helpers\Log;
|
||||
use Core\Models\MQ;
|
||||
|
||||
if (empty($_SERVER['DOCUMENT_ROOT'])) {
|
||||
$_SERVER['DOCUMENT_ROOT'] = __DIR__ . '/..';
|
||||
}
|
||||
require_once __DIR__ . '/bootstrap.php';
|
||||
|
||||
// Запускаем воркер диспетчера очереди
|
||||
exec('(php -f ' . $_SERVER['DOCUMENT_ROOT'] . '/core/runtime/threadsWorker.php & ) >> /dev/null 2>&1');
|
||||
|
||||
//$result = (new MQ())->setAttempts(3)->setPriority(1)->setCheckDuplicates(true)->createTask('Core\MQTasks', 'getMySLO');
|
||||
|
||||
// Попытка получения валюты сайта за ежедневные авторизации
|
||||
$cookieFile = $_SERVER['DOCUMENT_ROOT'] . '/uploads/visaviCookie.txt';
|
||||
$logFileName = 'visavi.log';
|
||||
|
||||
if (!file_exists($cookieFile) || time() - @filectime($cookieFile) > 60 * 60 * 23) {
|
||||
Log::logToFile('Время пришло - начинаем попытку авторизации', $logFileName);
|
||||
@unlink($cookieFile);
|
||||
Log::logToFile('Файл куков удален', $logFileName);
|
||||
|
||||
$array = [
|
||||
'login' => 'Nominal',
|
||||
'password' => 'j2medit',
|
||||
];
|
||||
$ch = curl_init('https://visavi.net/login');
|
||||
curl_setopt($ch, CURLOPT_POST, 1);
|
||||
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($array, '', '&'));
|
||||
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
|
||||
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
|
||||
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookieFile);
|
||||
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookieFile);
|
||||
curl_setopt($ch, CURLOPT_HEADER, false);
|
||||
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
|
||||
$html = curl_exec($ch);
|
||||
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
||||
curl_close($ch);
|
||||
|
||||
unset($html);
|
||||
|
||||
Log::logToFile('Запрос на авторизацию произведен. Код ответа: ' . $httpCode, $logFileName);
|
||||
}
|
||||
$tasksDir = __DIR__ . '/cronTasks/';
|
||||
$list = scandir($tasksDir);
|
||||
$logFileName = 'cron.log';
|
||||
foreach ($list as $file) {
|
||||
if (in_array($file, ['.', '..', 'init.php'], true)) {
|
||||
continue;
|
||||
}
|
||||
$command = '(php -f ' . $tasksDir . $file . ' & ) >> /dev/null 2>&1';
|
||||
Log::logToFile($command, $logFileName);
|
||||
exec($command);
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Copyright (c) 2022 Roman Grinko <rsgrinko@gmail.com>
|
||||
* Permission is hereby granted, free of charge, to any person obtaining
|
||||
@@ -19,28 +20,10 @@
|
||||
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
|
||||
namespace Core;
|
||||
@ignore_user_abort(true);
|
||||
set_time_limit(0);
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
if (empty($_SERVER['DOCUMENT_ROOT'])) {
|
||||
$_SERVER['DOCUMENT_ROOT'] = __DIR__ . '/../..';
|
||||
}
|
||||
require_once __DIR__ . '/../bootstrap.php';
|
||||
@@ -0,0 +1,32 @@
|
||||
<?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.
|
||||
*/
|
||||
require_once 'init.php';
|
||||
|
||||
use Core\Models\MQ;
|
||||
|
||||
(new MQ())->setCheckDuplicates(false)->setPriority(9)
|
||||
->setAttempts(2)
|
||||
->createTask(
|
||||
'Core\MQTasks',
|
||||
'getStory',
|
||||
[]
|
||||
);
|
||||
@@ -0,0 +1,25 @@
|
||||
<?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.
|
||||
*/
|
||||
|
||||
require_once 'init.php';
|
||||
|
||||
exec('(php -f ' . $_SERVER['DOCUMENT_ROOT'] . '/core/runtime/threadsWorker.php & ) >> /dev/null 2>&1');
|
||||
@@ -25,6 +25,7 @@
|
||||
use Core\Models\File;
|
||||
use Core\Models\MQ;
|
||||
use Core\Models\User;
|
||||
use Core\SystemConfig;
|
||||
|
||||
/**
|
||||
* Класс API контроллера
|
||||
@@ -69,7 +70,7 @@
|
||||
if ($to !== null) {
|
||||
$this->to = (int)$to;
|
||||
} else {
|
||||
$this->to = PAGINATION_LIMIT;
|
||||
$this->to = SystemConfig::getValue('PAGINATION_LIMIT');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -289,7 +290,7 @@
|
||||
null,
|
||||
$this->request->getProperty('subject'),
|
||||
$this->request->getProperty('body'),
|
||||
MAIL_TEMPLATE_DEFAULT,
|
||||
SystemConfig::getValue('MAIL_TEMPLATE_DEFAULT'),
|
||||
['TITLE' => $this->request->getProperty('subject')],
|
||||
]
|
||||
);
|
||||
|
||||
@@ -21,6 +21,7 @@
|
||||
|
||||
namespace Core;
|
||||
|
||||
use Core\Helpers\Captcha;
|
||||
use Core\Helpers\Pagination;
|
||||
use Core\Helpers\Registry;
|
||||
use Core\Helpers\SystemFunctions;
|
||||
@@ -49,6 +50,8 @@
|
||||
$memoryUse = memory_get_usage() - START_MEMORY;
|
||||
|
||||
return [
|
||||
'SITE_URL' => SITE_URL,
|
||||
'USE_CAPTCHA' => USE_CAPTCHA,
|
||||
'salt' => md5(random_int(1, 999999) . random_int(1, 999999) . random_int(1, 999999) . random_int(1, 999999)),
|
||||
'currentPage' => $currentPage,
|
||||
'memoryUse' => SystemFunctions::convertBytes($memoryUse),
|
||||
@@ -86,7 +89,7 @@
|
||||
{
|
||||
$buildInfo = [
|
||||
'Версия ядра' => CORE_VERSION,
|
||||
'Лимит пагинации' => PAGINATION_LIMIT,
|
||||
'Лимит пагинации' => SystemConfig::getValue('PAGINATION_LIMIT'),
|
||||
'Время для расчета онлайна' => USER_ONLINE_TIME,
|
||||
'Время жизни кеша' => CACHE_TTL,
|
||||
'E-Mail сайта' => SERVER_EMAIL,
|
||||
@@ -136,7 +139,7 @@
|
||||
|
||||
public static function users()
|
||||
{
|
||||
Pagination::execute($_REQUEST['page'], User::getAllCount(), PAGINATION_LIMIT);
|
||||
Pagination::execute($_REQUEST['page'], User::getAllCount(), SystemConfig::getValue('PAGINATION_LIMIT'));
|
||||
$limit = Pagination::getLimit();
|
||||
$limit= '0, 10';
|
||||
$arUsers = User::getUsers($limit);
|
||||
@@ -149,20 +152,41 @@
|
||||
|
||||
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();
|
||||
User::logout();
|
||||
header('Location: /');
|
||||
}
|
||||
|
||||
public static function loginAuthorize()
|
||||
{
|
||||
if (User::securityAuthorize($_REQUEST['login'], $_REQUEST['password'], false)) {
|
||||
header('Location: /');
|
||||
$captchaCorrect = true;
|
||||
if (USE_CAPTCHA) {
|
||||
if (empty($_REQUEST['captchaCode'])) {
|
||||
$_SESSION['authErrorMessage'] = 'Не введен код с картинки';
|
||||
$captchaCorrect = false;
|
||||
} else {
|
||||
$captchaCorrect = Captcha::isValidCaptcha($_REQUEST['captchaCode']);
|
||||
if ($captchaCorrect === false) {
|
||||
$_SESSION['authErrorMessage'] = 'Неверный код с картинки';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ($captchaCorrect) {
|
||||
if (User::securityAuthorize($_REQUEST['login'], $_REQUEST['password'], false)) {
|
||||
unset($_SESSION['authErrorMessage']);
|
||||
header('Location: /');
|
||||
} else {
|
||||
$_SESSION['authErrorMessage'] = 'Неверный логин или пароль';
|
||||
header('Location: /login/failed');
|
||||
}
|
||||
} else {
|
||||
header('Location: /login/failed');
|
||||
}
|
||||
@@ -175,7 +199,7 @@
|
||||
|
||||
public static function loginFailed()
|
||||
{
|
||||
self::render('login.twig', ['failed' => true]);
|
||||
self::render('login.twig', ['failed' => true, 'errorMessage' => $_SESSION['authErrorMessage']]);
|
||||
}
|
||||
|
||||
public static function userProfile(int $id)
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -22,6 +22,8 @@
|
||||
namespace Core\DataBases;
|
||||
|
||||
use Core\CoreException;
|
||||
use Core\Helpers\SystemFunctions;
|
||||
use Core\SystemConfig;
|
||||
use PDO;
|
||||
use Throwable;
|
||||
|
||||
@@ -112,22 +114,6 @@
|
||||
// TODO: на случай чего то стоящего...
|
||||
}
|
||||
|
||||
/**
|
||||
* Отправка уведомления о критическом событии
|
||||
* // TODO: метод-заглушка для возможности оповещения о критических событиях
|
||||
*
|
||||
* @param string $text Текст
|
||||
*
|
||||
* @return void
|
||||
* @deprecated Вероятно, будет выпилено в дальнейшем
|
||||
*/
|
||||
public static function sendAlarm(string $text): void
|
||||
{
|
||||
if (function_exists('sendTelegram')) {
|
||||
sendTelegram($text);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Получить объект класса
|
||||
*
|
||||
@@ -231,8 +217,14 @@
|
||||
return $set;
|
||||
}
|
||||
$set_string = '';
|
||||
foreach ($set as $set_key => $set_item) {
|
||||
$set_string .= ' ' . $set_key . '=\'' . $set_item . '\',';
|
||||
foreach ($set as $setKey => $setValue) {
|
||||
$set_string .= ' ' . $setKey . '=';
|
||||
if (is_null($setValue)) {
|
||||
$set_string .= ' ' . $setKey . '=null,';
|
||||
} else {
|
||||
$set_string .= '\'' . $setValue . '\',';
|
||||
}
|
||||
|
||||
}
|
||||
return substr($set_string, 0, -1);
|
||||
}
|
||||
@@ -301,11 +293,14 @@
|
||||
try {
|
||||
$stmt = $this->db->query($sql);
|
||||
} catch (\Throwable $t) {
|
||||
self::sendAlarm(
|
||||
'<b><u>' . date('d.m.Y H:i:s') . '</u></b>' . PHP_EOL . '</b><b>SQL ERROR:</b> ' . PHP_EOL . $this->db->errorInfo()[2] . PHP_EOL
|
||||
. '<b>QUERY:</b> ' . PHP_EOL . $sql
|
||||
SystemFunctions::sendAlarm('DataBase',
|
||||
'<b><u>' . date('d.m.Y H:i:s') . '</u></b>' . PHP_EOL
|
||||
. '</b><b>SQL ERROR:</b> ' . PHP_EOL
|
||||
. $this->db->errorInfo()[2] . PHP_EOL
|
||||
. '<b>QUERY:</b> ' . PHP_EOL
|
||||
. $sql
|
||||
);
|
||||
if(DEBUG) {
|
||||
if(SystemConfig::getValue('DEBUG')) {
|
||||
throw new CoreException(
|
||||
'В SQL запросе произошла ошибка: ' . $this->db->errorInfo()[2]
|
||||
. '. Запрос: ' . $sql, CoreException::ERROR_SQL_QUERY);
|
||||
|
||||
@@ -146,6 +146,7 @@
|
||||
* @param string $table Таблица
|
||||
*
|
||||
* @return array|null Имена колонок
|
||||
* @throws Throwable
|
||||
*/
|
||||
private static function getColumnsInfo(string $table): array
|
||||
{
|
||||
@@ -166,16 +167,16 @@
|
||||
private function setData(array $data): void
|
||||
{
|
||||
$this->sourceData = $data;
|
||||
$columnsInfo = self::getColumnsInfo(static::TABLE);
|
||||
foreach ($data as $prop => $value) {
|
||||
$key = $prop;
|
||||
if (empty($this->renameProps[$prop]) === false) {
|
||||
if (!empty($this->renameProps[$prop])) {
|
||||
$key = $this->renameProps[$prop];
|
||||
}
|
||||
if (property_exists($this, $key)) {
|
||||
$this->$key = $value;
|
||||
}
|
||||
$columnsInfo = self::getColumnsInfo(static::TABLE);
|
||||
if (empty($columnsInfo[$key]) === false) {
|
||||
if (!empty($columnsInfo[$key])) {
|
||||
switch ($columnsInfo[$key]['type']) {
|
||||
case self::COLUMN_TYPE_BOOL:
|
||||
$this->$key = (bool)$this->$key;
|
||||
@@ -188,23 +189,27 @@
|
||||
/**
|
||||
* Сохранить элемент
|
||||
*
|
||||
* @return $this
|
||||
* @throws CoreException
|
||||
* @return self
|
||||
* @throws DataObjectsException
|
||||
*/
|
||||
public function save(): self
|
||||
{
|
||||
/** @var DB $db */
|
||||
$db = DB::getInstance();
|
||||
$id = static::ID_NAME;
|
||||
if (empty($this->$id) === false) {
|
||||
$diff = $this->getDataDifference();
|
||||
if (empty($diff) === false) {
|
||||
$db->update(static::TABLE, [$id => $this->$id], $this->sanitizeFields($diff));
|
||||
try {
|
||||
if (!empty($this->$id)) {
|
||||
$diff = $this->getDataDifference();
|
||||
if (!empty($diff)) {
|
||||
$db->update(static::TABLE, [$id => $this->$id], $this->sanitizeFields($diff));
|
||||
}
|
||||
} else {
|
||||
$this->$id = $db->addItem(static::TABLE, $this->sanitizeFields($this->getDataDifference(true)));
|
||||
}
|
||||
} else {
|
||||
$this->$id = $db->addItem(static::TABLE, $this->sanitizeFields($this->getDataDifference(true)));
|
||||
$this->setData($db->getItem(static::TABLE, [$id => $this->$id]));
|
||||
} catch (Throwable $e) {
|
||||
throw new DataObjectsException('Произошла ошибка при сохранении данных: ' . $e->getMessage());
|
||||
}
|
||||
$this->setData($db->getItem(static::TABLE, [$id => $this->$id]));
|
||||
return $this;
|
||||
}
|
||||
|
||||
@@ -270,7 +275,7 @@
|
||||
$renameList = array_flip($this->renameProps);
|
||||
}
|
||||
$columnList = self::getColumnsInfo(static::TABLE);
|
||||
foreach (self::getColumnsInfo(static::TABLE) as $prop => $info) {
|
||||
foreach ($columnList as $prop => $info) {
|
||||
if (!$includeWriteProtected && in_array($prop, static::WRITE_PROTECTION, true)) {
|
||||
continue;
|
||||
}
|
||||
@@ -315,7 +320,7 @@
|
||||
public static function select(array $filter): ModelCollection
|
||||
{
|
||||
/** @var DB $db */
|
||||
$db = DB::getInstance();
|
||||
$db = DB::getInstance();
|
||||
$result = $db->getItems(static::TABLE, $filter);
|
||||
$collectionClass = static::COLLECTION;
|
||||
$collection = new $collectionClass();
|
||||
@@ -362,7 +367,7 @@
|
||||
* @param array $array Входные данные
|
||||
*
|
||||
* @return array Результат
|
||||
* @throws CoreException
|
||||
* @throws DataObjectsException
|
||||
*/
|
||||
private function sanitizeFields(array $array): array
|
||||
{
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
}
|
||||
+1
-1
@@ -23,7 +23,7 @@
|
||||
|
||||
use Core\CoreException;
|
||||
|
||||
class Request
|
||||
class RequestOLD
|
||||
{
|
||||
private $httpStatus = null;
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
<?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;
|
||||
|
||||
use mysql_xdevapi\Result;
|
||||
|
||||
/**
|
||||
* Класс для работы с 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['captcha'] = [
|
||||
'captchaCode' => $code,
|
||||
'verified' => false,
|
||||
'generatedTime' => time(),
|
||||
'generatedDate' => date(DATETIME_FORMAT),
|
||||
];
|
||||
|
||||
$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
|
||||
{
|
||||
$result = (string)$_SESSION['captcha']['captchaCode'] === $code;
|
||||
$_SESSION['captcha']['verified'] = $result;
|
||||
$_SESSION['captcha']['verifiedTime'] = time();
|
||||
$_SESSION['captcha']['verifiedDate'] = date(DATETIME_FORMAT);
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Очистка данных каптчи
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public static function clearSession(): void
|
||||
{
|
||||
unset($_SESSION['captcha']);
|
||||
}
|
||||
}
|
||||
@@ -24,6 +24,7 @@
|
||||
use Core\CoreException;
|
||||
use Core\DataBases\DB;
|
||||
use Core\Models\User;
|
||||
use Core\SystemConfig;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
@@ -86,7 +87,7 @@
|
||||
$this->user = $user;
|
||||
$this->setFrom(SERVER_EMAIL, SERVER_EMAIL_NAME)
|
||||
->setTo($user->getEmail(), $user->getName())
|
||||
->setTemplate(MAIL_TEMPLATE_DEFAULT);
|
||||
->setTemplate(SystemConfig::getValue('MAIL_TEMPLATE_DEFAULT'));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -95,14 +96,15 @@
|
||||
*
|
||||
* @param string $templateName Имя шаблона
|
||||
*
|
||||
* @return $this
|
||||
* @return self
|
||||
*/
|
||||
public function setTemplate(string $templateName): self
|
||||
{
|
||||
if(!file_exists(MAIL_TEMPLATES_PATH . '/' . $templateName . '.html')) {
|
||||
throw new CoreException('Шаблон "' . $templateName . '" не найден');
|
||||
}
|
||||
$this->templateName = $templateName;
|
||||
if (!file_exists(MAIL_TEMPLATES_PATH . '/' . $templateName . '.html')) {
|
||||
$this->templateName = 'default';
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
@@ -111,7 +113,7 @@
|
||||
*
|
||||
* @param array $templateVars Массив переменных шаблона
|
||||
*
|
||||
* @return $this
|
||||
* @return self
|
||||
*/
|
||||
public function setTemplateVars(array $templateVars): self
|
||||
{
|
||||
@@ -136,7 +138,7 @@
|
||||
/**
|
||||
* От кого
|
||||
*
|
||||
* @return $this
|
||||
* @return self
|
||||
*/
|
||||
public function setFrom($email, $name = null): self
|
||||
{
|
||||
@@ -148,7 +150,7 @@
|
||||
/**
|
||||
* Кому
|
||||
*
|
||||
* @return $this
|
||||
* @return self
|
||||
*/
|
||||
public function setTo($email, $name = null): self
|
||||
{
|
||||
@@ -160,7 +162,7 @@
|
||||
/**
|
||||
* Тема
|
||||
*
|
||||
* @return $this
|
||||
* @return self
|
||||
*/
|
||||
public function setSubject($subject = null): self
|
||||
{
|
||||
@@ -171,7 +173,7 @@
|
||||
/**
|
||||
* Тело письма
|
||||
*
|
||||
* @return $this
|
||||
* @return self
|
||||
*/
|
||||
public function setBody($body = null): self
|
||||
{
|
||||
@@ -182,7 +184,7 @@
|
||||
/**
|
||||
* Добавление файла к письму
|
||||
*
|
||||
* @return $this
|
||||
* @return self
|
||||
*/
|
||||
public function addFile($filename): self
|
||||
{
|
||||
|
||||
@@ -23,6 +23,10 @@
|
||||
|
||||
|
||||
use Core\CoreException;
|
||||
use Core\DTO\System\Memory;
|
||||
use Core\Models\Roles;
|
||||
use Core\Models\User;
|
||||
use Core\SystemConfig;
|
||||
|
||||
/**
|
||||
* Класс вспомогательных методов
|
||||
@@ -153,102 +157,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 +302,7 @@
|
||||
|
||||
/**
|
||||
* Метод для склонения слов в зависимости от числа
|
||||
* Пример: numWord($secs, array('секунда', 'секунды', 'секунд'))
|
||||
* Пример: numWord($secs, ['секунда', 'секунды', 'секунд'])
|
||||
*
|
||||
* @param int $value Число
|
||||
* @param array $words Массив слов
|
||||
@@ -550,7 +483,9 @@
|
||||
*/
|
||||
public static function sendTelegram(string $message): void
|
||||
{
|
||||
(new \Core\ExternalServices\TelegramSender(TELEGRAM_BOT_TOKEN))->setChat(TELEGRAM_NOTIFICATION_CHANNEL)->sendMessage($message);
|
||||
(new \Core\ExternalServices\TelegramSender(SystemConfig::getValue('TELEGRAM_BOT_TOKEN')))
|
||||
->setChat(SystemConfig::getValue('TELEGRAM_NOTIFICATION_CHANNEL'))
|
||||
->sendMessage($message);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -558,6 +493,7 @@
|
||||
*
|
||||
* @param array|string|null $var Массив
|
||||
* @param string $title Заголовок
|
||||
*
|
||||
*
|
||||
* @return string|null
|
||||
*/
|
||||
@@ -658,6 +594,7 @@
|
||||
* @param array $arData Массив данных
|
||||
*
|
||||
* @return void
|
||||
* @throws \Exception
|
||||
*/
|
||||
public static function arrayToXml(array $arData = [], ?string $objectName = null): string
|
||||
{
|
||||
@@ -678,16 +615,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 +685,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 +760,8 @@
|
||||
}
|
||||
|
||||
/**
|
||||
* Возвращает кусок текстового содерживого с подсвеченной строкой
|
||||
* Возвращает кусок текстового содержимого с подсвеченной строкой
|
||||
*
|
||||
* @param string $fileText Текст
|
||||
* @param int $lineNum Номер строки
|
||||
*
|
||||
@@ -921,6 +802,7 @@
|
||||
|
||||
$textBefore = '<div style="border:1px solid black">';
|
||||
$textAfter = '</div>';
|
||||
|
||||
return $textBefore . implode(PHP_EOL . PHP_EOL, $result) . $textAfter;
|
||||
}
|
||||
|
||||
@@ -968,6 +850,9 @@
|
||||
|
||||
/**
|
||||
* Генерация кода для каптчи
|
||||
*
|
||||
* TODO: реализовать схожий с генерацией пароля механизм
|
||||
*
|
||||
* @param int $min Минимальное количество символов
|
||||
* @param int $max Максимальное количество символов
|
||||
*
|
||||
@@ -992,83 +877,107 @@
|
||||
}
|
||||
|
||||
/**
|
||||
* Генерация и отображение картинки-каптчи
|
||||
* Получение информации о памяти сервера
|
||||
*
|
||||
* @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);
|
||||
return $memoryObject;
|
||||
}
|
||||
|
||||
/**
|
||||
* Проверка кода каптчи
|
||||
* Отправка уведомления о критическом событии
|
||||
*
|
||||
* @param int $code Код
|
||||
* @param string $text Текст алярма
|
||||
*
|
||||
* @return bool Результат валидации
|
||||
* @return void
|
||||
*/
|
||||
public static function isValidCaptcha(string $code): bool
|
||||
public static function sendAlarm(string $title, string $text): void
|
||||
{
|
||||
return (string)$_SESSION['captchaCode'] === $code;
|
||||
$userList = User::getListByRole(Roles::ALARM_ROLE_ID);
|
||||
|
||||
foreach($userList as $userObject) {
|
||||
(new Mail())->setFrom(SERVER_EMAIL, SERVER_EMAIL_NAME)
|
||||
->setTemplate(MAIL_TEMPLATE_DEFAULT)
|
||||
->setTo($userObject->getEmail(), $userObject->getName())
|
||||
->setSubject('Alarm: ' . $title)
|
||||
->setBody($text)
|
||||
->send();
|
||||
}
|
||||
if (function_exists('sendTelegram')) {
|
||||
sendTelegram('<b>' . $title . '</b>' . PHP_EOL. $text);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Проверка авторизации через Telegram
|
||||
*
|
||||
* @param array $authData Данные для проверки
|
||||
*
|
||||
* @return bool Результат проверки
|
||||
*/
|
||||
public static function checkTelegramAuthorization(array $authData): bool
|
||||
{
|
||||
if (empty($authData['hash']) || empty($authData['auth_date'])) {
|
||||
return false;
|
||||
}
|
||||
$checkHash = $authData['hash'];
|
||||
unset($authData['hash']);
|
||||
$dataCheckArr = [];
|
||||
foreach ($authData as $key => $value) {
|
||||
$dataCheckArr[] = $key . '=' . $value;
|
||||
}
|
||||
sort($dataCheckArr);
|
||||
$dataCheckString = implode("\n", $dataCheckArr);
|
||||
$secretKey = hash('sha256', SystemConfig::getValue('TELEGRAM_BOT_TOKEN'), true);
|
||||
$hash = hash_hmac('sha256', $dataCheckString, $secretKey);
|
||||
if (strcmp($hash, $checkHash) !== 0) {
|
||||
//Data is NOT from Telegram
|
||||
return false;
|
||||
}
|
||||
if ((time() - (int)$authData['auth_date']) > 86400) {
|
||||
//Data is outdated
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -25,39 +25,56 @@
|
||||
|
||||
class Thumbs
|
||||
{
|
||||
/** @var string $filename */
|
||||
private string $filename;
|
||||
|
||||
/** @var int $width */
|
||||
private $width;
|
||||
|
||||
/** @var int $height */
|
||||
private $height;
|
||||
|
||||
/** @var int $type */
|
||||
private $type;
|
||||
|
||||
/**
|
||||
* @var false|\GdImage|resource
|
||||
*/
|
||||
private $img;
|
||||
|
||||
public function __construct(string $filename)
|
||||
{
|
||||
$this->filename = $filename;
|
||||
if (empty($this->filename)) {
|
||||
throw new CoreException('Файл не найден');
|
||||
} else {
|
||||
$info = getimagesize($this->filename);
|
||||
if (empty($info)) {
|
||||
throw new CoreException('Файл не найден');
|
||||
} else {
|
||||
$this->width = $info[0];
|
||||
$this->height = $info[1];
|
||||
$this->type = $info[2];
|
||||
switch ($this->type) {
|
||||
case 1:
|
||||
$this->img = imageCreateFromGif($this->filename);
|
||||
break;
|
||||
case 2:
|
||||
$this->img = imageCreateFromJpeg($this->filename);
|
||||
break;
|
||||
case 3:
|
||||
$this->img = imageCreateFromPng($this->filename);
|
||||
imageAlphaBlending($this->img, true);
|
||||
imageSaveAlpha($this->img, true);
|
||||
break;
|
||||
case 18:
|
||||
$this->img = imageCreatefromWebp($this->filename);
|
||||
break;
|
||||
default:
|
||||
throw new CoreException('Формат файла не подерживается');
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$info = getimagesize($this->filename);
|
||||
if (empty($info)) {
|
||||
throw new CoreException('Файл не найден');
|
||||
}
|
||||
|
||||
$this->width = $info[0];
|
||||
$this->height = $info[1];
|
||||
$this->type = $info[2];
|
||||
switch ($this->type) {
|
||||
case IMAGETYPE_GIF:
|
||||
$this->img = imagecreatefromgif($this->filename);
|
||||
break;
|
||||
case IMAGETYPE_JPEG:
|
||||
$this->img = imagecreatefromjpeg($this->filename);
|
||||
break;
|
||||
case IMAGETYPE_PNG:
|
||||
$this->img = imagecreatefrompng($this->filename);
|
||||
imagealphablending($this->img, true);
|
||||
imagesavealpha($this->img, true);
|
||||
break;
|
||||
case IMAGETYPE_WEBP:
|
||||
$this->img = imagecreatefromwebp($this->filename);
|
||||
break;
|
||||
default:
|
||||
throw new CoreException('Формат файла не поддерживается');
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -93,7 +110,7 @@
|
||||
}
|
||||
|
||||
$tmp = imageCreateTrueColor($width, $height);
|
||||
if ($this->type == 1 || $this->type == 3) {
|
||||
if ($this->type === IMAGETYPE_GIF || $this->type === IMAGETYPE_PNG) {
|
||||
imagealphablending($tmp, true);
|
||||
imageSaveAlpha($tmp, true);
|
||||
$transparent = imagecolorallocatealpha($tmp, 0, 0, 0, 127);
|
||||
@@ -230,7 +247,7 @@
|
||||
}
|
||||
|
||||
$tmp = imageCreateTrueColor($width, $height);
|
||||
if ($this->type == 1 || $this->type == 3) {
|
||||
if ($this->type === IMAGETYPE_GIF || $this->type === IMAGETYPE_PNG) {
|
||||
imagealphablending($tmp, true);
|
||||
imageSaveAlpha($tmp, true);
|
||||
$transparent = imagecolorallocatealpha($tmp, 0, 0, 0, 127);
|
||||
@@ -263,9 +280,9 @@
|
||||
$tw = ceil($height / ($this->height / $this->width));
|
||||
$th = ceil($width / ($this->width / $this->height));
|
||||
|
||||
if ($this->width == $this->height) {
|
||||
if ($this->width === $this->height) {
|
||||
// Источник - квадратная фотка
|
||||
if ($width == $height) {
|
||||
if ($width === $height) {
|
||||
// Превью - квадратная.
|
||||
$this->resize($width, $height);
|
||||
} elseif ($width > $height) {
|
||||
@@ -341,9 +358,9 @@
|
||||
$tw = ceil($height / ($this->height / $this->width));
|
||||
$th = ceil($width / ($this->width / $this->height));
|
||||
|
||||
if ($this->width != $width && $this->height != $height) {
|
||||
if ($this->width !== $width && $this->height !== $height) {
|
||||
$tmp = imageCreateTrueColor($width, $height);
|
||||
if ($this->type == 1 || $this->type == 3) {
|
||||
if ($this->type === IMAGETYPE_GIF || $this->type === IMAGETYPE_PNG) {
|
||||
imagealphablending($tmp, true);
|
||||
imageSaveAlpha($tmp, true);
|
||||
$transparent = imagecolorallocatealpha($tmp, 0, 0, 0, 127);
|
||||
@@ -563,9 +580,9 @@
|
||||
unset($tmp);
|
||||
|
||||
return true;
|
||||
} else {
|
||||
return $this->cut($width, $height);
|
||||
}
|
||||
|
||||
return $this->cut($width, $height);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -626,80 +643,80 @@
|
||||
{
|
||||
if (empty($file)) {
|
||||
throw new CoreException('Файл маски не найден');
|
||||
} else {
|
||||
$info = getimagesize($file);
|
||||
if (empty($info)) {
|
||||
throw new CoreException('Файл маски не найден');
|
||||
} else {
|
||||
switch ($info[2]) {
|
||||
case 1:
|
||||
$dest = imageCreateFromGif($file);
|
||||
break;
|
||||
case 2:
|
||||
$dest = imageCreateFromJpeg($file);
|
||||
break;
|
||||
case 3:
|
||||
$dest = imageCreateFromPng($file);
|
||||
$transparent = imagecolorallocatealpha($dest, 0, 0, 0, 127);
|
||||
imagefill($dest, 0, 0, $transparent);
|
||||
imagecolortransparent($dest, $transparent);
|
||||
|
||||
imageAlphaBlending($dest, true);
|
||||
imageSaveAlpha($dest, true);
|
||||
|
||||
|
||||
break;
|
||||
case 18:
|
||||
$dest = imageCreatefromWebp($file);
|
||||
break;
|
||||
default:
|
||||
throw new CoreException('Формат файла маски не подерживается');
|
||||
break;
|
||||
}
|
||||
|
||||
switch ($position) {
|
||||
case 'top':
|
||||
$x = ceil(($this->width - $info[0]) / 2);
|
||||
$y = 0;
|
||||
break;
|
||||
case 'top-left':
|
||||
$x = 0;
|
||||
$y = 0;
|
||||
break;
|
||||
case 'top-right':
|
||||
$x = ceil($this->width - $info[0]);
|
||||
$y = 0;
|
||||
break;
|
||||
case 'left':
|
||||
$x = 0;
|
||||
$y = ceil(($this->height - $info[1]) / 2);
|
||||
break;
|
||||
case 'right':
|
||||
$x = ceil($this->width - $info[0]);
|
||||
$y = ceil(($this->height - $info[1]) / 2);
|
||||
break;
|
||||
case 'bottom':
|
||||
$x = ceil(($this->width - $info[0]) / 2);
|
||||
$y = ceil($this->height - $info[1]);
|
||||
break;
|
||||
case 'bottom-left':
|
||||
$x = 0;
|
||||
$y = ceil($this->height - $info[1]);
|
||||
break;
|
||||
case 'bottom-right':
|
||||
$x = ceil($this->width - $info[0]);
|
||||
$y = ceil($this->height - $info[1]);
|
||||
break;
|
||||
default:
|
||||
$x = ceil(($this->width - $info[0]) / 2);
|
||||
$y = ceil(($this->height - $info[1]) / 2);
|
||||
break;
|
||||
}
|
||||
|
||||
$dest = $this->opacity($dest, $transparency);
|
||||
imagecopy($this->img, $dest, $x, $y, 0, 0, $info[0], $info[1]);
|
||||
}
|
||||
}
|
||||
|
||||
$info = getimagesize($file);
|
||||
if (empty($info)) {
|
||||
throw new CoreException('Файл маски не найден');
|
||||
}
|
||||
|
||||
switch ($info[2]) {
|
||||
case IMAGETYPE_GIF:
|
||||
$dest = imageCreateFromGif($file);
|
||||
break;
|
||||
case IMAGETYPE_JPEG:
|
||||
$dest = imageCreateFromJpeg($file);
|
||||
break;
|
||||
case IMAGETYPE_PNG:
|
||||
$dest = imageCreateFromPng($file);
|
||||
$transparent = imagecolorallocatealpha($dest, 0, 0, 0, 127);
|
||||
imagefill($dest, 0, 0, $transparent);
|
||||
imagecolortransparent($dest, $transparent);
|
||||
|
||||
imageAlphaBlending($dest, true);
|
||||
imageSaveAlpha($dest, true);
|
||||
|
||||
|
||||
break;
|
||||
case IMAGETYPE_WEBP:
|
||||
$dest = imageCreatefromWebp($file);
|
||||
break;
|
||||
default:
|
||||
throw new CoreException('Формат файла маски не подерживается');
|
||||
break;
|
||||
}
|
||||
|
||||
switch ($position) {
|
||||
case 'top':
|
||||
$x = ceil(($this->width - $info[0]) / 2);
|
||||
$y = 0;
|
||||
break;
|
||||
case 'top-left':
|
||||
$x = 0;
|
||||
$y = 0;
|
||||
break;
|
||||
case 'top-right':
|
||||
$x = ceil($this->width - $info[0]);
|
||||
$y = 0;
|
||||
break;
|
||||
case 'left':
|
||||
$x = 0;
|
||||
$y = ceil(($this->height - $info[1]) / 2);
|
||||
break;
|
||||
case 'right':
|
||||
$x = ceil($this->width - $info[0]);
|
||||
$y = ceil(($this->height - $info[1]) / 2);
|
||||
break;
|
||||
case 'bottom':
|
||||
$x = ceil(($this->width - $info[0]) / 2);
|
||||
$y = ceil($this->height - $info[1]);
|
||||
break;
|
||||
case 'bottom-left':
|
||||
$x = 0;
|
||||
$y = ceil($this->height - $info[1]);
|
||||
break;
|
||||
case 'bottom-right':
|
||||
$x = ceil($this->width - $info[0]);
|
||||
$y = ceil($this->height - $info[1]);
|
||||
break;
|
||||
default:
|
||||
$x = ceil(($this->width - $info[0]) / 2);
|
||||
$y = ceil(($this->height - $info[1]) / 2);
|
||||
break;
|
||||
}
|
||||
|
||||
$dest = $this->opacity($dest, $transparency);
|
||||
imagecopy($this->img, $dest, $x, $y, 0, 0, $info[0], $info[1]);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -736,13 +753,13 @@
|
||||
}
|
||||
|
||||
switch ($this->type) {
|
||||
case 1:
|
||||
case IMAGETYPE_GIF:
|
||||
return $this->saveGif($filename);
|
||||
case 2:
|
||||
case IMAGETYPE_JPEG:
|
||||
return $this->saveJpg($filename, $quality);
|
||||
case 3:
|
||||
case IMAGETYPE_PNG:
|
||||
return $this->savePng($filename);
|
||||
case 18:
|
||||
case IMAGETYPE_WEBP:
|
||||
return $this->saveWebp($filename);
|
||||
}
|
||||
}
|
||||
@@ -753,19 +770,19 @@
|
||||
public function output($quality = 100): void
|
||||
{
|
||||
switch ($this->type) {
|
||||
case 1:
|
||||
case IMAGETYPE_GIF:
|
||||
header('Content-Type: image/gif');
|
||||
imageGif($this->img);
|
||||
break;
|
||||
case 2:
|
||||
case IMAGETYPE_JPEG:
|
||||
header('Content-Type: image/jpeg');
|
||||
imageJpeg($this->img, null, $quality);
|
||||
break;
|
||||
case 3:
|
||||
case IMAGETYPE_PNG:
|
||||
header('Content-Type: image/x-png');
|
||||
imagePng($this->img);
|
||||
break;
|
||||
case 18:
|
||||
case IMAGETYPE_WEBP:
|
||||
header('Content-Type: image/webp');
|
||||
imageWebp($this->img, $quality);
|
||||
break;
|
||||
@@ -782,15 +799,15 @@
|
||||
}
|
||||
|
||||
switch ($this->type) {
|
||||
case 1:
|
||||
case IMAGETYPE_GIF:
|
||||
header('Content-Type: image/gif');
|
||||
imageGif($this->img, $filename);
|
||||
break;
|
||||
case 2:
|
||||
case IMAGETYPE_JPEG:
|
||||
header('Content-Type: image/jpeg');
|
||||
imageJpeg($this->img, $filename, $quality);
|
||||
break;
|
||||
case 3:
|
||||
case IMAGETYPE_PNG:
|
||||
header('Content-Type: image/x-png');
|
||||
imagePng($this->img, $filename);
|
||||
break;
|
||||
|
||||
@@ -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('Не найдено новых данных для добавления');
|
||||
}
|
||||
@@ -269,7 +272,7 @@ DELETE from `jokes` WHERE `jokes`.id not in (SELECT id FROM t_temp);'
|
||||
if (date('H') > 21 || date('H') < 9) {
|
||||
return 'Нерабочее время :(';
|
||||
}
|
||||
$telegram = new \Core\ExternalServices\TelegramSender(TELEGRAM_BOT_TOKEN);
|
||||
$telegram = new \Core\ExternalServices\TelegramSender(SystemConfig::getValue('TELEGRAM_BOT_TOKEN'));
|
||||
$telegram->setChat(' -1001610334197');
|
||||
|
||||
/** @var DB $DB */
|
||||
@@ -335,7 +338,7 @@ DELETE from `jokes` WHERE `jokes`.id not in (SELECT id FROM t_temp);'
|
||||
$post .= PHP_EOL . '<a href="' . $link . '">Подробнее</a>';
|
||||
|
||||
|
||||
$telegram = new \Core\ExternalServices\TelegramSender(TELEGRAM_BOT_TOKEN);
|
||||
$telegram = new \Core\ExternalServices\TelegramSender(SystemConfig::getValue('TELEGRAM_BOT_TOKEN'));
|
||||
$telegram->setChat('-1001789206618');
|
||||
$res = $telegram->sendPhoto($tmpFile, $post);
|
||||
sendTelegram($post);
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -62,6 +62,11 @@
|
||||
*/
|
||||
const USER_ROLE_ID = 5;
|
||||
|
||||
/**
|
||||
* Роль "уведомления о событиях"
|
||||
*/
|
||||
const ALARM_ROLE_ID = 6;
|
||||
|
||||
/**
|
||||
* @var User $user
|
||||
*/
|
||||
@@ -125,7 +130,7 @@
|
||||
* @return int|null
|
||||
* @throws CoreException
|
||||
*/
|
||||
public function deleteRole(int $roleId): ?int
|
||||
public function delete(int $roleId): ?int
|
||||
{
|
||||
$cacheId = md5(__CLASS__ . '::' . __FUNCTION__);
|
||||
Cache::delete($cacheId);
|
||||
@@ -135,21 +140,6 @@
|
||||
return $DB->query('DELETE FROM ' . self::USER_ROLES_TABLE . ' WHERE user_id=' . $this->user->getId() . ' AND role_id=' . $roleId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Получение полной информации о ролях пользователя
|
||||
*
|
||||
* @deprecated Реализован новый метод для получения этих данных
|
||||
* @return array|null
|
||||
* @throws CoreException
|
||||
*/
|
||||
public function getFullRolesOld(): ?array
|
||||
{
|
||||
return array_map(function ($element) {
|
||||
return static::getAllRoles()[$element];
|
||||
},
|
||||
$this->getRoles());
|
||||
}
|
||||
|
||||
/**
|
||||
* Получение полной информации о ролях пользователя V2
|
||||
*
|
||||
|
||||
@@ -28,6 +28,7 @@
|
||||
use Core\CoreException;
|
||||
use Core\Helpers\{Cache, Log, Mail, Sanitize, SystemFunctions};
|
||||
use Core\DataBases\DB;
|
||||
use Core\DTO\User\FilterUser;
|
||||
use Throwable;
|
||||
|
||||
class User
|
||||
@@ -720,12 +721,12 @@
|
||||
*/
|
||||
public static function logout(): void
|
||||
{
|
||||
$_SESSION['id'] = '';
|
||||
$_SESSION['authorize'] = '';
|
||||
$_SESSION['login'] = '';
|
||||
$_SESSION['password'] = '';
|
||||
$_SESSION['token'] = '';
|
||||
$_SESSION['user'] = '';
|
||||
unset($_SESSION['id']);
|
||||
unset($_SESSION['authorize']);
|
||||
unset($_SESSION['login']);
|
||||
unset($_SESSION['password']);
|
||||
unset($_SESSION['token']);
|
||||
unset($_SESSION['user']);
|
||||
|
||||
setcookie('userId', '', time() - 3600);
|
||||
setcookie('userLogin', '', time() - 3600);
|
||||
@@ -801,6 +802,26 @@
|
||||
return SystemFunctions::arrayToXml($res, self::TABLE);
|
||||
}
|
||||
|
||||
/**
|
||||
* Выборка пользователей по роли
|
||||
*
|
||||
* @param int $roleId Идентификатор роли
|
||||
*
|
||||
* @return self[]
|
||||
* @throws CoreException
|
||||
*/
|
||||
public static function getListByRole(int $roleId): array
|
||||
{
|
||||
$result = [];
|
||||
/** @var $DB DB Объект базы данных */
|
||||
$DB = DB::getInstance();
|
||||
$res = $DB->getItems(Roles::USER_ROLES_TABLE, ['id' => $roleId]);
|
||||
foreach ($res as $element) {
|
||||
$result[] = new self((int)$element['user_id']);
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Проверка электронной почты на подтвержденность
|
||||
*
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace Core\Models;
|
||||
|
||||
use Core\CoreException;
|
||||
use Core\DataBases\DB;
|
||||
use Core\Helpers\Cache;
|
||||
|
||||
@@ -123,4 +124,18 @@
|
||||
$DB = DB::getInstance();
|
||||
$DB->query('DELETE FROM ' . self::TABLE . ' WHERE user_id=' . $this->user->getId() . ' AND id="' . $id . '"');
|
||||
}
|
||||
|
||||
/**
|
||||
* Получить список мета данных по фильтру
|
||||
*
|
||||
* @param array $params Параметры
|
||||
*
|
||||
* @return array|null
|
||||
* @throws CoreException
|
||||
*/
|
||||
public static function getListByParams(array $params = []): ?array {
|
||||
/** @var $DB DB */
|
||||
$DB = DB::getInstance();
|
||||
return $DB->getItems(self::TABLE, $params);
|
||||
}
|
||||
}
|
||||
@@ -20,7 +20,7 @@
|
||||
*/
|
||||
|
||||
/**
|
||||
* Класс для работы с пользователями
|
||||
* Модель пользователя
|
||||
*/
|
||||
|
||||
namespace Core\Models;
|
||||
@@ -36,6 +36,15 @@
|
||||
/** @var string Имя */
|
||||
protected $name;
|
||||
|
||||
/** @var string $login Логин */
|
||||
protected $login;
|
||||
|
||||
/** @var int $image_id Идентификатор картинки */
|
||||
protected $image_id;
|
||||
|
||||
/** @var string $token Токен */
|
||||
protected $token;
|
||||
|
||||
/**
|
||||
* Получить имя
|
||||
*
|
||||
@@ -59,4 +68,28 @@
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Получить идентификатор изображения
|
||||
*
|
||||
* @return int|null
|
||||
*/
|
||||
public function getImageId(): ?int
|
||||
{
|
||||
return $this->image_id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Установить идентификатор изображения
|
||||
*
|
||||
* @param int $id Идентификатор изображения
|
||||
*
|
||||
* @return $this
|
||||
*/
|
||||
public function setImageId(int $id): self
|
||||
{
|
||||
$this->image_id = $id;
|
||||
return $this;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
<?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;
|
||||
|
||||
/**
|
||||
* Класс системных параметров
|
||||
*/
|
||||
class SystemConfig {
|
||||
public static function getValue(string $param)
|
||||
{
|
||||
// TODO в текущей реализации берем просто заданную константу, в дальнейшем переделать
|
||||
return constant($param);
|
||||
}
|
||||
}
|
||||
@@ -30,6 +30,11 @@
|
||||
|
||||
use Core\Models\MQ;
|
||||
$fromPostId = $argv[1];
|
||||
//sleep(5);
|
||||
|
||||
(new MQ())->setPriority(9)->setAttempts(3)->createTask('Core\MQTasks', 'getStory', [$fromPostId]);
|
||||
(new MQ())->setPriority(9)
|
||||
->setAttempts(2)
|
||||
->createTask(
|
||||
'Core\MQTasks',
|
||||
'getStory',
|
||||
[$fromPostId]
|
||||
);
|
||||
@@ -41,6 +41,12 @@ final class Roles extends AbstractMigration
|
||||
'date_created' => date('Y-m-d H:i:s'),
|
||||
'date_updated' => null,
|
||||
],
|
||||
[
|
||||
'name' => 'Уведомления о событиях',
|
||||
'description' => 'Роль для рассылок уведомлений о сбоях в работе проекта',
|
||||
'date_created' => date('Y-m-d H:i:s'),
|
||||
'date_updated' => null,
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
+2
-1
@@ -3,6 +3,7 @@
|
||||
use Core\CoreException;
|
||||
use Core\ExternalServices\Telegram2;
|
||||
use Core\ExternalServices\ChatGPT;
|
||||
use Core\SystemConfig;
|
||||
|
||||
require_once __DIR__ . '/core/bootstrap.php';
|
||||
|
||||
@@ -13,7 +14,7 @@
|
||||
$data = json_decode($data, true);
|
||||
|
||||
|
||||
$tg = new Telegram2(TELEGRAM_BOT_TOKEN);
|
||||
$tg = new Telegram2(SystemConfig::getValue('TELEGRAM_BOT_TOKEN'));
|
||||
$tg->setRemoteRequest($data);
|
||||
|
||||
$gptObject = new ChatGPT();
|
||||
|
||||
+20
-1
@@ -3,12 +3,31 @@
|
||||
{% block main %}
|
||||
<h1>Авторизация</h1>
|
||||
{% if failed %}
|
||||
<div class="alert alert-error">Ошибка авторизации</div>
|
||||
<div class="alert alert-error">{{ errorMessage }}</div>
|
||||
{% endif %}
|
||||
<p>
|
||||
<form action="/login/authorize" method="POST">
|
||||
<input class="input" type="text" name="login" placeholder="Введите логин">
|
||||
<input class="input" type="password" name="password" placeholder="Введите пароль">
|
||||
|
||||
{% if USE_CAPTCHA %}
|
||||
<div class="input captchaInput">
|
||||
<img id="captchaCode" src="{{ SITE_URL }}/core/captcha.php">
|
||||
<span id="updateCaptcha" class="button" style="vertical-align: super;">Обновить код</span>
|
||||
</div>
|
||||
<input type="text" class="input" name="captchaCode" placeholder="Код с картинки">
|
||||
<script>
|
||||
$(document).ready(function () {
|
||||
let $captchaImage = $('#captchaCode'),
|
||||
$captchaSrc = $captchaImage.attr('src'),
|
||||
$updateBtn = $('#updateCaptcha');
|
||||
$updateBtn.click(function () {
|
||||
$captchaImage.attr('src', $captchaSrc + `?v=${new Date().getTime()}`);
|
||||
});
|
||||
});
|
||||
</script>
|
||||
{% endif %}
|
||||
|
||||
<button class="button w100" type="submit">Войти</button>
|
||||
</form>
|
||||
</p>
|
||||
|
||||
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 |
File renamed without changes.
File renamed without changes.
Reference in new issue
Block a user