diff --git a/admin/threads.php b/admin/threads.php index bfb5a6b..eabd860 100644 --- a/admin/threads.php +++ b/admin/threads.php @@ -172,4 +172,68 @@ + + + +
+
+
+
+

Выполненные задания

+

Список заверщившихся заданий

+
+ +
+ + + + + + + + + + + + + + + + + + getTasksHistory(10, 'id', 'desc'); + foreach($arTasks as $task) { + ?> + + + + + + + + + + + + + + + +
IDID заданияВремя выполненияПопытокКлассМетодПараметрыСтатусРезультатСозданОбновлен
+
+ +
+
+ + +
\ No newline at end of file diff --git a/core/config.php b/core/config.php index 81b4caf..af1673d 100644 --- a/core/config.php +++ b/core/config.php @@ -56,7 +56,7 @@ /** * Использование кэша */ - const USE_CACHE = false; + const USE_CACHE = true; /** * Папка кэша @@ -76,5 +76,5 @@ /** * Флаг использования логирования */ - const USE_LOG = true; + const USE_LOG = false; diff --git a/core/cron.php b/core/cron.php index 382e0d1..ba0adb6 100644 --- a/core/cron.php +++ b/core/cron.php @@ -1,6 +1,8 @@ > /dev/null 2>&1'); \ No newline at end of file + 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'); + } \ No newline at end of file diff --git a/core/lib/Core/ExternalServices/TelegramSender.class.php b/core/lib/Core/ExternalServices/TelegramSender.class.php index d830d95..425c7e4 100644 --- a/core/lib/Core/ExternalServices/TelegramSender.class.php +++ b/core/lib/Core/ExternalServices/TelegramSender.class.php @@ -1,6 +1,7 @@ * @package ITS @@ -40,13 +41,14 @@ public function __construct(string $token = TELEGRAM_BOT_TOKEN) { $this->token = $token; - $this->url = 'https://' . self::BASE_URL . '/bot' . $token . '/'; + $this->url = 'https://' . self::BASE_URL . '/bot' . $token . '/'; } /** * Установка метода * * @param string $method Метод + * * @return $this */ private function setMethod(string $method): self @@ -55,10 +57,32 @@ 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, '
');
+            $text = substr(trim($text), 0, $isCaption ? 1024 : 4096);
+            $text = mb_convert_encoding($text, 'UTF-8', 'UTF-8');
+
+            return $text;
+        }
+
         /**
          * Установка идентификатора чата
          *
          * @param int $chatId Метод
+         *
          * @return $this
          */
         public function setChat(int $chatId): self
@@ -81,7 +105,7 @@
             curl_setopt($ch, CURLOPT_POSTFIELDS, $response);
             curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
             curl_setopt($ch, CURLOPT_HEADER, false);
-            $res = curl_exec($ch);
+            $res      = curl_exec($ch);
             $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
             curl_close($ch);
             return json_decode($res, true);
@@ -90,16 +114,21 @@
         /**
          * Отправка изображения
          *
-         * @param string $imagePath Путь до изображения
+         * @param string      $imagePath Путь до изображения
+         * @param string|null $caption   Подпись
          *
          * @return array
          */
-        public function sendPhoto(string $imagePath): array
+        public function sendPhoto(string $imagePath, ?string $caption = null): array
         {
             $response = [
-                'chat_id' => $this->chatId,
-                'photo' => curl_file_create($imagePath),
+                'chat_id'    => $this->chatId,
+                'photo'      => curl_file_create($imagePath),
+                'parse_mode' => 'html',
             ];
+            if (!empty($caption)) {
+                $response['caption'] = $this->sanitize($caption, true);
+            }
             return $this->setMethod('sendPhoto')->sendRequest($response);
         }
 
