тестовые введения

This commit is contained in:
rsgrinko committed 2022-07-12 23:55:51 +03:00
1 parent b177fbf5c1
commit 69ce4ef26f
9 files changed
+649 -91

No files matched your search

+64
View File
@@ -172,4 +172,68 @@
<!-- end table --> <!-- end table -->
</div><!-- contentpanel --> </div><!-- contentpanel -->
<!-- table -->
<div class="row">
<div class="col-md-12">
<div class="panel panel-primary">
<div class="panel-heading">
<h4 class="panel-title">Выполненные задания</h4>
<p>Список заверщившихся заданий</p>
</div><!-- panel-heading -->
<div class="table-responsive">
<table class="table table-primary mb30">
<thead>
<tr>
<th>ID</th>
<th>ID задания</th>
<th>Время выполнения</th>
<th>Попыток</th>
<th>Класс</th>
<th>Метод</th>
<th>Параметры</th>
<th>Статус</th>
<th>Результат</th>
<th>Создан</th>
<th>Обновлен</th>
</tr>
</thead>
<tbody>
<?php
$arTasks = $MQ->getTasksHistory(10, 'id', 'desc');
foreach($arTasks as $task) {
?>
<tr class="<?php
if($task['status'] === MQ::STATUS_OK) {
echo 'alert-success';
} elseif($task['status'] === MQ::STATUS_ERROR) {
echo 'alert-danger';
}
?>">
<td><?=$task['id'];?></td>
<td><?=$task['task_id'];?></td>
<td><?=$task['execution_time'];?></td>
<td><?=$task['attempts'];?></td>
<td><?=$task['class'];?></td>
<td><?=$task['method'];?></td>
<td><?=$task['params'];?></td>
<td><?=$task['status'];?></td>
<td><?=$task['response'];?></td>
<td><?=$task['date_created'];?></td>
<td><?=$task['date_updated'];?></td>
</tr>
<?php
}
?>
</tbody>
</table>
</div><!-- table-responsive -->
</div>
</div>
<!-- end table -->
</div><!-- contentpanel -->
<?php require_once __DIR__ . '/inc/footer.php'; ?> <?php require_once __DIR__ . '/inc/footer.php'; ?>
+2 -2
View File
@@ -56,7 +56,7 @@
/** /**
* Использование кэша * Использование кэша
*/ */
const USE_CACHE = false; const USE_CACHE = true;
/** /**
* Папка кэша * Папка кэша
@@ -76,5 +76,5 @@
/** /**
* Флаг использования логирования * Флаг использования логирования
*/ */
const USE_LOG = true; const USE_LOG = false;
+21
View File
@@ -1,6 +1,8 @@
<?php <?php
@ignore_user_abort(true); @ignore_user_abort(true);
set_time_limit(0); set_time_limit(0);
use Core\Helpers\Cache;
use Core\Models\MQ;
if (empty($_SERVER['DOCUMENT_ROOT'])) { if (empty($_SERVER['DOCUMENT_ROOT'])) {
$_SERVER['DOCUMENT_ROOT'] = __DIR__ . '/..'; $_SERVER['DOCUMENT_ROOT'] = __DIR__ . '/..';
@@ -9,3 +11,22 @@
// Запускаем воркер диспетчера очереди // Запускаем воркер диспетчера очереди
exec('(php -f ' . __DIR__ . '/runtime/threadsWorker.php & ) >> /dev/null 2>&1'); exec('(php -f ' . __DIR__ . '/runtime/threadsWorker.php & ) >> /dev/null 2>&1');
// Каждые 10 минут добавляем в очередь задание на проверку новостей слободы и отправку в телегу
$cacheId = md5('cron_myslo');
$runMyslo = false;
if(Cache::check($cacheId) && $cronMyslo = Cache::get($cacheId)) {
if((time() - (int)$cronMyslo) > 600) {
$runMyslo = true;
Cache::set($cacheId, time());
}
}
if($runMyslo === true) {
$result = (new MQ())->setAttempts(3)
->setPriority(3)
->setCheckDuplicates(true)
->createTask('Core\MQTasks', 'getMySLO');
}
@@ -1,6 +1,7 @@
<?php <?php
/** /**
* Класс для работы с API телеграмм (не-статический) * Класс для работы с API телеграмм (не-статический)
*
* @version 2.6.1 * @version 2.6.1
* @author Roman Grinko <rsgrinko@gmail.com> * @author Roman Grinko <rsgrinko@gmail.com>
* @package ITS * @package ITS
@@ -47,6 +48,7 @@
* Установка метода * Установка метода
* *
* @param string $method Метод * @param string $method Метод
*
* @return $this * @return $this
*/ */
private function setMethod(string $method): self private function setMethod(string $method): self
@@ -55,10 +57,32 @@
return $this; return $this;
} }
/**
* Санитизация текста
*
* @param string|null $text Текст
* @param bool $isCaption Является ли текст описанием изображения
*
* @return string|null
*/
private function sanitize(?string $text, bool $isCaption = false): ?string
{
if (empty($text)) {
return null;
}
$text = strip_tags($text, '<b><a><strong><i><em><u><ins><s><strike><del><s><code><pre>');
$text = substr(trim($text), 0, $isCaption ? 1024 : 4096);
$text = mb_convert_encoding($text, 'UTF-8', 'UTF-8');
return $text;
}
/** /**
* Установка идентификатора чата * Установка идентификатора чата
* *
* @param int $chatId Метод * @param int $chatId Метод
*
* @return $this * @return $this
*/ */
public function setChat(int $chatId): self public function setChat(int $chatId): self
@@ -91,15 +115,20 @@
* Отправка изображения * Отправка изображения
* *
* @param string $imagePath Путь до изображения * @param string $imagePath Путь до изображения
* @param string|null $caption Подпись
* *
* @return array * @return array
*/ */
public function sendPhoto(string $imagePath): array public function sendPhoto(string $imagePath, ?string $caption = null): array
{ {
$response = [ $response = [
'chat_id' => $this->chatId, 'chat_id' => $this->chatId,
'photo' => curl_file_create($imagePath), 'photo' => curl_file_create($imagePath),
'parse_mode' => 'html',
]; ];
if (!empty($caption)) {
$response['caption'] = $this->sanitize($caption, true);
}
return $this->setMethod('sendPhoto')->sendRequest($response); return $this->setMethod('sendPhoto')->sendRequest($response);
} }
@@ -148,13 +177,10 @@
*/ */
public function sendMessage(?string $text): array public function sendMessage(?string $text): array
{ {
$text = substr(trim($text), 0, 4096);
$text = strip_tags($text, '<b><a><strong><i><em><u><ins><s><strike><del><s><code><pre>');
$text = mb_convert_encoding($text, 'UTF-8', 'UTF-8');
$params = [ $params = [
'chat_id' => $this->chatId, 'chat_id' => $this->chatId,
'parse_mode' => 'html', 'parse_mode' => 'html',
'text' => $text 'text' => $this->sanitize($text),
]; ];
return $this->setMethod('sendMessage')->sendRequest($params); return $this->setMethod('sendMessage')->sendRequest($params);
+271 -48
View File
@@ -18,7 +18,7 @@
$keys = [ $keys = [
'HTTP_CLIENT_IP', 'HTTP_CLIENT_IP',
'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED_FOR',
'REMOTE_ADDR' 'REMOTE_ADDR',
]; ];
foreach ($keys as $key) { foreach ($keys as $key) {
if (!empty($_SERVER[$key])) { if (!empty($_SERVER[$key])) {
@@ -35,6 +35,7 @@
* Преобразование байт в человеческий вид * Преобразование байт в человеческий вид
* *
* @param int $size Размер в байтах * @param int $size Размер в байтах
*
* @return string * @return string
*/ */
public static function convertBytes(int $size): string public static function convertBytes(int $size): string
@@ -128,21 +129,88 @@
$number = ($number > 0) ? $number : 1; $number = ($number > 0) ? $number : 1;
$arChars = [ $arChars = [
'a', 'b', 'c', 'd', 'e', 'f', 'a',
'g', 'h', 'i', 'j', 'k', 'l', 'b',
'm', 'n', 'o', 'p', 'r', 's', 'c',
't', 'u', 'v', 'x', 'y', 'z', 'd',
'A', 'B', 'C', 'D', 'E', 'F', 'e',
'G', 'H', 'I', 'J', 'K', 'L', 'f',
'M', 'N', 'O', 'P', 'R', 'S', 'g',
'T', 'U', 'V', 'X', 'Y', 'Z', 'h',
'1', '2', '3', '4', '5', '6', 'i',
'7', '8', '9', '0']; 'j',
'k',
'l',
'm',
'n',
'o',
'p',
'r',
's',
't',
'u',
'v',
'x',
'y',
'z',
'A',
'B',
'C',
'D',
'E',
'F',
'G',
'H',
'I',
'J',
'K',
'L',
'M',
'N',
'O',
'P',
'R',
'S',
'T',
'U',
'V',
'X',
'Y',
'Z',
'1',
'2',
'3',
'4',
'5',
'6',
'7',
'8',
'9',
'0',
];
$arSpecialChars = [ $arSpecialChars = [
'(', ')', '[', ']', '!', '?', '(',
'&', '^', '%', '@', '*', '$', ')',
'<', '>', '/', '|', '+', '-', '[',
'{', '}', '~']; ']',
'!',
'?',
'&',
'^',
'%',
'@',
'*',
'$',
'<',
'>',
'/',
'|',
'+',
'-',
'{',
'}',
'~',
];
if ($useSpecialChars) { if ($useSpecialChars) {
$arChars = array_merge($arChars, $arSpecialChars); $arChars = array_merge($arChars, $arSpecialChars);
@@ -172,26 +240,95 @@
$bots = [ $bots = [
// Yandex // Yandex
'YandexBot', 'YandexAccessibilityBot', 'YandexMobileBot', 'YandexDirectDyn', 'YandexScreenshotBot', 'YandexBot',
'YandexImages', 'YandexVideo', 'YandexVideoParser', 'YandexMedia', 'YandexBlogs', 'YandexFavicons', 'YandexAccessibilityBot',
'YandexWebmaster', 'YandexPagechecker', 'YandexImageResizer', 'YandexAdNet', 'YandexDirect', 'YandexMobileBot',
'YaDirectFetcher', 'YandexCalendar', 'YandexSitelinks', 'YandexMetrika', 'YandexNews', 'YandexDirectDyn',
'YandexNewslinks', 'YandexCatalog', 'YandexAntivirus', 'YandexMarket', 'YandexVertis', 'YandexScreenshotBot',
'YandexForDomain', 'YandexSpravBot', 'YandexSearchShop', 'YandexMedianaBot', 'YandexOntoDB', 'YandexImages',
'YandexOntoDBAPI', 'YandexTurbo', 'YandexVerticals', 'YandexVideo',
'YandexVideoParser',
'YandexMedia',
'YandexBlogs',
'YandexFavicons',
'YandexWebmaster',
'YandexPagechecker',
'YandexImageResizer',
'YandexAdNet',
'YandexDirect',
'YaDirectFetcher',
'YandexCalendar',
'YandexSitelinks',
'YandexMetrika',
'YandexNews',
'YandexNewslinks',
'YandexCatalog',
'YandexAntivirus',
'YandexMarket',
'YandexVertis',
'YandexForDomain',
'YandexSpravBot',
'YandexSearchShop',
'YandexMedianaBot',
'YandexOntoDB',
'YandexOntoDBAPI',
'YandexTurbo',
'YandexVerticals',
// Google // Google
'Googlebot', 'Googlebot-Image', 'Mediapartners-Google', 'AdsBot-Google', 'APIs-Google', 'Googlebot',
'AdsBot-Google-Mobile', 'AdsBot-Google-Mobile', 'Googlebot-News', 'Googlebot-Video', 'Googlebot-Image',
'Mediapartners-Google',
'AdsBot-Google',
'APIs-Google',
'AdsBot-Google-Mobile',
'AdsBot-Google-Mobile',
'Googlebot-News',
'Googlebot-Video',
'AdsBot-Google-Mobile-Apps', 'AdsBot-Google-Mobile-Apps',
// Other // Other
'Mail.RU_Bot', 'bingbot', 'Accoona', 'ia_archiver', 'Ask Jeeves', 'OmniExplorer_Bot', 'W3C_Validator', 'Mail.RU_Bot',
'WebAlta', 'YahooFeedSeeker', 'Yahoo!', 'Ezooms', 'Tourlentabot', 'MJ12bot', 'AhrefsBot', 'bingbot',
'SearchBot', 'SiteStatus', 'Nigma.ru', 'Baiduspider', 'Statsbot', 'SISTRIX', 'AcoonBot', 'findlinks', 'Accoona',
'proximic', 'OpenindexSpider', 'statdom.ru', 'Exabot', 'Spider', 'SeznamBot', 'oBot', 'C-T bot', 'ia_archiver',
'Updownerbot', 'Snoopy', 'heritrix', 'Yeti', 'DomainVader', 'DCPbot', 'PaperLiBot', 'StackRambler', 'Ask Jeeves',
'msnbot', 'msnbot-media', 'msnbot-news', 'OmniExplorer_Bot',
'W3C_Validator',
'WebAlta',
'YahooFeedSeeker',
'Yahoo!',
'Ezooms',
'Tourlentabot',
'MJ12bot',
'AhrefsBot',
'SearchBot',
'SiteStatus',
'Nigma.ru',
'Baiduspider',
'Statsbot',
'SISTRIX',
'AcoonBot',
'findlinks',
'proximic',
'OpenindexSpider',
'statdom.ru',
'Exabot',
'Spider',
'SeznamBot',
'oBot',
'C-T bot',
'Updownerbot',
'Snoopy',
'heritrix',
'Yeti',
'DomainVader',
'DCPbot',
'PaperLiBot',
'StackRambler',
'msnbot',
'msnbot-media',
'msnbot-news',
]; ];
foreach ($bots as $bot) { foreach ($bots as $bot) {
@@ -298,21 +435,73 @@
} }
$converter = [ $converter = [
'а' => 'a', 'б' => 'b', 'в' => 'v', 'г' => 'g', 'д' => 'd', 'а' => 'a',
'е' => 'e', 'ё' => 'e', 'ж' => 'zh', 'з' => 'z', 'и' => 'i', 'б' => 'b',
'й' => 'y', 'к' => 'k', 'л' => 'l', 'м' => 'm', 'н' => 'n', 'в' => 'v',
'о' => 'o', 'п' => 'p', 'р' => 'r', 'с' => 's', 'т' => 't', 'г' => 'g',
'у' => 'u', 'ф' => 'f', 'х' => 'h', 'ц' => 'c', 'ч' => 'ch', 'д' => 'd',
'ш' => 'sh', 'щ' => 'sch', 'ь' => '', 'ы' => 'y', 'ъ' => '', 'е' => 'e',
'э' => 'e', 'ю' => 'yu', 'я' => 'ya', 'ё' => 'e',
'ж' => 'zh',
'з' => 'z',
'и' => 'i',
'й' => 'y',
'к' => 'k',
'л' => 'l',
'м' => 'm',
'н' => 'n',
'о' => 'o',
'п' => 'p',
'р' => 'r',
'с' => 's',
'т' => 't',
'у' => 'u',
'ф' => 'f',
'х' => 'h',
'ц' => 'c',
'ч' => 'ch',
'ш' => 'sh',
'щ' => 'sch',
'ь' => '',
'ы' => 'y',
'ъ' => '',
'э' => 'e',
'ю' => 'yu',
'я' => 'ya',
'А' => 'A', 'Б' => 'B', 'В' => 'V', 'Г' => 'G', 'Д' => 'D', 'А' => 'A',
'Е' => 'E', 'Ё' => 'E', 'Ж' => 'Zh', 'З' => 'Z', 'И' => 'I', 'Б' => 'B',
'Й' => 'Y', 'К' => 'K', 'Л' => 'L', 'М' => 'M', 'Н' => 'N', 'В' => 'V',
'О' => 'O', 'П' => 'P', 'Р' => 'R', 'С' => 'S', 'Т' => 'T', 'Г' => 'G',
'У' => 'U', 'Ф' => 'F', 'Х' => 'H', 'Ц' => 'C', 'Ч' => 'Ch', 'Д' => 'D',
'Ш' => 'Sh', 'Щ' => 'Sch', 'Ь' => '', 'Ы' => 'Y', 'Ъ' => '', 'Е' => 'E',
'Э' => 'E', 'Ю' => 'Yu', 'Я' => 'Ya', 'Ё' => 'E',
'Ж' => 'Zh',
'З' => 'Z',
'И' => 'I',
'Й' => 'Y',
'К' => 'K',
'Л' => 'L',
'М' => 'M',
'Н' => 'N',
'О' => 'O',
'П' => 'P',
'Р' => 'R',
'С' => 'S',
'Т' => 'T',
'У' => 'U',
'Ф' => 'F',
'Х' => 'H',
'Ц' => 'C',
'Ч' => 'Ch',
'Ш' => 'Sh',
'Щ' => 'Sch',
'Ь' => '',
'Ы' => 'Y',
'Ъ' => '',
'Э' => 'E',
'Ю' => 'Yu',
'Я' => 'Ya',
]; ];
$result = strtr($text, $converter); $result = strtr($text, $converter);
@@ -335,9 +524,7 @@
*/ */
public static function sendTelegram(string $message): void public static function sendTelegram(string $message): void
{ {
(new \Core\ExternalServices\TelegramSender(TELEGRAM_BOT_TOKEN)) (new \Core\ExternalServices\TelegramSender(TELEGRAM_BOT_TOKEN))->setChat(TELEGRAM_NOTIFICATION_CHANNEL)->sendMessage($message);
->setChat(TELEGRAM_NOTIFICATION_CHANNEL)
->sendMessage($message);
} }
/** /**
@@ -378,6 +565,43 @@
return $table; return $table;
} }
/**
* Анонс из теста
*
* @param string $text Текст
* @param int $limit Ограничение на количество символов
*
* @return string
*/
public static function previewText(string $text, int $limit = 300): string
{
$text = stripslashes($text);
$text = htmlspecialchars_decode($text, ENT_QUOTES);
$text = str_ireplace(['<br>', '<br />', '<br/>'], ' ', $text);
$text = strip_tags($text);
$text = trim($text);
if (mb_strlen($text) < $limit) {
return $text;
} else {
$text = mb_substr($text, 0, $limit);
$length = mb_strripos($text, ' ');
$end = mb_substr($text, $length - 1, 1);
if (empty($length)) {
return $text;
} elseif (in_array($end, ['.', '!', '?'])) {
return mb_substr($text, 0, $length);
} elseif (in_array($end, [',', ':', ';', '«', '»', '…', '(', ')', '—', '–', '-'])) {
return trim(mb_substr($text, 0, $length - 1)) . '...';
} else {
return trim(mb_substr($text, 0, $length)) . '...';
}
return trim($text);
}
}
public static function showPage() public static function showPage()
{ {
@@ -387,6 +611,5 @@
]); ]);
echo $twig->render('index.tpl', ['name' => 'Roman']); echo $twig->render('index.tpl', ['name' => 'Roman']);
} }
} }
+130 -7
View File
@@ -2,6 +2,7 @@
namespace Core; namespace Core;
use Core\Helpers\Cache;
use Core\Helpers\SystemFunctions; use Core\Helpers\SystemFunctions;
use Core\Helpers\Thumbs; use Core\Helpers\Thumbs;
use Core\ExternalServices\TelegramSender; use Core\ExternalServices\TelegramSender;
@@ -17,7 +18,8 @@
/** /**
* @throws CoreException * @throws CoreException
*/ */
public static function resizeImage(string $filename, int $width, int $height) { public static function resizeImage(string $filename, int $width, int $height)
{
$saveImage = $_SERVER['DOCUMENT_ROOT'] . '/uploads/images/resized/' . $filename; $saveImage = $_SERVER['DOCUMENT_ROOT'] . '/uploads/images/resized/' . $filename;
$image = new Thumbs($_SERVER['DOCUMENT_ROOT'] . '/uploads/images/original/' . $filename); $image = new Thumbs($_SERVER['DOCUMENT_ROOT'] . '/uploads/images/original/' . $filename);
$image->thumb($width, $height); $image->thumb($width, $height);
@@ -135,7 +137,11 @@
$res = $DB->query('SELECT * FROM bashorg WHERE hash="' . $hash . '" AND date is null'); $res = $DB->query('SELECT * FROM bashorg WHERE hash="' . $hash . '" AND date is null');
if ($res) { if ($res) {
$j++; $j++;
$DB->update('bashorg', ['hash' => $hash], ['ext_id' => (int)$element['id'], 'date' => $element['date'], 'rating' => $element['rating']]); $DB->update(
'bashorg',
['hash' => $hash],
['ext_id' => (int)$element['id'], 'date' => $element['date'], 'rating' => $element['rating']]
);
} }
} }
//sleep(5); //sleep(5);
@@ -165,13 +171,130 @@
if (!$res) { if (!$res) {
$i++; $i++;
$itemId = $DB->addItem('jokes', ['hash' => $hash, 'text' => $joke]); $itemId = $DB->addItem('jokes', ['hash' => $hash, 'text' => $joke]);
//sendTelegram('<b>Добавлена шутка ID ' . $itemId . '</b>' . PHP_EOL . $joke);
} }
} }
//sleep(2);
return 'Добавлено ' . $i . ' шуток из ' . count($arJokes); return 'Добавлено ' . $i . ' шуток из ' . count($arJokes);
} }
public static function anekdot2()
{
$result = 'Ничего нового не добавлено';
/** @var DB $DB */
$DB = DB::getInstance();
$file = file_get_contents('http://rzhunemogu.ru/RandJSON.aspx?CType=11');
$file = \iconv('windows-1251//IGNORE', 'UTF-8//IGNORE', $file);
$file = str_replace('{"content":"', '', $file);
$file = str_replace('"}', '', $file);
if (empty($file)) {
throw new CoreException('Ошибка получения данных с сайта');
}
$hash = md5($file);
$file = addslashes($file);
$res = $DB->query('SELECT * FROM jokes WHERE hash="' . $hash . '"');
if (!$res) {
$itemId = $DB->addItem('jokes', ['hash' => $hash, 'text' => $file]);
$result = 'Добавлен новый элемент с ID ' . $itemId;
}
return $result;
}
public static function clearDuplicates()
{
/** @var DB $DB */
$DB = DB::getInstance();
$DB->query(
'CREATE TEMPORARY TABLE `t_temp` AS (SELECT min(id) as id FROM `jokes` GROUP BY hash );
DELETE from `jokes` WHERE `jokes`.id not in (SELECT id FROM t_temp);'
);
return 'Дубликаты удалены';
}
public static function sendJokeToTelegram()
{
if(date('H') > 21 || date('H') < 9) {
return 'Нерабочее время :(';
}
$telegram = new \Core\ExternalServices\TelegramSender(TELEGRAM_BOT_TOKEN);
$telegram->setChat(' -1001610334197');
/** @var DB $DB */
$DB = DB::getInstance();
$joke = $DB->getItem('jokes', ['sended' => 'N']);
$joke = $DB->query('select * from jokes where sended="N" order by id desc')[0];
$telegram->sendMessage('<b>Шутейка #' . $joke['id'] . '</b>' . PHP_EOL . $joke['text']);
$DB->update('jokes', ['id' => $joke['id']], ['sended' => 'Y']);
return 'Шутка ' . $joke['id'] . ' отправлена в канал';
}
public static function getMySLO()
{
$cacheId = md5('getMySLO_criminal');
if(Cache::check($cacheId)) {
$oldLink = Cache::get($cacheId);
} else {
$oldLink = '';
}
$file = file_get_contents('https://myslo.ru/news/criminal');
$file = preg_match_all('/"item width-100-tiny">(.*?)<div class="clear">/us', $file, $file2);
$file2 = $file2[1][0];
preg_match_all('/<h1 class="h3">(.*?)<\/h1>/us', $file2, $title);
$title = trim(strip_tags($title[1][0]));
preg_match_all('/src="(.*?)">/us', $file2, $image);
$image = trim($image[1][0]);
preg_match_all('/" href="(.*?)">/us', $file2, $link);
$link = 'https://myslo.ru' . trim($link[1][0]);
if($oldLink !== $link) {
$full = file_get_contents($link);
preg_match_all('/<div class="h3 lid"><p>(.*?)<\/p><\/div>/us', $full, $lidArticle);
$lidArticle = html_entity_decode($lidArticle[1][0]);
preg_match_all('/class="myslo_insert" >(.*?)<a class="media/us', $full, $fullArticle);
$fullArticle = html_entity_decode($fullArticle[1][0]);
$fullArticle = str_replace("\r", '', $fullArticle);
$fullArticle = str_replace("\n\n", '', $fullArticle);
$fullArticle = trim($fullArticle);
$fullArticle = preg_replace('/\s+/', ' ', $fullArticle);
if (empty($fullArticle)) {
throw new CoreException('Не удалось получить данные');
}
$tmpFile = CACHE_DIR . '/' . basename($image);
file_put_contents($tmpFile, file_get_contents($image));
$lidArticle = SystemFunctions::previewText($lidArticle, 100);
$fullArticle = SystemFunctions::previewText($fullArticle, 300);
$post = '<b>' . $title . '</b>' . PHP_EOL . $lidArticle . PHP_EOL . $fullArticle;
$post .= PHP_EOL . '<a href="' . $link . '">Подробнее</a>';
$telegram = new \Core\ExternalServices\TelegramSender(TELEGRAM_BOT_TOKEN);
$telegram->setChat(TELEGRAM_NOTIFICATION_CHANNEL);
$res = $telegram->sendPhoto($tmpFile, $post);
@unlink($tmpFile);
Cache::set($cacheId, $link);
return $res;
} else {
return 'Обновление не требуется';
}
return $res;
}
} }
+45 -2
View File
@@ -252,10 +252,16 @@
/** /**
* Добавить элемент в базу * Добавить элемент в базу
* *
* @param $table * @param string $table Таблица
* @param $data * @param array $data Данные <pre>
* [
* 'name' => 'Roman',
* 'age' => 27
* ]
* </pre>
* *
* @return int|null * @return int|null
* @throws CoreException
*/ */
public function addItem($table, $data): ?int public function addItem($table, $data): ?int
{ {
@@ -267,6 +273,43 @@
return (int)$this->lastInsertId; return (int)$this->lastInsertId;
} }
/**
* Добавить несколько элементов в базу
*
* @param string $table Таблица
* @param array $data Данные <pre>
* [
* ['name' => 'Roman', 'age' => 27],
* ['name' => 'Dmitry', 'age' => 31],
* ]
* </pre>
*
* @return int|null
* @throws CoreException
*/
public function addItems($table, $data)
{
self::$quantity++;
if (empty($data)) {
return null;
}
$sql = 'INSERT INTO ' . $table . ' (' . implode(', ', array_keys(reset($data))) . ') VALUES ';
$arValues = [];
foreach ($data as $element) {
$element = array_map(function ($el) {
return '"' . $el . '"';
}, $element);
$arValues[] = '(' . implode(', ', $element) . ')';
}
$sql .= implode(', ', $arValues) . ';';
return $this->query($sql);
}
/** /**
* Удалить элемент из базы * Удалить элемент из базы
* *
+83 -1
View File
@@ -56,7 +56,7 @@
/** /**
* Количество задач для обработки * Количество задач для обработки
*/ */
const EXECUTION_TASKS_LIMIT = 100; const EXECUTION_TASKS_LIMIT = 1000;
/** /**
* Лимит количества запущенных воркеров * Лимит количества запущенных воркеров
@@ -377,6 +377,75 @@
return $this; return $this;
} }
/**
* Массовое создание заданий
*
* @param int $count Количество заданий
* @param string|null $class Класс
* @param string $method Метод класса
* @param ?array $params Массив параметров
*
* @return \Core\Models\MQResponse
* @throws CoreException
*/
public function massCreateTasks(int $count = 1, ?string $class = null, string $method, ?array $params = null): MQResponse
{
if (empty($params)) {
$params = [];
}
if (!empty($this->priority)) {
$priority = $this->priority;
} else {
$priority = self::DEFAULT_PRIORITY;
}
$params = $this->convertToJson($params);
if (USE_LOG) {
Log::logToFile(
'Запущено массовое создание заданий',
self::LOG_FILE,
func_get_args(),
LOG_DEBUG
);
}
$arData = [];
for ($i = 0; $i < $count; $i++) {
$arData[] = [
'active' => self::VALUE_N,
'in_progress' => self::VALUE_N,
'attempts' => '0',
'attempts_limit' => $this->attempts,
'class' => !empty($class) ? addslashes($class) : '',
'method' => $method,
'priority' => $priority,
'params' => $params,
];
}
$this->DB->addItems(self::TABLE, $arData);
$this->priority = null;
$response = new MQResponse();
$response->setTaskId(0)->setStatus(self::STATUS_OK)->setParams(self::convertFromJson($params))->setParamsJson($params)->setResponse(
$count . ' tasks were created'
);
if (USE_LOG) {
Log::logToFile(
'Массовое создание заданий завершено',
self::LOG_FILE,
func_get_args(),
LOG_DEBUG
);
}
return $response;
}
/** /**
* Добавление задания в очередь * Добавление задания в очередь
* *
@@ -674,6 +743,19 @@
return $this->DB->query('SELECT * FROM ' . self::TABLE . ' ORDER BY ' . $orderBy . ' ' . $sort . ' LIMIT ' . $limit) ?? []; return $this->DB->query('SELECT * FROM ' . self::TABLE . ' ORDER BY ' . $orderBy . ' ' . $sort . ' LIMIT ' . $limit) ?? [];
} }
/**
* Получение списка истории заданий из очереди
*
* @param string $limit Лимит
*
* @return mixed|null
* @throws CoreException
*/
public function getTasksHistory(string $limit = '10', string $orderBy = 'id', string $sort = 'DESC'): ?array
{
return $this->DB->query('SELECT * FROM ' . self::TABLE_HISTORY . ' ORDER BY ' . $orderBy . ' ' . $sort . ' LIMIT ' . $limit) ?? [];
}
/** /**
* Получение количества заданий в очереди * Получение количества заданий в очереди
* *
+2 -26
View File
@@ -2,29 +2,5 @@
$_SERVER['DOCUMENT_ROOT'] = '/home/rsgrinko/sites/dev.it-stories.ru'; $_SERVER['DOCUMENT_ROOT'] = '/home/rsgrinko/sites/dev.it-stories.ru';
require_once $_SERVER['DOCUMENT_ROOT'] . '/core/bootstrap.php'; require_once $_SERVER['DOCUMENT_ROOT'] . '/core/bootstrap.php';
use Core\ExternalServices\TelegramSender; use Core\MQTasks;
use Core\Helpers\Log; echo MQTasks::sendJokeToTelegram();
throw new Exception('test ololo');
//Log::logToSentry('Тестовая ошибка', 'ERROR', $_REQUEST);
die();
$numProc = 4;
if (empty($argv[1])) {
$currentRunThread = (int)exec('ps -awx | grep \'test.php\' | grep -v \'grep\' | wc -l');
echo 'Now running: ' . $currentRunThread . PHP_EOL;
while ($currentRunThread <= $numProc) {
echo 'Run new (' . $currentRunThread . ')' . PHP_EOL;
$handler = '(php -f /home/rsgrinko/sites/dev.it-stories.ru/test.php ' . $currentRunThread . ' &) >> /dev/null 2>&1';
passthru($handler);
$currentRunThread = (int)exec('ps -awx | grep \'test.php\' | grep -v \'grep\' | wc -l');
echo 'Now running: ' . $currentRunThread . PHP_EOL;
}
} else {
$res = (new TelegramSender(TELEGRAM_BOT_TOKEN))->setChat(TELEGRAM_NOTIFICATION_CHANNEL)->sendMessage('Start proc #' . $argv[1]);
Log::logToFile(json_encode($res, JSON_UNESCAPED_UNICODE), 'test.log', $argv[1]);
sleep(rand(2, 10));
$res = (new TelegramSender(TELEGRAM_BOT_TOKEN))->setChat(TELEGRAM_NOTIFICATION_CHANNEL)->sendMessage('End proc #' . $argv[1]);
Log::logToFile(json_encode($res, JSON_UNESCAPED_UNICODE), 'test.log', $argv[1]);
}