[+] добавлен Phinx и миграции
[-] удалены мусорные файлы [*] скорректирован composer.json
This commit is contained in:
1 parent
24bb9a6830
commit
cde08cff9b
33 files changed
+1011
-1983
No files matched your search
@@ -0,0 +1 @@
|
||||
/vendor/
|
||||
Generated
+9
-1
@@ -15,7 +15,6 @@
|
||||
<excludeFolder url="file://$MODULE_DIR$/vendor/sebastian/diff" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/vendor/guzzlehttp/psr7" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/vendor/sabberworm/php-css-parser" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/vendor/workerman/workerman" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/vendor/guzzlehttp/promises" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/vendor/felixfbecker/advanced-json-rpc" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/vendor/felixfbecker/language-server-protocol" />
|
||||
@@ -84,6 +83,15 @@
|
||||
<excludeFolder url="file://$MODULE_DIR$/vendor/phpunit/php-timer" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/vendor/phpunit/phpunit" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/vendor/theseer/tokenizer" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/vendor/psr/simple-cache" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/vendor/symfony/filesystem" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/vendor/symfony/polyfill-php81" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/vendor/symfony/config" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/vendor/cakephp/database" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/vendor/cakephp/datasource" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/vendor/cakephp/core" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/vendor/cakephp/utility" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/vendor/robmorgan/phinx" />
|
||||
</content>
|
||||
<orderEntry type="inheritedJdk" />
|
||||
<orderEntry type="sourceFolder" forTests="false" />
|
||||
|
||||
Generated
+9
-1
@@ -25,7 +25,6 @@
|
||||
<path value="$PROJECT_DIR$/vendor/sebastian/diff" />
|
||||
<path value="$PROJECT_DIR$/vendor/guzzlehttp/psr7" />
|
||||
<path value="$PROJECT_DIR$/vendor/sabberworm/php-css-parser" />
|
||||
<path value="$PROJECT_DIR$/vendor/workerman/workerman" />
|
||||
<path value="$PROJECT_DIR$/vendor/guzzlehttp/promises" />
|
||||
<path value="$PROJECT_DIR$/vendor/felixfbecker/advanced-json-rpc" />
|
||||
<path value="$PROJECT_DIR$/vendor/felixfbecker/language-server-protocol" />
|
||||
@@ -94,6 +93,15 @@
|
||||
<path value="$PROJECT_DIR$/vendor/phpunit/php-timer" />
|
||||
<path value="$PROJECT_DIR$/vendor/phpunit/phpunit" />
|
||||
<path value="$PROJECT_DIR$/vendor/theseer/tokenizer" />
|
||||
<path value="$PROJECT_DIR$/vendor/psr/simple-cache" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/filesystem" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/polyfill-php81" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/config" />
|
||||
<path value="$PROJECT_DIR$/vendor/cakephp/database" />
|
||||
<path value="$PROJECT_DIR$/vendor/cakephp/datasource" />
|
||||
<path value="$PROJECT_DIR$/vendor/cakephp/core" />
|
||||
<path value="$PROJECT_DIR$/vendor/cakephp/utility" />
|
||||
<path value="$PROJECT_DIR$/vendor/robmorgan/phinx" />
|
||||
</include_path>
|
||||
</component>
|
||||
<component name="PhpInterpreters">
|
||||
|
||||
Generated
-9
@@ -1,9 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="SqlDialectMappings">
|
||||
<file url="file://$PROJECT_DIR$/core/SQL_DUMPS/files.sql" dialect="MySQL" />
|
||||
<file url="file://$PROJECT_DIR$/core/SQL_DUMPS/threads.sql" dialect="MySQL" />
|
||||
<file url="file://$PROJECT_DIR$/core/SQL_DUMPS/users.sql" dialect="MariaDB" />
|
||||
<file url="file://$PROJECT_DIR$/core/migrations/000001_core.sql" dialect="MySQL" />
|
||||
</component>
|
||||
</project>
|
||||
@@ -35,7 +35,21 @@ Delta Framework - простой фреймворк для разработки
|
||||
const DB_NAME = 'deltacore';
|
||||
```
|
||||
|
||||
На текущем этапе разработки миграции еще не готовы, поэтому требуется создание таблиц из дампов (```/core/migrations/*.sql```)
|
||||
Также настройте Phinx для использования миграций (```/phinx.php```)
|
||||
```
|
||||
'host' => 'localhost',
|
||||
'name' => 'deltacore',
|
||||
'user' => 'vasya',
|
||||
'pass' => 'mysuperpassword',
|
||||
```
|
||||
|
||||
Далее потребуется выполнить непосредственно сами миграции. В зависимости от окружения используйте ````dev```` или ````prod````.
|
||||
|
||||
Для примера выполним миграцию в окружение для разработки
|
||||
|
||||
````
|
||||
vendor/bin/phinx migrate -e dev
|
||||
````
|
||||
|
||||
Доступ к панели управления находится тут
|
||||
````https://site.ru/admin/````
|
||||
|
||||
@@ -1,158 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<!-- Required meta tags -->
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
|
||||
|
||||
<!-- Bootstrap CSS -->
|
||||
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
|
||||
|
||||
<title>Чат для компании</title>
|
||||
<style>
|
||||
div#app {
|
||||
height: 380px;
|
||||
overflow-y: scroll;
|
||||
box-shadow: inset 0px 15px 10px -7px black;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<div class="container mt-5">
|
||||
|
||||
<div id="userList"></div>
|
||||
|
||||
|
||||
<div id="app">
|
||||
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
|
||||
<div class="input-group">
|
||||
<div class="input-group-prepend">
|
||||
<span class="input-group-text">Введите сообщение</span>
|
||||
</div>
|
||||
<textarea id="message" class="form-control" aria-label="With textarea"></textarea>
|
||||
</div>
|
||||
<button id="sendBtn" type="button" class="btn btn-primary btn-lg btn-block">Отправить</button>
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
|
||||
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
|
||||
|
||||
<script>
|
||||
function getRandomInt(min, max) {
|
||||
min = Math.ceil(min);
|
||||
max = Math.floor(max);
|
||||
return Math.floor(Math.random() * (max - min)) + min;
|
||||
}
|
||||
|
||||
let socket = new WebSocket('wss://dev.it-stories.ru/wss?userName=Guest_' + getRandomInt(1, 9999));
|
||||
|
||||
socket.onopen = function(e) {
|
||||
/*const initMessage = {
|
||||
method: 'registration',
|
||||
userId: 1,
|
||||
date: Date.now()
|
||||
};
|
||||
socket.send(JSON.stringify(initMessage));*/
|
||||
};
|
||||
|
||||
socket.onmessage = function(event) {
|
||||
let data = JSON.parse(event.data);
|
||||
// Обработка пингов
|
||||
if (data.action === 'Ping') {
|
||||
const pongMessage = {action: 'Pong'};
|
||||
socket.send(JSON.stringify(pongMessage));
|
||||
return;
|
||||
}
|
||||
|
||||
// Обработка подключившихся пользователей
|
||||
if (data.action === 'PublicMessage') {
|
||||
$('#app').append(`<div class="alert alert-success" role="alert"><h5 class="alert-heading" onClick="contactTo('${data.userName}')">${data.userName}</h5>${data.text}</div>`)
|
||||
//return;
|
||||
}
|
||||
|
||||
// Обработка при подключении
|
||||
if (data.action === 'Connected') {
|
||||
$('#app').append(`<div class="alert alert-info" role="alert">Пользователь <b>${data.userName}</b> подлючился в чат</div>`)
|
||||
//return;
|
||||
}
|
||||
|
||||
// Обработка при подключении
|
||||
if (data.action === 'Authorized') {
|
||||
$('#userList').html('');
|
||||
data.users.forEach(function(element){
|
||||
$('#userList').append(`<span class="badge badge-secondary m-2">${element.userName}</span>`)
|
||||
});
|
||||
//return;
|
||||
}
|
||||
|
||||
// Обработка при отклбчении
|
||||
if (data.action === 'Disconnected') {
|
||||
$('#app').append(`<div class="alert alert-info" role="alert">Пользователь <b>${data.userName}</b> покинул чат</div>`)
|
||||
|
||||
$('#userList').html('');
|
||||
data.users.forEach(function(element){
|
||||
$('#userList').append(`<span class="badge badge-secondary">${element.userName}</span>`)
|
||||
});
|
||||
//return;
|
||||
}
|
||||
|
||||
// Обработка при отклбчении
|
||||
if (data.action === 'Information') {
|
||||
$('#app').append(`<div class="alert alert-warning" role="alert">${data.text}</div>`)
|
||||
//return;
|
||||
}
|
||||
|
||||
window.document.getElementById('app').scrollTop = window.document.getElementById('app').scrollHeight
|
||||
};
|
||||
|
||||
socket.onclose = function(event) {
|
||||
if (event.wasClean) {
|
||||
console.log(`[close] Соединение закрыто чисто, код=${event.code} причина=${event.reason}`);
|
||||
} else {
|
||||
console.log('[close] Соединение прервано');
|
||||
}
|
||||
};
|
||||
|
||||
socket.onerror = function(error) {
|
||||
console.log(`[error]`);
|
||||
};
|
||||
|
||||
$('#sendBtn').on('click', function(){
|
||||
let messageText = $('#message').val();
|
||||
if (messageText === "") {
|
||||
return;
|
||||
}
|
||||
|
||||
const message = {
|
||||
action: 'PublicMessage',
|
||||
text: $('#message').val()
|
||||
};
|
||||
socket.send(JSON.stringify(message));
|
||||
$('#message').val('');
|
||||
});
|
||||
|
||||
function contactTo(name){
|
||||
$('#message').val($('#message').val() + " [b]" + name + "[/b] ");
|
||||
}
|
||||
</script>
|
||||
|
||||
|
||||
</body>
|
||||
</html>
|
||||
+2
-2
@@ -25,8 +25,8 @@
|
||||
"ext-dom": "*",
|
||||
"ext-pdo": "*",
|
||||
"ext-mbstring": "*",
|
||||
"dompdf/dompdf": "^2.0",
|
||||
"workerman/workerman": "^4.1"
|
||||
"dompdf/dompdf": "^2.0",
|
||||
"robmorgan/phinx": "^0.13.4"
|
||||
},
|
||||
"require-dev": {
|
||||
"vimeo/psalm": "^4.27",
|
||||
|
||||
Generated
+943
-414
File diff suppressed because it is too large.
Load diff
@@ -1,10 +0,0 @@
|
||||
CREATE TABLE `files` (
|
||||
`id` int(11) NOT NULL,
|
||||
`name` varchar(255) DEFAULT NULL,
|
||||
`path` text
|
||||
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
|
||||
|
||||
ALTER TABLE `files` ADD PRIMARY KEY (`id`);
|
||||
|
||||
ALTER TABLE `files` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=23;
|
||||
COMMIT;
|
||||
@@ -1,13 +0,0 @@
|
||||
CREATE TABLE `roles` (
|
||||
`id` int(11) NOT NULL,
|
||||
`name` text,
|
||||
`description` text
|
||||
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
|
||||
|
||||
|
||||
INSERT INTO `roles` (`id`, `name`, `description`) VALUES
|
||||
(1, 'Админисистратор', 'Группа, имеющая доступ ко всему'),
|
||||
(2, 'Пользователи', 'Базовая группа для простых пользователей'),
|
||||
|
||||
ALTER TABLE `roles` ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `id` (`id`);
|
||||
COMMIT;
|
||||
@@ -1,19 +0,0 @@
|
||||
CREATE TABLE `threads` (
|
||||
`id` int(11) NOT NULL,
|
||||
`active` varchar(1) NOT NULL DEFAULT 'N',
|
||||
`in_progress` varchar(1) NOT NULL DEFAULT 'N',
|
||||
`priority` int(11) DEFAULT NULL,
|
||||
`execution_time` varchar(255) DEFAULT NULL,
|
||||
`attempts` int(11) NOT NULL,
|
||||
`attempts_limit` int(11) DEFAULT '1',
|
||||
`date_created` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
`date_updated` datetime DEFAULT NULL,
|
||||
`class` varchar(255) DEFAULT NULL,
|
||||
`method` varchar(255) DEFAULT NULL,
|
||||
`params` text,
|
||||
`status` varchar(255) DEFAULT NULL,
|
||||
`response` text
|
||||
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
|
||||
ALTER TABLE `threads` ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `id` (`id`);
|
||||
ALTER TABLE `threads` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=78989;
|
||||
COMMIT;
|
||||
@@ -1,18 +0,0 @@
|
||||
CREATE TABLE `threads_history` (
|
||||
`id` int(11) NOT NULL,
|
||||
`task_id` int(11) DEFAULT NULL,
|
||||
`execution_time` varchar(255) DEFAULT NULL,
|
||||
`attempts` int(11) NOT NULL,
|
||||
`date_created` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
`date_updated` datetime DEFAULT NULL,
|
||||
`class` varchar(255) DEFAULT NULL,
|
||||
`method` varchar(255) DEFAULT NULL,
|
||||
`params` text,
|
||||
`status` varchar(255) DEFAULT NULL,
|
||||
`response` text
|
||||
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
|
||||
|
||||
ALTER TABLE `threads_history` ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `id` (`id`);
|
||||
|
||||
ALTER TABLE `threads_history` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7946;
|
||||
COMMIT;
|
||||
@@ -1,10 +0,0 @@
|
||||
CREATE TABLE `user_roles` (
|
||||
`id` int(11) NOT NULL,
|
||||
`user_id` int(11) NOT NULL,
|
||||
`role_id` int(11) NOT NULL
|
||||
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
|
||||
|
||||
INSERT INTO `user_roles` (`id`, `user_id`, `role_id`) VALUES (1, 1, 1),
|
||||
ALTER TABLE `user_roles` ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `id` (`id`);
|
||||
ALTER TABLE `user_roles` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;
|
||||
COMMIT;
|
||||
@@ -1,30 +0,0 @@
|
||||
CREATE TABLE `users`
|
||||
(
|
||||
`id` int(11) NOT NULL,
|
||||
`active` enum('Y','N') NOT NULL DEFAULT 'YN',
|
||||
`login` varchar(100) NOT NULL,
|
||||
`password` varchar(100) NOT NULL,
|
||||
`name` varchar(150) NOT NULL,
|
||||
`email` text,
|
||||
`image_id` int(11) DEFAULT NULL,
|
||||
`token` text,
|
||||
`last_active` varchar(100) NOT NULL,
|
||||
`date_created` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
`date_updated` datetime DEFAULT NULL
|
||||
) ENGINE = MyISAM
|
||||
DEFAULT CHARSET = utf8;
|
||||
|
||||
INSERT INTO `users` (`id`, `login`, `password`, `name`, `email`, `image_id`, `token`, `last_active`, `date_created`, `date_updated`)
|
||||
VALUES (1, 'Y', 'admin', '5321ef98bd96cccf03f50979fdd8c893', 'Роман Гринько', 'rsgrinko@yandex.ru', 18, 'RG1819-1000-77EB-8F7A-9B112FB69D3A0',
|
||||
'1657051585', '2022-06-17 16:18:56', NULL),
|
||||
(2, 'Y', 'a.kirilcev', 'c7e82c3d2bed998ea1f4c1aca09c282b', 'Александр Кирильцев', 'a.kirilcev@it-tula.ru', 20,
|
||||
'RG17DE-1000-26FC-837F-8F9C47E643970', '1655471459', '2022-06-17 16:18:56', NULL),
|
||||
(3, 'Y', 'system', '', 'Система', 'info@it-stories.ru', NULL, 'RG17DE-1000-2702-816F-97E3877DD6650', '1651673702', '2022-06-17 16:18:56', NULL);
|
||||
|
||||
ALTER TABLE `users`
|
||||
ADD PRIMARY KEY (`id`);
|
||||
|
||||
ALTER TABLE `users`
|
||||
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT,
|
||||
AUTO_INCREMENT = 25;
|
||||
COMMIT;
|
||||
@@ -1,203 +0,0 @@
|
||||
<?php
|
||||
/**
|
||||
* Copyright (c) 2022 Roman Grinko <rsgrinko@gmail.com>
|
||||
* Permission is hereby granted, free of charge, to any person obtaining
|
||||
* a copy of this software and associated documentation files (the
|
||||
* "Software"), to deal in the Software without restriction, including
|
||||
* without limitation the rights to use, copy, modify, merge, publish,
|
||||
* distribute, sublicense, and/or sell copies of the Software, and to
|
||||
* permit persons to whom the Software is furnished to do so, subject to
|
||||
* the following conditions:
|
||||
* The above copyright notice and this permission notice shall be included
|
||||
* in all copies or substantial portions of the Software.
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
||||
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
||||
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
|
||||
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
|
||||
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
|
||||
namespace Core\Helpers;
|
||||
|
||||
use Core\CoreException;
|
||||
|
||||
class Ascii
|
||||
{
|
||||
/**
|
||||
* @var \GdImage Изображение
|
||||
*/
|
||||
private $image;
|
||||
|
||||
/**
|
||||
* @var string $file Полный путь до изображения
|
||||
*/
|
||||
private string $file;
|
||||
|
||||
/**
|
||||
* @var int $pixelSize Размер пикселя
|
||||
*/
|
||||
private int $pixelSize = 1;
|
||||
|
||||
/**
|
||||
* @var int $quality Качество
|
||||
*/
|
||||
private int $quality = 1;
|
||||
|
||||
/**
|
||||
* @var bool $isUseColor Флаг использования цвета
|
||||
*/
|
||||
public bool $isUseColor = false;
|
||||
|
||||
/**
|
||||
* @var array|string[] $chars Массив символов для рисования
|
||||
*/
|
||||
public array $chars = ['@', '#', '+', '\'', ';', ':', ',', '.', '`', ' '];
|
||||
|
||||
/**
|
||||
* @var string $colorChar Символ для цветного рисования
|
||||
*/
|
||||
public string $colorChar = '#';
|
||||
|
||||
/**
|
||||
* Конструктор
|
||||
*
|
||||
* @param string $file Полный путь к изображению
|
||||
*
|
||||
* @throws CoreException
|
||||
*/
|
||||
public function __construct(string $file)
|
||||
{
|
||||
$this->file = $file;
|
||||
|
||||
if (!file_exists($file)) {
|
||||
throw new CoreException('Изображение ' . $this->file . ' недоступно.');
|
||||
}
|
||||
|
||||
switch (exif_imagetype($file)) {
|
||||
case IMAGETYPE_GIF:
|
||||
$this->image = imagecreatefromgif($this->file);
|
||||
break;
|
||||
case IMAGETYPE_JPEG:
|
||||
$this->image = imagecreatefromjpeg($this->file);
|
||||
break;
|
||||
case IMAGETYPE_PNG:
|
||||
$this->image = imagecreatefrompng($this->file);
|
||||
break;
|
||||
case IMAGETYPE_WBMP:
|
||||
$this->image = imagecreatefromwbmp($this->file);
|
||||
break;
|
||||
case IMAGETYPE_XBM:
|
||||
$this->image = imagecreatefromxbm($this->file);
|
||||
break;
|
||||
default:
|
||||
throw new CoreException('Неподдерживаемый формат изображения.');
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Установка размера пикселя
|
||||
*
|
||||
* @param int $size Размер пикселя
|
||||
*
|
||||
* @return $this
|
||||
*/
|
||||
public function setPixelSize(int $size): self
|
||||
{
|
||||
$this->pixelSize = $size;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Установка флага Цветного/ЧБ изображения
|
||||
*
|
||||
* @param bool $isUseColor Флаг использования цвета
|
||||
*
|
||||
* @return $this
|
||||
*/
|
||||
public function setUseColor(bool $isUseColor = true): self
|
||||
{
|
||||
$this->isUseColor = $isUseColor;
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Получение ASCII изображения
|
||||
*
|
||||
* @return string ASCII изображение
|
||||
*/
|
||||
public function draw(): string
|
||||
{
|
||||
$width = imagesx($this->image);
|
||||
$height = imagesy($this->image);
|
||||
|
||||
if ($this->isUseColor === true) {
|
||||
$pixel_color = imagecolorat($this->image, 1, 1);
|
||||
$rgb = imagecolorsforindex($this->image, $pixel_color);
|
||||
$output = '<span style="color: ' . $this->rgbToHex($rgb['red'], $rgb['green'], $rgb['blue']) . ';">';
|
||||
} else {
|
||||
$output = '';
|
||||
}
|
||||
|
||||
for ($y = 0; $y < $height; $y += $this->quality) {
|
||||
for ($x = 0; $x < $width; $x += $this->quality) {
|
||||
$pixel_color = imagecolorat($this->image, $x, $y);
|
||||
$rgb = imagecolorsforindex($this->image, $pixel_color);
|
||||
|
||||
if ($this->isUseColor === true) {
|
||||
if ($x > $this->quality && $y > $this->quality && $pixel_color === imagecolorat($this->image, $x - $this->quality, $y)) {
|
||||
$char = $this->colorChar;
|
||||
} else {
|
||||
$char = '</span><span style="color: ' . $this->rgbToHex($rgb['red'], $rgb['green'], $rgb['blue']) . ';">'
|
||||
. $this->colorChar;
|
||||
}
|
||||
} else {
|
||||
$brightness = $rgb['red'] + $rgb['green'] + $rgb['blue'];
|
||||
$brightness = round($brightness / (765 / (count($this->chars) - 1)));
|
||||
$char = $this->chars[$brightness];
|
||||
}
|
||||
$output .= $char;
|
||||
}
|
||||
$output .= PHP_EOL;
|
||||
}
|
||||
|
||||
if ($this->isUseColor === true) {
|
||||
$output .= '</span>';
|
||||
}
|
||||
|
||||
$result = '<pre style="font: ' . $this->pixelSize * 2 . 'px/' . $this->pixelSize . 'px monospace;">';
|
||||
$result .= $output;
|
||||
$result .= '</pre>';
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Преобразование цвета из RDB в HEX
|
||||
*
|
||||
* @param int $red Красный
|
||||
* @param int $green Зеленый
|
||||
* @param int $blue Синий
|
||||
*
|
||||
* @return string Цвет в HEX
|
||||
*/
|
||||
private function rgbToHex(int $red, int $green, int $blue): string
|
||||
{
|
||||
$hex = '#';
|
||||
$hex .= str_pad(dechex($red), 2, '0', STR_PAD_LEFT);
|
||||
$hex .= str_pad(dechex($green), 2, '0', STR_PAD_LEFT);
|
||||
$hex .= str_pad(dechex($blue), 2, '0', STR_PAD_LEFT);
|
||||
return $hex;
|
||||
}
|
||||
|
||||
/**
|
||||
* Деструктор
|
||||
*/
|
||||
public function __destruct()
|
||||
{
|
||||
imagedestroy($this->image);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,118 +0,0 @@
|
||||
<?php
|
||||
/**
|
||||
* Copyright (c) 2022 Roman Grinko <rsgrinko@gmail.com>
|
||||
* Permission is hereby granted, free of charge, to any person obtaining
|
||||
* a copy of this software and associated documentation files (the
|
||||
* "Software"), to deal in the Software without restriction, including
|
||||
* without limitation the rights to use, copy, modify, merge, publish,
|
||||
* distribute, sublicense, and/or sell copies of the Software, and to
|
||||
* permit persons to whom the Software is furnished to do so, subject to
|
||||
* the following conditions:
|
||||
* The above copyright notice and this permission notice shall be included
|
||||
* in all copies or substantial portions of the Software.
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
||||
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
||||
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
|
||||
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
|
||||
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
|
||||
namespace Core\Helpers;
|
||||
|
||||
class Crypto
|
||||
{
|
||||
/**
|
||||
* @var string|null $key Ключ шифрования
|
||||
*/
|
||||
private $key = CRYPTO_KEY;
|
||||
|
||||
/**
|
||||
* @var string $method Метод шифрования
|
||||
*/
|
||||
private $method = 'AES-192-CBC';
|
||||
|
||||
/**
|
||||
* @var string $algorithm Алгоритм
|
||||
*/
|
||||
private $algorithm = 'sha256';
|
||||
|
||||
|
||||
/**
|
||||
* Конструктор
|
||||
*/
|
||||
public function __construct()
|
||||
{
|
||||
}
|
||||
|
||||
/**
|
||||
* Деструктор
|
||||
*/
|
||||
public function __destruct()
|
||||
{
|
||||
unset($this->key);
|
||||
unset($this->method);
|
||||
}
|
||||
|
||||
/**
|
||||
* Генерация ключа шифрования
|
||||
*
|
||||
* @return string Ключ
|
||||
*/
|
||||
public static function generateKey(): string
|
||||
{
|
||||
return bin2hex(openssl_random_pseudo_bytes(40));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $key
|
||||
*
|
||||
* @return Crypto
|
||||
*/
|
||||
public function setKey(string $key): self
|
||||
{
|
||||
$this->key = $key;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Шифрование данных
|
||||
*
|
||||
* @param string $string Строка
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function encode(string $string): string
|
||||
{
|
||||
$ivLength = openssl_cipher_iv_length($this->method);
|
||||
$iv = openssl_random_pseudo_bytes($ivLength);
|
||||
$cipherTextRaw = openssl_encrypt($string, $this->method, $this->key, OPENSSL_RAW_DATA, $iv);
|
||||
$hmac = hash_hmac($this->algorithm, $cipherTextRaw, $this->key, true);
|
||||
$cipherText = base64_encode($iv . $hmac . $cipherTextRaw);
|
||||
return $cipherText;
|
||||
}
|
||||
|
||||
/**
|
||||
* Расшифровка данных
|
||||
*
|
||||
* @param string $string Зашифрованная строка
|
||||
*
|
||||
* @return string|null
|
||||
*/
|
||||
public function decode(string $string): ?string
|
||||
{
|
||||
$c = base64_decode($string);
|
||||
$ivLength = openssl_cipher_iv_length($this->method);
|
||||
$iv = substr($c, 0, $ivLength);
|
||||
$hmac = substr($c, $ivLength, $sha2len = 32);
|
||||
$cipherTextRaw = substr($c, $ivLength + $sha2len);
|
||||
$result = openssl_decrypt($cipherTextRaw, $this->method, $this->key, OPENSSL_RAW_DATA, $iv);
|
||||
$calcMac = hash_hmac($this->algorithm, $cipherTextRaw, $this->key, true);
|
||||
if (hash_equals($hmac, $calcMac)) {
|
||||
return $result;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,209 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Core\ML;
|
||||
|
||||
class NeuroNetwork
|
||||
{
|
||||
|
||||
/** @var string $storageFile Файл-хранилище весов */
|
||||
private $storageFile;
|
||||
|
||||
/** @var array $arValues Файл-хранилище весов */
|
||||
private $arValues;
|
||||
|
||||
/**
|
||||
* @var array $layers Массив массивов нейронов
|
||||
* [
|
||||
* [], // Входной слой
|
||||
* [], // Скрытый слой
|
||||
* [], // Выходной слой
|
||||
* ];
|
||||
*/
|
||||
private array $layers;
|
||||
|
||||
/** @var array Массив синапсов */
|
||||
private array $synapses;
|
||||
|
||||
/**
|
||||
* Конструктор
|
||||
*/
|
||||
public function __construct(?string $storageFile = null)
|
||||
{
|
||||
// Хранилище весов
|
||||
if ($storageFile === null) {
|
||||
$this->storageFile = $_SERVER['DOCUMENT_ROOT'] . '/neuroSynaps.json';
|
||||
} else {
|
||||
$this->storageFile = $storageFile;
|
||||
}
|
||||
|
||||
// Слои нейросети
|
||||
$this->layers = [
|
||||
[new Neuron(1), new Neuron(2)],
|
||||
[new Neuron(3), new Neuron(4), new Neuron(5), new Neuron(6)],
|
||||
[new Neuron(7)],
|
||||
];
|
||||
|
||||
|
||||
/** Строим связи нейронов */
|
||||
$this->generateSynapses();
|
||||
/*$this->synaps = [
|
||||
new Synaps($this->layers[0][0], $this->layers[1][0]),
|
||||
new Synaps($this->layers[0][0], $this->layers[1][1]),
|
||||
new Synaps($this->layers[0][0], $this->layers[1][2]),
|
||||
new Synaps($this->layers[0][0], $this->layers[1][3]),
|
||||
new Synaps($this->layers[0][1], $this->layers[1][0]),
|
||||
new Synaps($this->layers[0][1], $this->layers[1][1]),
|
||||
new Synaps($this->layers[0][1], $this->layers[1][2]),
|
||||
new Synaps($this->layers[0][1], $this->layers[1][3]),
|
||||
new Synaps($this->layers[1][0], $this->layers[2][0]),
|
||||
new Synaps($this->layers[1][0], $this->layers[2][1]),
|
||||
new Synaps($this->layers[1][1], $this->layers[2][0]),
|
||||
new Synaps($this->layers[1][1], $this->layers[2][1]),
|
||||
new Synaps($this->layers[1][2], $this->layers[2][0]),
|
||||
new Synaps($this->layers[1][2], $this->layers[2][1]),
|
||||
new Synaps($this->layers[1][3], $this->layers[2][0]),
|
||||
new Synaps($this->layers[1][3], $this->layers[2][1]),
|
||||
];*/
|
||||
|
||||
// Получение сохраненных данных по весам
|
||||
$this->getSynapsValue();
|
||||
}
|
||||
|
||||
/**
|
||||
* Генерируем связи между нейронами
|
||||
*/
|
||||
private function generateSynapses(): void
|
||||
{
|
||||
$synapsId = 1;
|
||||
$layersCount = count($this->layers);
|
||||
|
||||
// Бежим по слоям нейронов (последний нам не нужен) и строим связи
|
||||
for ($i = 0; $i < $layersCount - 1; $i++) {
|
||||
$neuronCount = count($this->layers[$i + 1]);
|
||||
for ($j = 0; $j < $neuronCount; $j++) {
|
||||
$neuronInCount = count($this->layers[$i]);
|
||||
for ($k = 0; $k < $neuronInCount; $k++) {
|
||||
$this->synapses[] = new Synaps(
|
||||
$synapsId, $this->layers[$i][$k], $this->layers[$i + 1][$j], $this->arValues[$synapsId] ?? null
|
||||
);
|
||||
$synapsId++;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Сохранить значения весов синапсов в файл
|
||||
*
|
||||
* @param bool $forceUpdate Принудительно перезаписать
|
||||
*/
|
||||
private function saveSynapsValue(bool $forceUpdate= false): void
|
||||
{
|
||||
$data = [];
|
||||
foreach ($this->synapses as $synapse) {
|
||||
/** @var Synaps $synapse */
|
||||
$data[$synapse->getId()] = $synapse->getValue();
|
||||
}
|
||||
|
||||
if ($forceUpdate || !file_exists($this->storageFile)) {
|
||||
echo 'SAVED FILE' . PHP_EOL;
|
||||
file_put_contents($this->storageFile, json_encode($data, JSON_UNESCAPED_UNICODE));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Получить значения весов синапсов из файла
|
||||
*
|
||||
* @return array Сохраненный раннее массив весов
|
||||
*/
|
||||
private function getSynapsValue(): array
|
||||
{
|
||||
if (!file_exists($this->storageFile)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
// Получаем массив весов
|
||||
$synapsValues = json_decode(file_get_contents($this->storageFile), true);
|
||||
|
||||
// Устанавливаем веса для синапсов
|
||||
foreach ($this->synapses as $synapse) {
|
||||
/** @var Synaps $synapse */
|
||||
$synapse->setValue($synapsValues[$synapse->getId()]);
|
||||
}
|
||||
|
||||
$this->arValues = $synapsValues;
|
||||
|
||||
// Возвращаем веса
|
||||
return $synapsValues;
|
||||
}
|
||||
|
||||
/**
|
||||
* Мутация веса
|
||||
*
|
||||
* @param float|null $shift Величина сдвига для мутации
|
||||
*
|
||||
* @throws \Exception
|
||||
*/
|
||||
public function mutate(?float $shift = 0.1): self
|
||||
{
|
||||
foreach ($this->synapses as $synapse) {
|
||||
/** @var Synaps $synapse */
|
||||
$tempValue = random_int((int)(($synapse->getValue() - $shift) * 100), (int)(($synapse->getValue() + $shift) * 100)) / 100;
|
||||
|
||||
// Ограничиваемся диапазоном 0..1
|
||||
if ($tempValue < 0) {
|
||||
$tempValue = 0;
|
||||
}
|
||||
if ($tempValue > 1) {
|
||||
$tempValue = 1;
|
||||
}
|
||||
|
||||
$synapse->setValue($tempValue);
|
||||
}
|
||||
|
||||
$this->saveSynapsValue(true);
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Запуск обработки
|
||||
*/
|
||||
public function run(array $arValue): array
|
||||
{
|
||||
foreach ($arValue as $key => $value) {
|
||||
$this->layers[0][$key]->setValue($value);
|
||||
}
|
||||
foreach ($this->synapses as $synapse) {
|
||||
$this->step($synapse);
|
||||
}
|
||||
|
||||
$result = [];
|
||||
// Отдаем значения нейронов последнего слоя как результат
|
||||
foreach ($this->layers[2] as $neuron) {
|
||||
$result[] = $neuron->getValue();
|
||||
}
|
||||
$this->saveSynapsValue();
|
||||
return $result;
|
||||
//return [$this->layers[2][0]->getValue(), $this->layers[2][1]->getValue()];
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Шаг преобразования значений между нейронами
|
||||
*/
|
||||
public function step(Synaps $synaps): void
|
||||
{
|
||||
/*
|
||||
// Умножение значения на коэфициент
|
||||
$synaps->getOutNeuron()->setValue(
|
||||
$synaps->getInNeuron()->getValue() * $synaps->getValue()
|
||||
);*/
|
||||
|
||||
// Гиперболический тангенс
|
||||
// https://otus.ru/journal/kak-sozdat-nejroset/
|
||||
// Функция активации
|
||||
$synaps->getOutNeuron()->setValue(
|
||||
tanh($synaps->getInNeuron()->getValue() * $synaps->getValue())
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Core\ML;
|
||||
|
||||
/**
|
||||
* Класс нейрона
|
||||
*/
|
||||
class Neuron
|
||||
{
|
||||
|
||||
/** @var int Идентификатор нейрона */
|
||||
private int $id;
|
||||
|
||||
/** @var float|null Текущее значение */
|
||||
private ?float $value;
|
||||
|
||||
/**
|
||||
* Конструктор
|
||||
*
|
||||
* @param int $id Идентификатор нейрона
|
||||
*/
|
||||
public function __construct(int $id)
|
||||
{
|
||||
$this->id = $id;
|
||||
}
|
||||
|
||||
/** Получить текущее значение */
|
||||
public function getValue(): ?float
|
||||
{
|
||||
return $this->value;
|
||||
}
|
||||
|
||||
/** Задать текущее значение */
|
||||
public function setValue(float $value): self
|
||||
{
|
||||
$this->value = $value;
|
||||
return $this;
|
||||
}
|
||||
}
|
||||
@@ -1,97 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Core\ML;
|
||||
|
||||
/**
|
||||
* Класс синапса
|
||||
* является связующим звеном между нейронами
|
||||
*/
|
||||
class Synaps
|
||||
{
|
||||
/** @var int Идентификатор синапса */
|
||||
private $id;
|
||||
|
||||
/** @var float Вес */
|
||||
private $value;
|
||||
|
||||
/** @var Neuron Входной нейрон */
|
||||
private Neuron $inNeuron;
|
||||
|
||||
/** @var Neuron Выходной нейрон */
|
||||
private Neuron $outNeuron;
|
||||
|
||||
/**
|
||||
* Конструктор
|
||||
*
|
||||
* @param int $id Идентификатор синапса
|
||||
* @param Neuron $inNeuron Входной нейрон
|
||||
* @param Neuron $outNeuron Выходной нейрон
|
||||
* @param float|null $value Значение веса синапса
|
||||
*
|
||||
* @throws \Exception
|
||||
*/
|
||||
public function __construct(int $id, Neuron $inNeuron, Neuron $outNeuron, float $value = null)
|
||||
{
|
||||
$this->inNeuron = $inNeuron;
|
||||
$this->outNeuron = $outNeuron;
|
||||
|
||||
// если мы хотим явно задать вес - задаем, иначе генерируем как-нибудь
|
||||
if ($value !== null) {
|
||||
$this->value = $value;
|
||||
} else {
|
||||
$this->value = random_int(0, 100) / 100;
|
||||
}
|
||||
$this->id = $id;
|
||||
}
|
||||
|
||||
/** Получить id синапса */
|
||||
public function getId(): int
|
||||
{
|
||||
return $this->id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Получение входящего нейрона
|
||||
*
|
||||
* @return Neuron
|
||||
*/
|
||||
public function getInNeuron(): Neuron
|
||||
{
|
||||
return $this->inNeuron;
|
||||
}
|
||||
|
||||
/**
|
||||
* Получение выходящего нейрона
|
||||
*
|
||||
* @return Neuron
|
||||
*/
|
||||
public function getOutNeuron(): Neuron
|
||||
{
|
||||
return $this->outNeuron;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Получить вес
|
||||
*
|
||||
* @return float Вес
|
||||
*/
|
||||
public function getValue(): ?float
|
||||
{
|
||||
return $this->value;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Установить вес
|
||||
*
|
||||
* @param float $value Вес
|
||||
* @return $this
|
||||
*/
|
||||
public function setValue(float $value): self
|
||||
{
|
||||
$this->value = $value;
|
||||
return $this;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
-- Таблица versions --
|
||||
create table if not exists `d_migrations` (
|
||||
`id` int(10) unsigned not null auto_increment,
|
||||
`name` varchar(255) not null,
|
||||
`date_created` timestamp default current_timestamp,
|
||||
primary key (id)
|
||||
)
|
||||
engine = innodb
|
||||
auto_increment = 1
|
||||
character set utf8
|
||||
collate utf8_general_ci;
|
||||
@@ -1,96 +0,0 @@
|
||||
CREATE TABLE `d_users`
|
||||
(
|
||||
`id` int(11) NOT NULL,
|
||||
`login` varchar(100) NOT NULL,
|
||||
`password` varchar(100) NOT NULL,
|
||||
`name` varchar(150) NOT NULL,
|
||||
`email` text,
|
||||
`image_id` int(11) DEFAULT NULL,
|
||||
`token` text,
|
||||
`last_active` varchar(100) NOT NULL,
|
||||
`date_created` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
`date_updated` datetime DEFAULT NULL
|
||||
) ENGINE = innodb
|
||||
DEFAULT CHARSET = utf8;
|
||||
INSERT INTO `d_users` (`id`, `login`, `password`, `name`, `email`, `image_id`, `token`, `last_active`, `date_created`, `date_updated`)
|
||||
VALUES (1, 'admin', '7c607172d24d7237579acfdeffe373e2', 'Роман Гринько', 'rsgrinko@yandex.ru', 18, 'RG1819-1000-77EB-8F7A-9B112FB69D3A0',
|
||||
'1657051585', '2022-06-17 16:18:56', NULL),
|
||||
(2, 'demo', '7c607172d24d7237579acfdeffe373e2', 'Demo', 'demo@it-stories.ru', 20,
|
||||
'RG17DE-1000-26FC-837F-8F9C47E643970', '1655471459', '2022-06-17 16:18:56', NULL),
|
||||
(3, 'system', '', 'Система', 'info@it-stories.ru', NULL, 'RG17DE-1000-2702-816F-97E3877DD6650', '1651673702', '2022-06-17 16:18:56', NULL);
|
||||
ALTER TABLE `d_users` ADD PRIMARY KEY (`id`);
|
||||
ALTER TABLE `d_users` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT = 25;
|
||||
|
||||
|
||||
CREATE TABLE `roles` (
|
||||
`id` int(11) NOT NULL,
|
||||
`name` text,
|
||||
`description` text
|
||||
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
|
||||
|
||||
|
||||
INSERT INTO `roles` (`id`, `name`, `description`) VALUES
|
||||
(1, 'Админисистратор', 'Группа, имеющая доступ ко всему'),
|
||||
(2, 'Пользователи', 'Базовая группа для простых пользователей');
|
||||
|
||||
ALTER TABLE `roles` ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `id` (`id`);
|
||||
|
||||
|
||||
CREATE TABLE `user_roles` (
|
||||
`id` int(11) NOT NULL,
|
||||
`user_id` int(11) NOT NULL,
|
||||
`role_id` int(11) NOT NULL
|
||||
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
|
||||
INSERT INTO `user_roles` (`id`, `user_id`, `role_id`) VALUES (1, 1, 1);
|
||||
ALTER TABLE `user_roles` ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `id` (`id`);
|
||||
ALTER TABLE `user_roles` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;
|
||||
|
||||
|
||||
CREATE TABLE `threads` (
|
||||
`id` int(11) NOT NULL,
|
||||
`active` varchar(1) NOT NULL DEFAULT 'N',
|
||||
`in_progress` varchar(1) NOT NULL DEFAULT 'N',
|
||||
`executed` varchar(1) NOT NULL DEFAULT 'N',
|
||||
`execution_time` varchar(255) DEFAULT NULL,
|
||||
`attempts` int(11) NOT NULL,
|
||||
`date_created` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
`date_updated` datetime DEFAULT NULL,
|
||||
`class` varchar(255) DEFAULT NULL,
|
||||
`method` varchar(255) DEFAULT NULL,
|
||||
`params` text,
|
||||
`status` varchar(255) DEFAULT NULL,
|
||||
`response` text
|
||||
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
|
||||
ALTER TABLE `threads` ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `id` (`id`);
|
||||
ALTER TABLE `threads` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=17923;
|
||||
|
||||
|
||||
CREATE TABLE `threads_history` (
|
||||
`id` int(11) NOT NULL,
|
||||
`task_id` int(11) DEFAULT NULL,
|
||||
`execution_time` varchar(255) DEFAULT NULL,
|
||||
`attempts` int(11) NOT NULL,
|
||||
`date_created` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
`date_updated` datetime DEFAULT NULL,
|
||||
`class` varchar(255) DEFAULT NULL,
|
||||
`method` varchar(255) DEFAULT NULL,
|
||||
`params` text,
|
||||
`status` varchar(255) DEFAULT NULL,
|
||||
`response` text
|
||||
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
|
||||
ALTER TABLE `threads_history` ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `id` (`id`);
|
||||
ALTER TABLE `threads_history` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7946;
|
||||
|
||||
|
||||
CREATE TABLE `files` (
|
||||
`id` int(11) NOT NULL,
|
||||
`name` varchar(255) DEFAULT NULL,
|
||||
`path` text
|
||||
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
|
||||
ALTER TABLE `files` ADD PRIMARY KEY (`id`);
|
||||
ALTER TABLE `files` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=23;
|
||||
|
||||
COMMIT;
|
||||
|
||||
|
||||
|
||||
@@ -1,29 +0,0 @@
|
||||
CREATE TABLE if not exists `d_users`
|
||||
(
|
||||
`id` int(11) NOT NULL,
|
||||
`login` varchar(100) NOT NULL,
|
||||
`password` varchar(100) NOT NULL,
|
||||
`name` varchar(150) NOT NULL,
|
||||
`email` text,
|
||||
`image_id` int(11) DEFAULT NULL,
|
||||
`token` text,
|
||||
`last_active` varchar(100) NOT NULL,
|
||||
`date_created` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
`date_updated` datetime DEFAULT NULL
|
||||
) ENGINE = innodb
|
||||
DEFAULT CHARSET = utf8;
|
||||
|
||||
INSERT INTO `d_users` (`id`, `login`, `password`, `name`, `email`, `image_id`, `token`, `last_active`, `date_created`, `date_updated`)
|
||||
VALUES (1, 'admin', '7c607172d24d7237579acfdeffe373e2', 'Роман Гринько', 'rsgrinko@yandex.ru', 18, 'RG1819-1000-77EB-8F7A-9B112FB69D3A0',
|
||||
'1657051585', '2022-06-17 16:18:56', NULL),
|
||||
(2, 'demo', '7c607172d24d7237579acfdeffe373e2', 'Demo user', 'demo@it-stories.ru', 20,
|
||||
'RG17DE-1000-26FC-837F-8F9C47E643970', '1655471459', '2022-06-17 16:18:56', NULL),
|
||||
(3, 'system', '', 'Система', 'info@it-stories.ru', NULL, 'RG17DE-1000-2702-816F-97E3877DD6650', '1651673702', '2022-06-17 16:18:56', NULL);
|
||||
|
||||
ALTER TABLE `d_users`
|
||||
ADD PRIMARY KEY (`id`);
|
||||
|
||||
ALTER TABLE `d_users`
|
||||
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT,
|
||||
AUTO_INCREMENT = 25;
|
||||
COMMIT;
|
||||
@@ -1,12 +0,0 @@
|
||||
CREATE TABLE if not exists `d_roles` (
|
||||
`id` int(11) NOT NULL,
|
||||
`name` text,
|
||||
`description` text
|
||||
) ENGINE=innodb DEFAULT CHARSET=utf8;
|
||||
|
||||
|
||||
INSERT INTO `d_roles` (`id`, `name`, `description`) VALUES
|
||||
(1, 'Админисистратор', 'Группа, имеющая доступ ко всему'),
|
||||
(2, 'Пользователи', 'Базовая группа для простых пользователей'),
|
||||
|
||||
ALTER TABLE `d_roles` ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `id` (`id`);
|
||||
@@ -1,9 +0,0 @@
|
||||
CREATE TABLE if not exists `d_user_roles` (
|
||||
`id` int(11) NOT NULL,
|
||||
`user_id` int(11) NOT NULL,
|
||||
`role_id` int(11) NOT NULL
|
||||
) ENGINE=innodb DEFAULT CHARSET=utf8;
|
||||
|
||||
INSERT INTO `d_user_roles` (`id`, `user_id`, `role_id`) VALUES (1, 1, 1),
|
||||
ALTER TABLE `d_user_roles` ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `id` (`id`);
|
||||
ALTER TABLE `d_user_roles` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;
|
||||
@@ -1,7 +0,0 @@
|
||||
CREATE TABLE if not exists `d_files` (
|
||||
`id` int(11) NOT NULL,
|
||||
`name` varchar(255) DEFAULT NULL,
|
||||
`path` text
|
||||
) ENGINE=innodb DEFAULT CHARSET=utf8;
|
||||
ALTER TABLE `d_files` ADD PRIMARY KEY (`id`);
|
||||
ALTER TABLE `d_files` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=23;
|
||||
@@ -1,18 +0,0 @@
|
||||
CREATE TABLE `d_threads` (
|
||||
`id` int(11) NOT NULL,
|
||||
`active` varchar(1) NOT NULL DEFAULT 'N',
|
||||
`in_progress` varchar(1) NOT NULL DEFAULT 'N',
|
||||
`priority` int(11) DEFAULT NULL,
|
||||
`execution_time` varchar(255) DEFAULT NULL,
|
||||
`attempts` int(11) NOT NULL,
|
||||
`attempts_limit` int(11) DEFAULT '1',
|
||||
`date_created` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
`date_updated` datetime DEFAULT NULL,
|
||||
`class` varchar(255) DEFAULT NULL,
|
||||
`method` varchar(255) DEFAULT NULL,
|
||||
`params` text,
|
||||
`status` varchar(255) DEFAULT NULL,
|
||||
`response` text
|
||||
) ENGINE=innodb DEFAULT CHARSET=utf8;
|
||||
ALTER TABLE `d_threads` ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `id` (`id`);
|
||||
ALTER TABLE `d_threads` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=78989;
|
||||
@@ -1,15 +0,0 @@
|
||||
CREATE TABLE if not exists `d_threads_history` (
|
||||
`id` int(11) NOT NULL,
|
||||
`task_id` int(11) DEFAULT NULL,
|
||||
`execution_time` varchar(255) DEFAULT NULL,
|
||||
`attempts` int(11) NOT NULL,
|
||||
`date_created` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
`date_updated` datetime DEFAULT NULL,
|
||||
`class` varchar(255) DEFAULT NULL,
|
||||
`method` varchar(255) DEFAULT NULL,
|
||||
`params` text,
|
||||
`status` varchar(255) DEFAULT NULL,
|
||||
`response` text
|
||||
) ENGINE=innodb DEFAULT CHARSET=utf8;
|
||||
ALTER TABLE `d_threads_history` ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `id` (`id`);
|
||||
ALTER TABLE `d_threads_history` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7946;
|
||||
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
|
||||
return
|
||||
[
|
||||
'paths' => [
|
||||
'migrations' => '%%PHINX_CONFIG_DIR%%/db/migrations',
|
||||
'seeds' => '%%PHINX_CONFIG_DIR%%/db/seeds'
|
||||
],
|
||||
'environments' => [
|
||||
'default_migration_table' => 'd_phinxlog',
|
||||
'default_environment' => 'dev',
|
||||
'prod' => [
|
||||
'adapter' => 'mysql',
|
||||
'host' => 'localhost',
|
||||
'name' => 'rsgrinko_delta',
|
||||
'user' => 'rsgrinko_delta',
|
||||
'pass' => '2670135',
|
||||
'port' => '3306',
|
||||
'charset' => 'utf8',
|
||||
],
|
||||
'dev' => [
|
||||
'adapter' => 'mysql',
|
||||
'host' => 'it-stories.ru',
|
||||
'name' => 'rsgrinko_test',
|
||||
'user' => 'rsgrinko_test',
|
||||
'pass' => '2670135',
|
||||
'port' => '3306',
|
||||
'charset' => 'utf8',
|
||||
]
|
||||
],
|
||||
'version_order' => 'creation'
|
||||
];
|
||||
@@ -1,117 +0,0 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Copyright (c) 2022 Roman Grinko <rsgrinko@gmail.com>
|
||||
* Permission is hereby granted, free of charge, to any person obtaining
|
||||
* a copy of this software and associated documentation files (the
|
||||
* "Software"), to deal in the Software without restriction, including
|
||||
* without limitation the rights to use, copy, modify, merge, publish,
|
||||
* distribute, sublicense, and/or sell copies of the Software, and to
|
||||
* permit persons to whom the Software is furnished to do so, subject to
|
||||
* the following conditions:
|
||||
* The above copyright notice and this permission notice shall be included
|
||||
* in all copies or substantial portions of the Software.
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
||||
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
||||
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
|
||||
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
|
||||
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
|
||||
//$_SERVER['DOCUMENT_ROOT'] = '/home/rsgrinko/sites/dev.it-stories.ru';
|
||||
//require_once $_SERVER['DOCUMENT_ROOT'] . '/core/bootstrap.php';
|
||||
|
||||
class HostFunctions
|
||||
{
|
||||
public static $cmd = 'default';
|
||||
|
||||
public static function toOut($data, $status = 'success')
|
||||
{
|
||||
$result = [
|
||||
'status' => $status,
|
||||
'cmd' => self::$cmd,
|
||||
'time' => time(),
|
||||
'data' => $data,
|
||||
];
|
||||
header('Content-Type: application/json; charset=utf-8');
|
||||
echo json_encode($result, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
|
||||
}
|
||||
|
||||
public static function getHostInfo()
|
||||
{
|
||||
$result = [];
|
||||
$output = [];
|
||||
exec('free -h', $output, $code);
|
||||
$result['memory'] = implode(PHP_EOL, $output);
|
||||
|
||||
$output = [];
|
||||
exec('cat /proc/cpuinfo', $output, $code);
|
||||
$result['cpuinfo'] = implode(PHP_EOL, $output);
|
||||
|
||||
$output = [];
|
||||
exec('uname -a', $output, $code);
|
||||
$result['uname'] = implode(PHP_EOL, $output);
|
||||
|
||||
$output = [];
|
||||
exec('hostname', $output, $code);
|
||||
$result['hostname'] = implode(PHP_EOL, $output);
|
||||
|
||||
$output = [];
|
||||
exec('uptime', $output, $code);
|
||||
$result['uptime'] = implode(PHP_EOL, $output);
|
||||
|
||||
$result['ip'] = $_SERVER['SERVER_ADDR'];
|
||||
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
$commandList = [
|
||||
'ping',
|
||||
'getHostInfo',
|
||||
'getHostIp',
|
||||
'eval',
|
||||
];
|
||||
$command = $_REQUEST['cmd'] ?? 'default';
|
||||
HostFunctions::$cmd = $command;
|
||||
switch ($command) {
|
||||
case 'getCommands':
|
||||
HostFunctions::toOut($commandList);
|
||||
break;
|
||||
case 'ping':
|
||||
HostFunctions::toOut('pong');
|
||||
break;
|
||||
case 'getHostInfo':
|
||||
$result = HostFunctions::getHostInfo();
|
||||
HostFunctions::toOut($result);
|
||||
break;
|
||||
|
||||
case 'getHostIp':
|
||||
HostFunctions::toOut($_SERVER['SERVER_ADDR']);
|
||||
break;
|
||||
|
||||
case 'eval':
|
||||
$evalString = isset($_REQUEST['evalString']) ? base64_decode($_REQUEST['evalString']) : null;
|
||||
if ($evalString === null) {
|
||||
HostFunctions::toOut('No eval string', 'error');
|
||||
} else {
|
||||
ob_start();
|
||||
try {
|
||||
eval($evalString);
|
||||
$result = ob_get_clean();
|
||||
} catch (Throwable $t) {
|
||||
$result = 'Error on line ' . $t->getLine() . ': ' . $t->getMessage();
|
||||
ob_clean();
|
||||
}
|
||||
HostFunctions::toOut($result);
|
||||
}
|
||||
break;
|
||||
|
||||
default:
|
||||
HostFunctions::toOut('Command not found', 'error');
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -1,34 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use Core\ExternalServices\TelegramSender;
|
||||
|
||||
const USE_ROUTER = false;
|
||||
require_once $_SERVER['DOCUMENT_ROOT'] . '/core/bootstrap.php';
|
||||
|
||||
$deviceId = $_REQUEST['MachineName'] . '_' . $_REQUEST['UserName'];
|
||||
|
||||
$uploadPath = './uploads/screenshots/' . $deviceId;
|
||||
if (!file_exists($uploadPath)) {
|
||||
mkdir($uploadPath, 0777, true);
|
||||
}
|
||||
|
||||
$uploadfile = $uploadPath . '/' . date("YmdHis") . '_' . basename($_FILES['screenshot']['name']);
|
||||
move_uploaded_file($_FILES['screenshot']['tmp_name'], $uploadfile);
|
||||
|
||||
$clipboard = '---- пусто ----';
|
||||
if (!empty($_REQUEST['Clipboard'])) {
|
||||
$clipboard = iconv('utf-8//IGNORE', 'cp1252//IGNORE', $_REQUEST['Clipboard']);
|
||||
$clipboard = iconv('cp1251//IGNORE', 'utf-8//IGNORE', $clipboard);
|
||||
}
|
||||
|
||||
|
||||
(new TelegramSender(TELEGRAM_BOT_TOKEN))->setChat(TELEGRAM_NOTIFICATION_CHANNEL)->sendPhoto(
|
||||
$uploadfile,
|
||||
'<b>Дата:</b> ' . date('Y-m-d H_i:s') . PHP_EOL . '<b>Имя устройства:</b> ' . $deviceId . PHP_EOL . '<b>Буфер: </b>' . $clipboard
|
||||
);
|
||||
@unlink($uploadfile);
|
||||
echo 'ok';
|
||||
|
||||
//sendTelegram($_REQUEST['Clipboard']);
|
||||
@@ -1,255 +0,0 @@
|
||||
<?php
|
||||
use Core\Models\{User, DB};
|
||||
|
||||
const USE_ROUTER = false;
|
||||
$_SERVER['DOCUMENT_ROOT'] = '/home/rsgrinko/sites/dev.it-stories.ru';
|
||||
require_once $_SERVER['DOCUMENT_ROOT'] . '/core/bootstrap.php';
|
||||
|
||||
$DB = DB::getInstance();
|
||||
|
||||
use Workerman\Timer;
|
||||
use Workerman\Worker;
|
||||
|
||||
function replaceBBCode($text_post) {
|
||||
$str_search = array(
|
||||
"#\\\n#is",
|
||||
"#\[b\](.+?)\[\/b\]#is",
|
||||
"#\[i\](.+?)\[\/i\]#is",
|
||||
"#\[u\](.+?)\[\/u\]#is",
|
||||
"#\[code\](.+?)\[\/code\]#is",
|
||||
"#\[quote\](.+?)\[\/quote\]#is",
|
||||
"#\[url=(.+?)\](.+?)\[\/url\]#is",
|
||||
"#\[url\](.+?)\[\/url\]#is",
|
||||
"#\[img\](.+?)\[\/img\]#is",
|
||||
"#\[size=(.+?)\](.+?)\[\/size\]#is",
|
||||
"#\[color=(.+?)\](.+?)\[\/color\]#is",
|
||||
"#\[list\](.+?)\[\/list\]#is",
|
||||
"#\[listn](.+?)\[\/listn\]#is",
|
||||
"#\[\*\](.+?)\[\/\*\]#"
|
||||
);
|
||||
$str_replace = array(
|
||||
"<br />",
|
||||
"<b>\\1</b>",
|
||||
"<i>\\1</i>",
|
||||
"<span style='text-decoration:underline'>\\1</span>",
|
||||
"<code class='code'>\\1</code>",
|
||||
"<table width = '95%'><tr><td>Цитата</td></tr><tr><td class='quote'>\\1</td></tr></table>",
|
||||
"<a href='\\1'>\\2</a>",
|
||||
"<a href='\\1'>\\1</a>",
|
||||
"<img width='150px' src='\\1' alt = 'Изображение' />",
|
||||
"<span style='font-size:\\1%'>\\2</span>",
|
||||
"<span style='color:\\1'>\\2</span>",
|
||||
"<ul>\\1</ul>",
|
||||
"<ol>\\1</ol>",
|
||||
"<li>\\1</li>"
|
||||
);
|
||||
return preg_replace($str_search, $str_replace, $text_post);
|
||||
}
|
||||
|
||||
|
||||
|
||||
$connections = []; // сюда будем складывать все подключения
|
||||
|
||||
// Стартуем WebSocket-сервер на порту 27800
|
||||
$worker = new Worker('websocket://0.0.0.0:8282');
|
||||
|
||||
$worker->onWorkerStart = function($worker) use (&$connections)
|
||||
{
|
||||
$interval = 5; // пингуем каждые 5 секунд
|
||||
|
||||
|
||||
Timer::add($interval, function() use(&$connections) {
|
||||
foreach ($connections as $c) {
|
||||
// Если ответ от клиента не пришел 3 раза, то удаляем соединение из списка
|
||||
// и оповещаем всех участников об "отвалившемся" пользователе
|
||||
if ($c->pingWithoutResponseCount >= 3) {
|
||||
$messageData = [
|
||||
'action' => 'ConnectionLost',
|
||||
'userId' => $c->id,
|
||||
'userName' => $c->userName,
|
||||
'gender' => $c->gender,
|
||||
'userColor' => $c->userColor
|
||||
];
|
||||
$message = json_encode($messageData);
|
||||
|
||||
unset($connections[$c->id]);
|
||||
$c->destroy(); // уничтожаем соединение
|
||||
|
||||
// рассылаем оповещение
|
||||
foreach ($connections as $c) {
|
||||
$c->send($message);
|
||||
}
|
||||
} else {
|
||||
$c->send('{"action":"Ping"}');
|
||||
$c->pingWithoutResponseCount++; // увеличиваем счетчик пингов
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
Timer::add(10, function () use (&$connections) {
|
||||
$infoMessages = [
|
||||
'Случайное число: <b>' . random_int(1000, 9999). '</b>',
|
||||
'Чат разработан командой <a href=\'https://it-stories.ru/\' target=\'_blank\'>it-stories.ru</a> - проекта о веб разработке и программировании',
|
||||
'Это информационное сообщение для проверки работы чата',
|
||||
'Нужен сайт? Студия <a href=\'https://softline71.ru/\' target=\'_blank\'>SoftLine71</a> поможет вам!',
|
||||
];
|
||||
$randomKey = random_int(0, count($infoMessages) - 1);
|
||||
$randMessage = $infoMessages[$randomKey];
|
||||
|
||||
foreach ($connections as $c) {
|
||||
$c->send('{"action":"Information", "text": "' . $randMessage . '"}');
|
||||
$c->pingWithoutResponseCount++; // увеличиваем счетчик пингов
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
$worker->onConnect = function($connection) use(&$connections)
|
||||
{
|
||||
// Эта функция выполняется при подключении пользователя к WebSocket-серверу
|
||||
$connection->onWebSocketConnect = function($connection) use (&$connections)
|
||||
{
|
||||
// Достаём имя пользователя, если оно было указано
|
||||
if (isset($_GET['userName'])) {
|
||||
$originalUserName = preg_replace('/[^a-zA-Zа-яА-ЯёЁ0-9\-\_ ]/u', '', trim($_GET['userName']));
|
||||
}
|
||||
else {
|
||||
$originalUserName = 'Инкогнито';
|
||||
}
|
||||
|
||||
|
||||
// Добавляем соединение в список
|
||||
// + мы можем добавлять произвольные поля в $connection
|
||||
// и затем читать их из любой функции:
|
||||
$connection->userName = $originalUserName;
|
||||
$connection->pingWithoutResponseCount = 0; // счетчик безответных пингов
|
||||
|
||||
$connections[$connection->id] = $connection;
|
||||
|
||||
// Собираем список всех пользователей
|
||||
$users = [];
|
||||
foreach ($connections as $c) {
|
||||
// TcpConnection::id - уникальный идентификатор соединения,
|
||||
// присваивается автоматически. Будем использовать его как
|
||||
// идентификатор пользователя 'userId'.
|
||||
$users[] = [
|
||||
'userId' => $c->id,
|
||||
'userName' => $c->userName,
|
||||
];
|
||||
}
|
||||
|
||||
// Отправляем пользователю данные авторизации
|
||||
$messageData = [
|
||||
'action' => 'Authorized',
|
||||
'userId' => $connection->id,
|
||||
'userName' => $connection->userName,
|
||||
'users' => $users
|
||||
];
|
||||
//$connection->send(json_encode($messageData));
|
||||
foreach ($connections as $c) {
|
||||
$c->send(json_encode($messageData));
|
||||
}
|
||||
|
||||
// Оповещаем всех пользователей о новом участнике в чате
|
||||
$messageData = [
|
||||
'action' => 'Connected',
|
||||
'userId' => $connection->id,
|
||||
'userName' => $connection->userName,
|
||||
'gender' => $connection->gender,
|
||||
'userColor' => $connection->userColor
|
||||
];
|
||||
$message = json_encode($messageData);
|
||||
|
||||
foreach ($connections as $c) {
|
||||
$c->send($message);
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
$worker->onClose = function($connection) use(&$connections)
|
||||
{
|
||||
// Эта функция выполняется при закрытии соединения
|
||||
if (!isset($connections[$connection->id])) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Удаляем соединение из списка
|
||||
unset($connections[$connection->id]);
|
||||
|
||||
// Собираем список всех пользователей
|
||||
$users = [];
|
||||
foreach ($connections as $c) {
|
||||
// TcpConnection::id - уникальный идентификатор соединения,
|
||||
// присваивается автоматически. Будем использовать его как
|
||||
// идентификатор пользователя 'userId'.
|
||||
$users[] = [
|
||||
'userId' => $c->id,
|
||||
'userName' => $c->userName,
|
||||
];
|
||||
}
|
||||
|
||||
// Оповещаем всех пользователей о выходе участника из чата
|
||||
$messageData = [
|
||||
'action' => 'Disconnected',
|
||||
'userId' => $connection->id,
|
||||
'userName' => $connection->userName,
|
||||
'users' => $users,
|
||||
];
|
||||
$message = json_encode($messageData);
|
||||
|
||||
foreach ($connections as $c) {
|
||||
$c->send($message);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
$worker->onMessage = function($connection, $message) use (&$connections)
|
||||
{
|
||||
// распаковываем json
|
||||
$messageData = json_decode($message, true);
|
||||
// проверяем наличие ключа 'toUserId', который используется для отправки приватных сообщений
|
||||
$toUserId = isset($messageData['toUserId']) ? (int) $messageData['toUserId'] : 0;
|
||||
$action = isset($messageData['action']) ? $messageData['action'] : '';
|
||||
|
||||
if ($action == 'Pong') {
|
||||
// При получении сообщения "Pong", обнуляем счетчик пингов
|
||||
$connection->pingWithoutResponseCount = 0;
|
||||
} else {
|
||||
// Все остальные сообщения дополняем данными об отправителе
|
||||
$messageData['userId'] = $connection->id;
|
||||
$messageData['userName'] = $connection->userName;
|
||||
|
||||
// Преобразуем специальные символы в HTML-сущности в тексте сообщения
|
||||
$messageData['text'] = htmlspecialchars($messageData['text']);
|
||||
// Заменяем текст заключенный в фигурные скобки на жирный
|
||||
// (позже будет описано зачем и почему)
|
||||
//$messageData['text'] = preg_replace('/\{(.*)\}/u', '<b>\\1</b>', $messageData['text']);
|
||||
$messageData['text'] = replaceBBCode($messageData['text']);
|
||||
|
||||
|
||||
if ($toUserId == 0) {
|
||||
// Отправляем сообщение всем пользователям
|
||||
$messageData['action'] = 'PublicMessage';
|
||||
foreach ($connections as $c) {
|
||||
$c->send(json_encode($messageData));
|
||||
}
|
||||
}
|
||||
else {
|
||||
$messageData['action'] = 'PrivateMessage';
|
||||
if (isset($connections[$toUserId])) {
|
||||
// Отправляем приватное сообщение указанному пользователю
|
||||
$connections[$toUserId]->send(json_encode($messageData));
|
||||
// и отправителю
|
||||
$connections->send(json_encode($messageData));
|
||||
}
|
||||
else {
|
||||
$messageData['text'] = 'Не удалось отправить сообщение выбранному пользователю';
|
||||
$connection->send(json_encode($messageData));
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
Worker::runAll();
|
||||
@@ -1,20 +0,0 @@
|
||||
<?php
|
||||
|
||||
use Core\Models\{DB};
|
||||
|
||||
const USE_ROUTER = false;
|
||||
require_once $_SERVER['DOCUMENT_ROOT'] . '/core/bootstrap.php';
|
||||
// ID статьи
|
||||
$post_id = 123;
|
||||
|
||||
$DB = DB::getInstance();
|
||||
/** @var DB $DB */
|
||||
$res = $DB->query('SELECT * FROM `visits` WHERE `page_id` = ' . $post_id . ' AND `date` = CURDATE()');
|
||||
|
||||
if ($res === null) {
|
||||
echo 'insert';
|
||||
$res = $DB->query('INSERT INTO `visits` SET `page_id` = ' . $post_id . ', `counter` = 1, `date` = CURDATE()');
|
||||
} else {
|
||||
echo 'update';
|
||||
$res = $DB->query('UPDATE `visits` SET `counter` = `counter` + 1 WHERE `id` = ' . $res[0]['id']);
|
||||
}
|
||||
Reference in new issue
Block a user