@@ -113,7 +142,7 @@
         public function sendDocument(string $filePath): array
         {
             $response = [
-                'chat_id' => $this->chatId,
+                'chat_id'  => $this->chatId,
                 'document' => curl_file_create($filePath),
             ];
             return $this->setMethod('sendDocument')->sendRequest($response);
@@ -123,7 +152,7 @@
         /**
          * Отправляет координаты с картой
          *
-         * @param float $latitude Широта
+         * @param float $latitude  Широта
          * @param float $longitude Долгота
          *
          * @return array
@@ -131,8 +160,8 @@
         public function sendLocation(float $latitude, float $longitude): array
         {
             $response = [
-                'chat_id' => $this->chatId,
-                'latitude' => $latitude,
+                'chat_id'   => $this->chatId,
+                'latitude'  => $latitude,
                 'longitude' => $longitude,
             ];
             return $this->setMethod('sendLocation')->sendRequest($response);
@@ -148,13 +177,10 @@
          */
         public function sendMessage(?string $text): array
         {
-            $text = substr(trim($text), 0, 4096);
-            $text = strip_tags($text, '
');
-            $text = mb_convert_encoding($text, 'UTF-8', 'UTF-8');
             $params = [
-                'chat_id' => $this->chatId,
+                'chat_id'    => $this->chatId,
                 'parse_mode' => 'html',
-                'text' => $text
+                'text'       => $this->sanitize($text),
             ];
 
             return $this->setMethod('sendMessage')->sendRequest($params);
diff --git a/core/lib/Core/Helpers/SystemFunctions.class.php b/core/lib/Core/Helpers/SystemFunctions.class.php
index 2ef5e3c..d468870 100644
--- a/core/lib/Core/Helpers/SystemFunctions.class.php
+++ b/core/lib/Core/Helpers/SystemFunctions.class.php
@@ -18,7 +18,7 @@
             $keys = [
                 'HTTP_CLIENT_IP',
                 'HTTP_X_FORWARDED_FOR',
-                'REMOTE_ADDR'
+                'REMOTE_ADDR',
             ];
             foreach ($keys as $key) {
                 if (!empty($_SERVER[$key])) {
@@ -35,6 +35,7 @@
          * Преобразование байт в человеческий вид
          *
          * @param int $size Размер в байтах
+         *
          * @return string
          */
         public static function convertBytes(int $size): string
@@ -67,34 +68,34 @@
         {
             $undefinedOS = 'Unknown OS';
 
-            if(empty($_SERVER['HTTP_USER_AGENT'])) {
+            if (empty($_SERVER['HTTP_USER_AGENT'])) {
                 return $undefinedOS;
             }
 
             $oses = [
-                'iOS' => '/(iPhone)|(iPad)/i',
-                'Windows 3.11' => '/Win16/i',
-                'Windows 95' => '/(Windows 95)|(Win95)|(Windows_95)/i',
-                'Windows 98' => '/(Windows 98)|(Win98)/i',
-                'Windows 2000' => '/(Windows NT 5.0)|(Windows 2000)/i',
-                'Windows XP' => '/(Windows NT 5.1)|(Windows XP)/i',
-                'Windows 2003' => '/(Windows NT 5.2)/i',
-                'Windows Vista' => '/(Windows NT 6.0)|(Windows Vista)/i',
-                'Windows 7' => '/(Windows NT 6.1)|(Windows 7)/i',
-                'Windows 8' => '/(Windows NT 6.2)|(Windows 8)/i',
-                'Windows 8.1' => '/(Windows NT 6.3)|(Windows 8.1)/i',
-                'Windows 10' => '/(Windows NT 10.0)|(Windows 10)/i',
+                'iOS'            => '/(iPhone)|(iPad)/i',
+                'Windows 3.11'   => '/Win16/i',
+                'Windows 95'     => '/(Windows 95)|(Win95)|(Windows_95)/i',
+                'Windows 98'     => '/(Windows 98)|(Win98)/i',
+                'Windows 2000'   => '/(Windows NT 5.0)|(Windows 2000)/i',
+                'Windows XP'     => '/(Windows NT 5.1)|(Windows XP)/i',
+                'Windows 2003'   => '/(Windows NT 5.2)/i',
+                'Windows Vista'  => '/(Windows NT 6.0)|(Windows Vista)/i',
+                'Windows 7'      => '/(Windows NT 6.1)|(Windows 7)/i',
+                'Windows 8'      => '/(Windows NT 6.2)|(Windows 8)/i',
+                'Windows 8.1'    => '/(Windows NT 6.3)|(Windows 8.1)/i',
+                'Windows 10'     => '/(Windows NT 10.0)|(Windows 10)/i',
                 'Windows NT 4.0' => '/(Windows NT 4.0)|(WinNT4.0)|(WinNT)|(Windows NT)/i',
-                'Windows ME' => '/Windows ME/i',
-                'Open BSD' => '/OpenBSD/i',
-                'Sun OS' => '/SunOS/i',
-                'Android' => '/Android/i',
-                'Linux' => '/(Linux)|(X11)/i',
-                'Macintosh' => '/(Mac_PowerPC)|(Macintosh)/i',
-                'QNX' => '/QNX/i',
-                'BeOS' => '/BeOS/i',
-                'OS/2' => '/OS/2/i',
-                'Search Bot' => '/(nuhk)|(Googlebot)|(Yammybot)|(Openbot)|(Slurp/cat)|(msnbot)|(ia_archiver)/i',
+                'Windows ME'     => '/Windows ME/i',
+                'Open BSD'       => '/OpenBSD/i',
+                'Sun OS'         => '/SunOS/i',
+                'Android'        => '/Android/i',
+                'Linux'          => '/(Linux)|(X11)/i',
+                'Macintosh'      => '/(Mac_PowerPC)|(Macintosh)/i',
+                'QNX'            => '/QNX/i',
+                'BeOS'           => '/BeOS/i',
+                'OS/2'           => '/OS/2/i',
+                'Search Bot'     => '/(nuhk)|(Googlebot)|(Yammybot)|(Openbot)|(Slurp/cat)|(msnbot)|(ia_archiver)/i',
             ];
 
             foreach ($oses as $os => $pattern) {
@@ -110,7 +111,7 @@
          */
         public static function generateGUID(): string
         {
-            $uid = dechex(microtime(true) * 1000) . bin2hex(random_bytes(8));
+            $uid  = dechex(microtime(true) * 1000) . bin2hex(random_bytes(8));
             $guid = vsprintf('DLT%s-1000-%s-8%.3s-%s%s%s0', str_split($uid, 4));
             return strtoupper($guid);
         }
@@ -127,22 +128,89 @@
         {
             $number = ($number > 0) ? $number : 1;
 
-            $arChars = [
-                'a', 'b', 'c', 'd', 'e', 'f',
-                'g', 'h', 'i', 'j', 'k', 'l',
-                'm', 'n', 'o', 'p', 'r', 's',
-                't', 'u', 'v', 'x', 'y', 'z',
-                'A', 'B', 'C', 'D', 'E', 'F',
-                'G', 'H', 'I', 'J', 'K', 'L',
-                'M', 'N', 'O', 'P', 'R', 'S',
-                'T', 'U', 'V', 'X', 'Y', 'Z',
-                '1', '2', '3', '4', '5', '6',
-                '7', '8', '9', '0'];
+            $arChars        = [
+                'a',
+                'b',
+                'c',
+                'd',
+                'e',
+                'f',
+                'g',
+                'h',
+                'i',
+                'j',
+                'k',
+                'l',
+                'm',
+                'n',
+                'o',
+                'p',
+                'r',
+                's',
+                't',
+                'u',
+                'v',
+                'x',
+                'y',
+                'z',
+                'A',
+                'B',
+                'C',
+                'D',
+                'E',
+                'F',
+                'G',
+                'H',
+                'I',
+                'J',
+                'K',
+                'L',
+                'M',
+                'N',
+                'O',
+                'P',
+                'R',
+                'S',
+                'T',
+                'U',
+                'V',
+                'X',
+                'Y',
+                'Z',
+                '1',
+                '2',
+                '3',
+                '4',
+                '5',
+                '6',
+                '7',
+                '8',
+                '9',
+                '0',
+            ];
             $arSpecialChars = [
-                '(', ')', '[', ']', '!', '?',
-                '&', '^', '%', '@', '*', '$',
-                '<', '>', '/', '|', '+', '-',
-                '{', '}', '~'];
+                '(',
+                ')',
+                '[',
+                ']',
+                '!',
+                '?',
+                '&',
+                '^',
+                '%',
+                '@',
+                '*',
+                '$',
+                '<',
+                '>',
+                '/',
+                '|',
+                '+',
+                '-',
+                '{',
+                '}',
+                '~',
+            ];
 
             if ($useSpecialChars) {
                 $arChars = array_merge($arChars, $arSpecialChars);
@@ -151,7 +219,7 @@
             $pass = '';
             for ($i = 0; $i < $number; $i++) {
                 $index = rand(0, count($arChars) - 1);
-                $pass .= $arChars[$index];
+                $pass  .= $arChars[$index];
             }
             return $pass;
         }
@@ -172,26 +240,95 @@
 
             $bots = [
                 // Yandex
-                'YandexBot', 'YandexAccessibilityBot', 'YandexMobileBot', 'YandexDirectDyn', 'YandexScreenshotBot',
-                'YandexImages', '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',
+                'YandexBot',
+                'YandexAccessibilityBot',
+                'YandexMobileBot',
+                'YandexDirectDyn',
+                'YandexScreenshotBot',
+                'YandexImages',
+                '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
-                'Googlebot', 'Googlebot-Image', 'Mediapartners-Google', 'AdsBot-Google', 'APIs-Google',
-                'AdsBot-Google-Mobile', 'AdsBot-Google-Mobile', 'Googlebot-News', 'Googlebot-Video',
+                'Googlebot',
+                'Googlebot-Image',
+                'Mediapartners-Google',
+                'AdsBot-Google',
+                'APIs-Google',
+                'AdsBot-Google-Mobile',
+                'AdsBot-Google-Mobile',
+                'Googlebot-News',
+                'Googlebot-Video',
                 'AdsBot-Google-Mobile-Apps',
 
                 // Other
-                'Mail.RU_Bot', 'bingbot', 'Accoona', 'ia_archiver', 'Ask Jeeves', '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',
+                'Mail.RU_Bot',
+                'bingbot',
+                'Accoona',
+                'ia_archiver',
+                'Ask Jeeves',
+                '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) {
@@ -255,13 +392,13 @@
             }
 
             $hours = floor($secs / 3600);
-            $secs = $secs % 3600;
+            $secs  = $secs % 3600;
             if ($hours > 0) {
                 $res .= $hours . ' ' . self::numWord($hours, ['час', 'часа', 'часов']) . ', ';
             }
 
             $minutes = floor($secs / 60);
-            $secs = $secs % 60;
+            $secs    = $secs % 60;
             if ($minutes > 0) {
                 $res .= $minutes . ' ' . self::numWord($minutes, ['минута', 'минуты', 'минут']) . ', ';
             }
@@ -298,21 +435,73 @@
             }
 
             $converter = [
-                'а' => 'a', 'б' => 'b', 'в' => 'v', 'г' => 'g', 'д' => 'd',
-                'е' => 'e', 'ё' => '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',
+                'е' => 'e',
+                'ё' => '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',
-                'Е' => 'E', 'Ё' => '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',
+                'Е' => 'E',
+                'Ё' => '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);
@@ -335,9 +524,7 @@
          */
         public static function sendTelegram(string $message): void
         {
-            (new \Core\ExternalServices\TelegramSender(TELEGRAM_BOT_TOKEN))
-                ->setChat(TELEGRAM_NOTIFICATION_CHANNEL)
-                ->sendMessage($message);
+            (new \Core\ExternalServices\TelegramSender(TELEGRAM_BOT_TOKEN))->setChat(TELEGRAM_NOTIFICATION_CHANNEL)->sendMessage($message);
         }
 
         /**
@@ -350,10 +537,10 @@
          */
         public static function arrayToTable($var, string $title = ''): ?string
         {
-            $tableStyle = 'border: 1px solid #7b9ea3;border-collapse: collapse;';
+            $tableStyle  = 'border: 1px solid #7b9ea3;border-collapse: collapse;';
             $tdBoldStyle = 'padding: 10px;border: 1px solid #7b9ea3;background: powderblue;font-weight: bold; text-align: center;color: #226770;text-shadow: #7b9ea3 0px 0px 2px;';
-            $tdStyle = 'padding: 10px;border: 1px solid #7b9ea3;';
-            $thStyle = 'text-align: center;font-size: 1.3em;padding: 10px;background: linear-gradient(0deg, #b0e0e6, #90c1c7);color: #226770;text-shadow: #7b9ea3 1px 1px 0px;';
+            $tdStyle     = 'padding: 10px;border: 1px solid #7b9ea3;';
+            $thStyle     = 'text-align: center;font-size: 1.3em;padding: 10px;background: linear-gradient(0deg, #b0e0e6, #90c1c7);color: #226770;text-shadow: #7b9ea3 1px 1px 0px;';
             if (is_array($var)) {
                 $table = '';
                 if ($title) {
@@ -378,15 +565,51 @@
             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(['
', '
', '
'], ' ', $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() { $loader = new \Twig\Loader\FilesystemLoader(PATH_TO_TEMPLATES); - $twig = new \Twig\Environment($loader, [ + $twig = new \Twig\Environment($loader, [ 'cache' => CACHE_DIR, ]); echo $twig->render('index.tpl', ['name' => 'Roman']); - } } \ No newline at end of file diff --git a/core/lib/Core/MQTasks.class.php b/core/lib/Core/MQTasks.class.php index 476f237..00b275f 100644 --- a/core/lib/Core/MQTasks.class.php +++ b/core/lib/Core/MQTasks.class.php @@ -2,6 +2,7 @@ namespace Core; + use Core\Helpers\Cache; use Core\Helpers\SystemFunctions; use Core\Helpers\Thumbs; use Core\ExternalServices\TelegramSender; @@ -17,9 +18,10 @@ /** * @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; - $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->watermark($_SERVER['DOCUMENT_ROOT'] . '/uploads/images/w.png', 'bottom-right', 70); $image->save($saveImage); @@ -43,7 +45,7 @@ $i = 0; foreach ($frazes as $post) { - //sendTelegram($post); + //sendTelegram($post); $text = str_replace('
', PHP_EOL, $post); $text = htmlspecialchars_decode($text); $text = str_replace('\'', '\\\'', $text); @@ -71,7 +73,7 @@ return \iconv('windows-1251//IGNORE', 'UTF-8//IGNORE', $e); }, $frazes); - $i =0; + $i = 0; foreach ($frazes as $post) { //sendTelegram($post); $text = str_replace('
', PHP_EOL, $post); @@ -102,7 +104,7 @@ preg_match_all('|
(.+)
|U', $frazes, $posts); $posts = $posts[1]; - if(empty($posts)) { + if (empty($posts)) { throw new CoreException('Ошибка обработки данных'); } @@ -125,7 +127,7 @@ ]; } - $i =0; + $i = 0; $j = 0; foreach ($result as $element) { $text = str_replace('
', PHP_EOL, $element['post']); @@ -135,7 +137,11 @@ $res = $DB->query('SELECT * FROM bashorg WHERE hash="' . $hash . '" AND date is null'); if ($res) { $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); @@ -147,17 +153,17 @@ /** @var DB $DB */ $DB = DB::getInstance(); - $file = file_get_contents('https://www.anekdot.ru/rss/randomu.html'); - $file = explode('JSON.parse(\'', $file)[1]; - $file = explode('\');', $file)[0]; - $file = stripcslashes($file); + $file = file_get_contents('https://www.anekdot.ru/rss/randomu.html'); + $file = explode('JSON.parse(\'', $file)[1]; + $file = explode('\');', $file)[0]; + $file = stripcslashes($file); $arJokes = json_decode($file); - if(empty($arJokes)) { + if (empty($arJokes)) { throw new CoreException('Ошибка получения данных с сайта'); } $i = 0; - foreach($arJokes as $joke) { + foreach ($arJokes as $joke) { $hash = md5($joke); $joke = str_replace('
', PHP_EOL, $joke); $joke = addslashes($joke); @@ -165,13 +171,130 @@ if (!$res) { $i++; $itemId = $DB->addItem('jokes', ['hash' => $hash, 'text' => $joke]); - //sendTelegram('Добавлена шутка ID ' . $itemId . '' . PHP_EOL . $joke); } } - - - - //sleep(2); 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('Шутейка #' . $joke['id'] . '' . 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">(.*?)
/us', $file, $file2); + $file2 = $file2[1][0]; + + preg_match_all('/

(.*?)<\/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('/

(.*?)<\/p><\/div>/us', $full, $lidArticle); + $lidArticle = html_entity_decode($lidArticle[1][0]); + + preg_match_all('/class="myslo_insert" >(.*?)' . PHP_EOL . $lidArticle . PHP_EOL . $fullArticle; + $post .= PHP_EOL . 'Подробнее'; + + $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; + } } \ No newline at end of file diff --git a/core/lib/Core/Models/DB.class.php b/core/lib/Core/Models/DB.class.php index e83fa61..0d13705 100644 --- a/core/lib/Core/Models/DB.class.php +++ b/core/lib/Core/Models/DB.class.php @@ -49,13 +49,13 @@ */ public function __construct(string $db_server = DB_HOST, string $db_user = DB_USER, ?string $db_pass = DB_PASSWORD, string $db_name = DB_NAME) { - $dsn = 'mysql:host=' . $db_server . ';dbname=' . $db_name . ';charset=utf8'; - $opt = [ - \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION, - \PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC, - \PDO::ATTR_EMULATE_PREPARES => false, - ]; - $this->db = new \PDO($dsn, $db_user, $db_pass, $opt); + $dsn = 'mysql:host=' . $db_server . ';dbname=' . $db_name . ';charset=utf8'; + $opt = [ + \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION, + \PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC, + \PDO::ATTR_EMULATE_PREPARES => false, + ]; + $this->db = new \PDO($dsn, $db_user, $db_pass, $opt); } /** @@ -93,7 +93,7 @@ { if (!is_array($where)) { return $where; - }elseif (empty($where)){ + } elseif (empty($where)) { return '1'; } $where_string = ''; @@ -192,24 +192,24 @@ { $startTime = microtime(true); self::$quantity++; - try { - $stmt = $this->db->query($sql); - } catch (\Throwable $t) { - sendTelegram('SQL ERROR: ' . $sql); - throw new CoreException('В SQL запросе произошла ошибка', CoreException::ERROR_SQL_QUERY); - } - $this->lastInsertId = $this->db->lastInsertId() ?? null; + try { + $stmt = $this->db->query($sql); + } catch (\Throwable $t) { + sendTelegram('SQL ERROR: ' . $sql); + throw new CoreException('В SQL запросе произошла ошибка', CoreException::ERROR_SQL_QUERY); + } + $this->lastInsertId = $this->db->lastInsertId() ?? null; - $endTime = microtime(true); - self::$workingTime += ($endTime - $startTime); + $endTime = microtime(true); + self::$workingTime += ($endTime - $startTime); - if ($returnObject) { - return $stmt; - } else { - $result = $stmt->fetchAll(); - return $result ?: null; - } + if ($returnObject) { + return $stmt; + } else { + $result = $stmt->fetchAll(); + return $result ?: null; + } } /** @@ -252,10 +252,16 @@ /** * Добавить элемент в базу * - * @param $table - * @param $data + * @param string $table Таблица + * @param array $data Данные

+         *                        [
+         *                        'name' => 'Roman',
+         *                        'age' => 27
+         *                        ]
+         *                        
* * @return int|null + * @throws CoreException */ public function addItem($table, $data): ?int { @@ -267,6 +273,43 @@ return (int)$this->lastInsertId; } + /** + * Добавить несколько элементов в базу + * + * @param string $table Таблица + * @param array $data Данные
+         *                        [
+         *                        ['name' => 'Roman', 'age' => 27],
+         *                        ['name' => 'Dmitry', 'age' => 31],
+         *                        ]
+         *                        
+ * + * @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); + } + /** * Удалить элемент из базы * diff --git a/core/lib/Core/Models/MQ.class.php b/core/lib/Core/Models/MQ.class.php index 13e9113..4278090 100644 --- a/core/lib/Core/Models/MQ.class.php +++ b/core/lib/Core/Models/MQ.class.php @@ -56,7 +56,7 @@ /** * Количество задач для обработки */ - const EXECUTION_TASKS_LIMIT = 100; + const EXECUTION_TASKS_LIMIT = 1000; /** * Лимит количества запущенных воркеров @@ -377,6 +377,75 @@ 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) ?? []; } + /** + * Получение списка истории заданий из очереди + * + * @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) ?? []; + } + /** * Получение количества заданий в очереди * diff --git a/test.php b/test.php index a404b25..61d820a 100644 --- a/test.php +++ b/test.php @@ -2,29 +2,5 @@ $_SERVER['DOCUMENT_ROOT'] = '/home/rsgrinko/sites/dev.it-stories.ru'; require_once $_SERVER['DOCUMENT_ROOT'] . '/core/bootstrap.php'; - use Core\ExternalServices\TelegramSender; - use Core\Helpers\Log; -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]); - } - + use Core\MQTasks; + echo MQTasks::sendJokeToTelegram();