diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml
index 53bf127..34d8ff2 100644
--- a/.gitlab-ci.yml
+++ b/.gitlab-ci.yml
@@ -14,7 +14,7 @@ build-job: # This job runs in the build stage, which runs first.
- composer install
- echo "Compile complete."
- echo "Running Unit-tests..."
- - ./vendor/bin/phpunit tests
+ - ./vendor/bin/phpunit --testdox tests
unit-test-job: # This job runs in the test stage.
stage: test # It only starts when the job in the build stage completes successfully.
diff --git a/core/config.php b/core/config.php
index 18cd0ae..6b27fd4 100644
--- a/core/config.php
+++ b/core/config.php
@@ -77,7 +77,7 @@
/**
* Параметры SQL базы
*/
- const DB_HOST = 'localhost';
+ const DB_HOST = 'dev.it-stories.ru';//'localhost';
const DB_USER = 'rsgrinko_delta';
const DB_PASSWORD = '2670135';
const DB_NAME = 'rsgrinko_delta';
diff --git a/core/lib/Core/ExternalServices/ChatGPT.class.php b/core/lib/Core/ExternalServices/ChatGPT.class.php
new file mode 100644
index 0000000..28096f3
--- /dev/null
+++ b/core/lib/Core/ExternalServices/ChatGPT.class.php
@@ -0,0 +1,59 @@
+token = $token;
+ }
+
+ public function ask(string $question, $context = [])
+ {
+ $url = 'https://api.openai.com/v1/chat/completions';
+
+ $headers = [
+ 'Authorization: Bearer ' .$this->token,
+ //"OpenAI-Organization: YOUR-Organization-ID",
+ 'Content-Type: application/json',
+ ];
+
+ // Define messages
+ $messages = [];
+ $messages[] = ['role' => 'user', 'content' => $question];
+ $messages = array_merge($context, $messages);
+
+
+
+ $data = [
+ 'model' => 'gpt-3.5-turbo',
+ 'messages' => $messages,
+ 'max_tokens' => 1600,
+ 'temperature' => 0.5,
+ ];
+
+ // init curl
+ $curl = curl_init(self::BASE_URL);
+ curl_setopt($curl, CURLOPT_POST, 1);
+ curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
+ curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
+ curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);//
+ curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);//
+ curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
+
+ $result = curl_exec($curl);
+ $error = curl_errno($curl);
+ curl_close($curl);
+
+ if ($error) {
+ return 'Error:' . $error;
+ }
+
+ return json_decode($result,true);
+ }
+ }
\ No newline at end of file
diff --git a/core/lib/Core/ExternalServices/Telegram2.class.php b/core/lib/Core/ExternalServices/Telegram2.class.php
index 140a7ea..b879c27 100644
--- a/core/lib/Core/ExternalServices/Telegram2.class.php
+++ b/core/lib/Core/ExternalServices/Telegram2.class.php
@@ -345,6 +345,7 @@
} else {
$this->eventType = null;
}
+ $this->setChat($this->eventChatId);
}
return $this;
}
@@ -360,6 +361,7 @@
}
+
/**
* Получение конкретного типа
*
@@ -370,6 +372,16 @@
return $this->messageType;
}
+ /**
+ * Получение сообщения, полученного от пользователя
+ *
+ * @return string|null
+ */
+ public function getMessage(): ?string
+ {
+ return $this->event['message'];
+ }
+
/**
* Получить собранные данные по текущему событию
*
diff --git a/core/lib/Core/ExternalServices/TelegramActions.class.php b/core/lib/Core/ExternalServices/TelegramActions.class.php
index fb85cc7..19ec93c 100644
--- a/core/lib/Core/ExternalServices/TelegramActions.class.php
+++ b/core/lib/Core/ExternalServices/TelegramActions.class.php
@@ -231,15 +231,18 @@
*/
public static function __callStatic(string $name, ?array $arguments): void
{
- $message = 'Команда ' . self::$cmd . ' не найдена.' . PHP_EOL;
+ /*$message = 'Команда ' . self::$cmd . ' не найдена.' . PHP_EOL;
if (!empty($arguments)) {
$message .= 'Аргументы: ' . implode(', ', $arguments) . PHP_EOL;
}
if (self::getEventType() !== 'callback') {
$message .= '' . print_r(self::$data, true) . '';
- }
+ }*/
+ //ChatGPT connect...
+ $gptObject = new ChatGPT();
Telegram::sendChatAction(self::getChatId()); // печатает...
- Telegram::execute(self::getChatId(), $message, '', self::getInlineKeyboard(), self::getKeyboard());
+ //Telegram::execute(self::getChatId(), $message, '', self::getInlineKeyboard(), self::getKeyboard());
+ Telegram::execute(self::getChatId(), htmlspecialchars($gptObject->ask($name)), '', self::getInlineKeyboard(), self::getKeyboard());
}
/**
@@ -390,222 +393,4 @@
self::getKeyboard()
);
}
-
- /**
- * Команда /online
- *
- * @return void
- */
- public static function commandOnline(): void
- {
- Online::removeInactive();
- $result = Online::getOnline();
- $message = 'Посетители онлайн (' . count($result) . ')' . PHP_EOL;
-
- foreach ($result as $key => $item) {
- $message .= '✔ Пользователь #' . ($key + 1) . ' ' . PHP_EOL . 'IP: ' . $item['ip'] . PHP_EOL . 'Страница: '
- . $item['page'] . '' . PHP_EOL . 'Referer: ' . (!empty(
- trim(
- $item['referer']
- )
- ) ? SystemFunctions::getBaseUrl($item['referer']) : 'нет') . '' . PHP_EOL . 'Бот: ' . (SystemFunctions::isSearchBot(
- $item['useragent']
- ) ?? 'нет') . PHP_EOL . 'Последняя активность: ' . SystemFunctions::secToString(time() - (int)$item['last_active'])
- . PHP_EOL . 'Геозона: ' . SystemFunctions::gluingLocationToString(
- ['country' => $item['country'], 'region' => $item['region'], 'city' => $item['city']]
- ) . PHP_EOL . PHP_EOL;
- }
- Telegram::sendChatAction(self::getChatId()); // печатает...
- Telegram::execute(self::getChatId(), $message, '', self::getInlineKeyboard(), self::getKeyboard());
- }
-
- /**
- * Команда /fail2ban
- *
- * @return void
- */
- public static function commandFail2ban(): void
- {
- $result = Fail2ban::getBlockedIpList('10', 'last_active', 'DESC');
- $message = 'Список заблокированных IP (' . Fail2ban::getBlockedIpCount() . ' из ' . Fail2ban::getAllIpCount() . ')' . PHP_EOL;
-
- foreach ($result as $key => $item) {
- $message .= '🚩 ' . $item['ip'] . ' ' . PHP_EOL . 'Попыток: ' . $item['attempts'] . PHP_EOL . 'Активность: '
- . SystemFunctions::secToString(time() - $item['last_active']) . PHP_EOL . 'Геозона: '
- . SystemFunctions::gluingLocationToString(
- ['country' => $item['country'], 'region' => $item['region'], 'city' => $item['city']]
- ) . PHP_EOL . PHP_EOL;
- }
- Telegram::sendChatAction(self::getChatId()); // печатает...
- Telegram::execute(self::getChatId(), $message, '', self::getInlineKeyboard(), self::getKeyboard());
- }
-
- /**
- * Команда /deploy
- *
- * @return void
- */
- public static function commandDeploy(): void
- {
- SystemFunctions::deploymentFromGit();
- Telegram::sendChatAction(self::getChatId()); // печатает...
- Telegram::execute(self::getChatId(), 'Произведен деплоймент из ветки master', '', self::getInlineKeyboard(), self::getKeyboard());
- }
-
-
- /**
- * Команда /stat
- *
- * @return void
- */
- public static function commandStat(): void
- {
- self::setInlineKeyboard(
- [
- [
- ['text' => 'Очистка кэша', 'callback_data' => self::getPreparedCallbackData('clearcache')],
- ['text' => 'Сброс Opcache', 'callback_data' => self::getPreparedCallbackData('clearopcache')],
- ],
- ]
- );
-
- $countCacheElements = \FCCache::getCountElements();
- $cacheSize = \FCCache::getCacheSize();
- $usersOnline = Online::getOnlineCount();
- $countBlockedIp = Fail2ban::getBlockedIpCount();
- $countAllIp = Fail2ban::getAllIpCount();
- $arOpcache = opcache_get_status();
-
- $message = '📱 Статистика по проекту' . PHP_EOL . 'В кэше: ' . $countCacheElements . ' ' . SystemFunctions::numWord(
- $countCacheElements,
- ['элемент', 'элемента', 'элементов']
- ) . PHP_EOL . 'Размер кэша: ' . SystemFunctions::convertBytes($cacheSize) . PHP_EOL . 'В Opcache: '
- . $arOpcache['opcache_statistics']['num_cached_scripts'] . ' ' . SystemFunctions::numWord(
- $arOpcache['opcache_statistics']['num_cached_scripts'],
- ['элемент', 'элемента', 'элементов']
- ) . PHP_EOL . 'Opcache (используется): ' . SystemFunctions::convertBytes($arOpcache['memory_usage']['used_memory']) . PHP_EOL
- . 'Opcache (свободно): ' . SystemFunctions::convertBytes($arOpcache['memory_usage']['free_memory']) . PHP_EOL
- . 'Opcache (битая): ' . SystemFunctions::convertBytes($arOpcache['memory_usage']['wasted_memory']) . PHP_EOL
- . 'Opcache (всего): 512Mb' . PHP_EOL . 'Онлайн на сайте: ' . $usersOnline . ' ' . SystemFunctions::numWord(
- $usersOnline,
- ['посетитель', 'посетителя', 'посетителей']
- ) . PHP_EOL . 'Заблокировано: ' . $countBlockedIp . ' ' . SystemFunctions::numWord(
- $countBlockedIp,
- ['адрес', 'адреса', 'адресов']
- ) . ' из ' . $countAllIp;
- Telegram::sendChatAction(self::getChatId()); // печатает...
- Telegram::execute(self::getChatId(), $message, '', self::getInlineKeyboard(), self::getKeyboard());
- }
-
- /**
- * Команда /yastat
- *
- * @return void
- */
- public static function commandYaStat(): void
- {
- $objectYandex = new Yandex(
- YANDEX_APP_ID, YANDEX_APP_SECRET, YANDEX_REDIRECT_URL
- );
- $objectYandex->loadConfig()->refreshToken();
- $objectYandex->save();
-
-
- $query = [
- 'oauth_token' => $objectYandex->getAccessToken(),
- 'dimension_field' => 'date|day',
- 'period' => 'thisyear',
- 'entity_field' => 'page_level',
- 'field' => 'partner_wo_nds',
- 'lang' => 'ru',
- 'pretty' => '0',
-
- ];
-
- $result = $objectYandex->request(
- 'partner2.yandex.ru',
- 'api/statistics2/get.json',
- $query
- );
-
-
- $day_price = [];
- foreach ($result['data']['points'] as $k => $item) {
- $day = date("d") - 1;
- if ($day == 0) {
- $day = 1;
- } elseif ($day < 9) {
- $day = '0' . $day;
- }
- if ($item['dimensions']['date'][0] == date("Y-m-") . $day) {
- $day_price['yesterday'] = $item['measures'][0]['partner_wo_nds'];
- }
-
- if ($item['dimensions']['date'][0] == date("Y-m-d")) {
- $day_price['today'] = $item['measures'][0]['partner_wo_nds'];
- }
- }
- $day_price['today'] = $day_price['today'] ?? '0';
- $day_price['yesterday'] = $day_price['yesterday'] ?? '0';
-
- $message = 'Статистика РСЯ' . PHP_EOL . 'Доход за сегодня: ' . $day_price['today'] . ' р.' . PHP_EOL . 'Доход за вчера: '
- . $day_price['yesterday'] . ' р.' . PHP_EOL . 'Курс доллара: ' . SystemFunctions::getExchangeRates('USD', 2) . ' р.';
- Telegram::sendChatAction(self::getChatId()); // печатает...
- Telegram::execute(self::getChatId(), $message, '', self::getInlineKeyboard(), self::getKeyboard());
- }
-
- /**
- * Команда /getcam
- *
- * @return void
- */
- public static function commandGetCam(): void
- {
- $image = SystemFunctions::getCamScreen();
- Telegram::sendChatAction(self::getChatId()); // печатает...
- Telegram::execute(
- self::getChatId(),
- 'Снимок сделан ' . date('d.m.Y H:i:s', strtotime('+3 hours')),
- $image,
- self::getInlineKeyboard(),
- self::getKeyboard()
- );
- }
-
- /**
- * Команда /clearcache
- *
- * @return void
- */
- public static function commandClearCache(): void
- {
- opcache_reset();
- $cacheSize = SystemFunctions::convertBytes(\FCCache::getCacheSize());
- \FCCache::clearCache();
- Telegram::sendChatAction(self::getChatId()); // печатает...
- Telegram::execute(self::getChatId(), 'Кэш очищен. Удалено ' . $cacheSize, '', self::getInlineKeyboard(), self::getKeyboard());
- }
-
- /**
- * Callback очистка кэша
- *
- * @return void
- */
- public static function callbackClearcache(): void
- {
- $cacheSize = SystemFunctions::convertBytes(\FCCache::getCacheSize());
- \FCCache::clearCache();
- Telegram::answerCallbackQuery(self::getEventData()['callback_id'], 'Файловый кэш очищен. Удалено ' . $cacheSize, true);
- }
-
- /**
- * Callback очистка Opcache
- *
- * @return void
- */
- public static function callbackClearOpcache(): void
- {
- opcache_reset();
- Telegram::answerCallbackQuery(self::getEventData()['callback_id'], 'Opcache очищен.', false);
- }
}
\ No newline at end of file
diff --git a/core/lib/Core/ML/NeuroNetwork.class.php b/core/lib/Core/ML/NeuroNetwork.class.php
new file mode 100644
index 0000000..ce66e6a
--- /dev/null
+++ b/core/lib/Core/ML/NeuroNetwork.class.php
@@ -0,0 +1,209 @@
+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())
+ );
+ }
+ }
\ No newline at end of file
diff --git a/core/lib/Core/ML/Neuron.class.php b/core/lib/Core/ML/Neuron.class.php
new file mode 100644
index 0000000..578e5dd
--- /dev/null
+++ b/core/lib/Core/ML/Neuron.class.php
@@ -0,0 +1,39 @@
+id = $id;
+ }
+
+ /** Получить текущее значение */
+ public function getValue(): ?float
+ {
+ return $this->value;
+ }
+
+ /** Задать текущее значение */
+ public function setValue(float $value): self
+ {
+ $this->value = $value;
+ return $this;
+ }
+ }
diff --git a/core/lib/Core/ML/Synaps.class.php b/core/lib/Core/ML/Synaps.class.php
new file mode 100644
index 0000000..d8f902f
--- /dev/null
+++ b/core/lib/Core/ML/Synaps.class.php
@@ -0,0 +1,97 @@
+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;
+ }
+
+ }
diff --git a/telegramHandler.php b/telegramHandler.php
index 75a24ec..ad63a08 100644
--- a/telegramHandler.php
+++ b/telegramHandler.php
@@ -2,12 +2,13 @@
use Core\CoreException;
use Core\ExternalServices\Telegram2;
+ use Core\ExternalServices\ChatGPT;
require_once __DIR__ . '/core/bootstrap.php';
$data = file_get_contents('php://input');
if(empty($data)) {
- die('Данные не получены');
+ //die('Данные не получены');
}
$data = json_decode($data, true);
@@ -15,7 +16,10 @@
$tg = new Telegram2(TELEGRAM_BOT_TOKEN);
$tg->setRemoteRequest($data);
+ $gptObject = new ChatGPT();
+
+ $response = $gptObject->ask($tg->getMessage())['choices'][0]['message']['content'];
+ $response = htmlspecialchars($response);
+ $tg->sendMessage($response);
//$res = $tg->setChat(TELEGRAM_ADMIN_CHAT_ID)->updateMessage(121, '');
-
- //sendTelegram(print_r($data, true));
\ No newline at end of file
diff --git a/tests/UserTest.php b/tests/UserTest.php
index 828967f..60e637a 100644
--- a/tests/UserTest.php
+++ b/tests/UserTest.php
@@ -9,12 +9,7 @@
{
public function testGetAllUserData(): void
{
- $testClassMock = $this->getMockBuilder(TestClass::class)->setMethodsExcept(['getAllUserData'])->getMock();
- //->getMockBuilder(TestClass::class)
- //->setConstructorArgs([1])
- //->getMock();
-
- $this->assertTrue(method_exists($testClassMock, 'getAllUserData'), TestClass::class . '\getAllUserData() - метод не найден');
+ $this->assertTrue(0, 'Сообщение об ошибке');
}
}
\ No newline at end of file