Passed
Push — develop ( 96460f...afdd08 )
by Портнов
04:07
created

Util::echoDone()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 4
c 1
b 0
f 0
dl 0
loc 6
rs 10
cc 2
nc 2
nop 1
1
<?php
2
/*
3
 * MikoPBX - free phone system for small business
4
 * Copyright (C) 2017-2020 Alexey Portnov and Nikolay Beketov
5
 *
6
 * This program is free software: you can redistribute it and/or modify
7
 * it under the terms of the GNU General Public License as published by
8
 * the Free Software Foundation; either version 3 of the License, or
9
 * (at your option) any later version.
10
 *
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License along with this program.
17
 * If not, see <https://www.gnu.org/licenses/>.
18
 */
19
20
namespace MikoPBX\Core\System;
21
22
use DateTime;
23
use Exception;
24
use MikoPBX\Common\Models\{CallEventsLogs, CustomFiles};
25
use MikoPBX\Common\Providers\LoggerProvider;
26
use MikoPBX\Core\Asterisk\AsteriskManager;
27
use Phalcon\Di;
28
use ReflectionClass;
29
use ReflectionException;
30
use Throwable;
31
32
/**
33
 * Universal commands and procedures
34
 */
35
class Util
36
{
37
38
    /**
39
     * @param $options
40
     * @param $manual_attributes
41
     * @param $section
42
     *
43
     * @return string
44
     */
45
    public static function overrideConfigurationArray($options, $manual_attributes, $section): string
46
    {
47
        $result_config = '';
48
        if ($manual_attributes !== null && isset($manual_attributes[$section])) {
49
            foreach ($manual_attributes[$section] as $key => $value) {
50
                if ($key === 'type') {
51
                    continue;
52
                }
53
                $options[$key] = $value;
54
            }
55
        }
56
        foreach ($options as $key => $value) {
57
            if (empty($value) || empty($key)) {
58
                continue;
59
            }
60
            if (is_array($value)) {
61
                array_unshift($value, ' ');
62
                $result_config .= trim(implode("\n{$key} = ", $value)) . "\n";
63
            } else {
64
                $result_config .= "{$key} = {$value}\n";
65
            }
66
        }
67
68
        return "$result_config\n";
69
    }
70
71
    /**
72
     * Инициация телефонного звонка.
73
     *
74
     * @param $peer_number
75
     * @param $peer_mobile
76
     * @param $dest_number
77
     *
78
     * @return array
79
     * @throws Exception
80
     */
81
    public static function amiOriginate($peer_number, $peer_mobile, $dest_number): array
82
    {
83
        $am       = self::getAstManager('off');
84
        $channel  = 'Local/' . $peer_number . '@internal-originate';
85
        $context  = 'all_peers';
86
        $IS_ORGNT = self::generateRandomString();
87
        $variable = "_IS_ORGNT={$IS_ORGNT},pt1c_cid={$dest_number},_extenfrom1c={$peer_number},__peer_mobile={$peer_mobile},_FROM_PEER={$peer_number}";
88
89
        return $am->Originate(
90
            $channel,
91
            $dest_number,
92
            $context,
93
            '1',
94
            null,
95
            null,
96
            null,
97
            null,
98
            $variable,
99
            null,
100
            true
101
        );
102
    }
103
104
    /**
105
     * Получаем объект менеджер asterisk.
106
     *
107
     * @param string $events
108
     *
109
     * @return AsteriskManager
110
     */
111
    public static function getAstManager($events = 'on'): AsteriskManager
112
    {
113
        if ($events === 'on') {
114
            $nameService = 'amiListner';
115
        } else {
116
            $nameService = 'amiCommander';
117
        }
118
119
        $di = Di::getDefault();
120
        $am = $di->getShared($nameService);
121
        if (is_resource($am->socket)) {
122
            return $am;
123
        }
124
125
        return $di->get($nameService);
126
    }
127
128
    /**
129
     * Генератор произвольной строки.
130
     *
131
     * @param int $length
132
     *
133
     * @return string
134
     */
135
    public static function generateRandomString($length = 10): string
136
    {
137
        $characters       = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
138
        $charactersLength = strlen($characters);
139
        $randomString     = '';
140
        for ($i = 0; $i < $length; $i++) {
141
            try {
142
                $randomString .= $characters[random_int(0, $charactersLength - 1)];
143
            } catch (Throwable $e) {
144
                $randomString = '';
145
            }
146
        }
147
148
        return $randomString;
149
    }
150
151
    /**
152
     * Json validate
153
     *
154
     * @param $jsonString
155
     *
156
     * @return bool
157
     */
158
    public static function isJson($jsonString): bool
159
    {
160
        json_decode($jsonString, true);
161
162
        return (json_last_error() === JSON_ERROR_NONE);
163
    }
164
165
    /**
166
     *  Возвращает размер файла в Мб.
167
     *
168
     * @param $filename
169
     *
170
     * @return float|int
171
     */
172
    public static function mFileSize($filename)
173
    {
174
        $size = 0;
175
        if (file_exists($filename)) {
176
            $tmp_size = filesize($filename);
177
            if ($tmp_size !== false) {
178
                // Получим размер в Мб.
179
                $size = $tmp_size;
180
            }
181
        }
182
183
        return $size;
184
    }
185
186
    /**
187
     * Возвращает указанное количество X.
188
     *
189
     * @param $length
190
     *
191
     * @return string
192
     */
193
    public static function getExtensionX($length): string
194
    {
195
        $extension = '';
196
        for ($i = 0; $i < $length; $i++) {
197
            $extension .= 'X';
198
        }
199
200
        return $extension;
201
    }
202
203
    /**
204
     * Проверяет существование файла.
205
     *
206
     * @param $filename
207
     *
208
     * @return bool
209
     */
210
    public static function recFileExists($filename): ?bool
211
    {
212
        return (file_exists($filename) && filesize($filename) > 0);
213
    }
214
215
    /**
216
     * Если переданный параметр - число, то будет возвращена дата.
217
     *
218
     * @param $data
219
     *
220
     * @return string
221
     */
222
    public static function numberToDate($data): string
223
    {
224
        $re_number = '/^\d+.\d+$/';
225
        preg_match_all($re_number, $data, $matches, PREG_SET_ORDER, 0);
226
        if (count($matches) > 0) {
227
            $data = date('Y.m.d-H:i:s', $data);
228
        }
229
230
        return $data;
231
    }
232
233
    /**
234
     * Записывает данные в файл.
235
     *
236
     * @param $filename
237
     * @param $data
238
     */
239
    public static function fileWriteContent($filename, $data): void
240
    {
241
        /** @var CustomFiles $res */
242
        $res = CustomFiles::findFirst("filepath = '{$filename}'");
243
244
        $filename_orgn = "{$filename}.orgn";
245
        if (($res === null || $res->mode === 'none') && file_exists($filename_orgn)) {
246
            unlink($filename_orgn);
247
        } elseif ($res !== null && $res->mode !== 'none') {
248
            // Запишем оригинальный файл.
249
            file_put_contents($filename_orgn, $data);
250
        }
251
252
        if ($res === null) {
253
            // Файл еще не зарегистрирован в базе. Сделаем это.
254
            $res = new CustomFiles();
255
            $res->writeAttribute('filepath', $filename);
256
            $res->writeAttribute('mode', 'none');
257
            $res->save();
258
        } elseif ($res->mode === 'append') {
259
            // Добавить к файлу.
260
            $data .= "\n\n";
261
            $data .= base64_decode((string)$res->content);
262
        } elseif ($res->mode === 'override') {
263
            // Переопределить файл.
264
            $data = base64_decode((string)$res->content);
265
        }
266
        file_put_contents($filename, $data);
267
    }
268
269
    /**
270
     * Пишем лог в базу данных.
271
     *
272
     * @param $app
273
     * @param $data_obj
274
     */
275
    public static function logMsgDb($app, $data_obj): void
276
    {
277
        try {
278
            $data = new CallEventsLogs();
279
            $data->writeAttribute('eventtime', date("Y-m-d H:i:s"));
280
            $data->writeAttribute('app', $app);
281
            $data->writeAttribute('datajson', json_encode($data_obj, JSON_UNESCAPED_SLASHES));
282
283
            if (is_array($data_obj) && isset($data_obj['linkedid'])) {
284
                $data->writeAttribute('linkedid', $data_obj['linkedid']);
285
            }
286
            $data->save();
287
        } catch (Throwable $e) {
288
            self::sysLogMsg(__METHOD__, $e->getMessage(), LOG_ERR);
289
        }
290
    }
291
292
    /**
293
     * Adds messages to Syslog.
294
     *
295
     * @param string $ident category, class, method
296
     * @param string $message log message
297
     * @param int $level log level https://docs.phalcon.io/4.0/en/logger#constants
298
     *
299
     */
300
    public static function sysLogMsg(string $ident, string $message, $level = LOG_WARNING): void
301
    {
302
        /** @var \Phalcon\Logger $logger */
303
        $logger = Di::getDefault()->getShared(LoggerProvider::SERVICE_NAME);
304
        $logger->log($level, "{$message} on {$ident}" );
305
    }
306
307
    /**
308
     * Возвращает текущую дату в виде строки с точностью до милисекунд.
309
     *
310
     * @return string
311
     */
312
    public static function getNowDate(): ?string
313
    {
314
        $result = null;
315
        try {
316
            $d      = new DateTime();
317
            $result = $d->format("Y-m-d H:i:s.v");
318
        } catch (Exception $e) {
319
            unset($e);
320
        }
321
322
        return $result;
323
    }
324
325
    /**
326
     * Получает расширение файла.
327
     *
328
     * @param        $filename
329
     *
330
     * @return mixed
331
     */
332
    public static function getExtensionOfFile($filename)
333
    {
334
        $path_parts = pathinfo($filename);
335
336
        return $path_parts['extension'] ?? '';
337
    }
338
339
    /**
340
     * Удаляет расширение файла.
341
     *
342
     * @param        $filename
343
     * @param string $delimiter
344
     *
345
     * @return string
346
     */
347
    public static function trimExtensionForFile($filename, $delimiter = '.'): string
348
    {
349
        // Отсечем расширение файла.
350
        $tmp_arr = explode((string)$delimiter, $filename);
351
        if (count($tmp_arr) > 1) {
352
            unset($tmp_arr[count($tmp_arr) - 1]);
353
            $filename = implode((string)$delimiter, $tmp_arr);
354
        }
355
356
        return $filename;
357
    }
358
359
    /**
360
     * Получаем размер файла / директории.
361
     *
362
     * @param $filename
363
     *
364
     * @return float
365
     */
366
    public static function getSizeOfFile($filename): float
367
    {
368
        $result = 0;
369
        if (file_exists($filename)) {
370
            $duPath  = self::which('du');
371
            $awkPath = self::which('awk');
372
            Processes::mwExec("{$duPath} -d 0 -k '{$filename}' | {$awkPath}  '{ print $1}'", $out);
373
            $time_str = implode($out);
374
            preg_match_all('/^\d+$/', $time_str, $matches, PREG_SET_ORDER, 0);
375
            if (count($matches) > 0) {
376
                $result = round(1 * $time_str / 1024, 2);
377
            }
378
        }
379
380
        return $result;
381
    }
382
383
    /**
384
     * Return full path to executable binary
385
     *
386
     * @param string $cmd - name of file
387
     *
388
     * @return string
389
     */
390
    public static function which(string $cmd): string
391
    {
392
        global $_ENV;
393
        if (array_key_exists('PATH', $_ENV)) {
394
            $binaryFolders = $_ENV['PATH'];
395
396
            foreach (explode(':', $binaryFolders) as $path) {
397
                if (is_executable("{$path}/{$cmd}")) {
398
                    return "{$path}/{$cmd}";
399
                }
400
            }
401
        }
402
        $binaryFolders =
403
            [
404
                '/bin',
405
                '/sbin',
406
                '/usr/bin',
407
                '/usr/sbin',
408
                '/usr/local/bin',
409
                '/usr/local/sbin',
410
            ];
411
        foreach ($binaryFolders as $path) {
412
            if (is_executable("{$path}/{$cmd}")) {
413
                return "{$path}/{$cmd}";
414
            }
415
        }
416
417
        return $cmd;
418
    }
419
420
    /**
421
     * DEPRICATED
422
     * Executes command exec().
423
     *
424
     * @param $command
425
     * @param $outArr
426
     * @param $retVal
427
     *
428
     * @return int
429
     */
430
    public static function mwExec($command, &$outArr = null, &$retVal = null): int
431
    {
432
        self::sysLogMsg('Util', 'Deprecated call ' . __METHOD__ . ' from ' . static::class, LOG_DEBUG);
433
434
        return Processes::mwExec($command, $outArr, $retVal);
435
    }
436
437
    /**
438
     * Устанавливаем шрифт для консоли.
439
     */
440
    public static function setCyrillicFont(): void
441
    {
442
        $setfontPath = self::which('setfont');
443
        Processes::mwExec("{$setfontPath} /usr/share/consolefonts/Cyr_a8x16.psfu.gz 2>/dev/null");
444
    }
445
446
    /**
447
     * Получить перевод строки текста.
448
     *
449
     * @param $text
450
     *
451
     * @return mixed
452
     */
453
    public static function translate($text)
454
    {
455
        $di = Di::getDefault();
456
        if ($di !== null) {
457
            return $di->getShared('translation')->_($text);
458
        } else {
459
            return $text;
460
        }
461
    }
462
463
    /**
464
     *
465
     * Delete a directory RECURSIVELY
466
     *
467
     * @param string $dir - directory path
468
     *
469
     * @link http://php.net/manual/en/function.rmdir.php
470
     */
471
    public static function rRmDir(string $dir): void
472
    {
473
        if (is_dir($dir)) {
474
            $objects = scandir($dir);
475
            foreach ($objects as $object) {
476
                if ($object != "." && $object != "..") {
477
                    if (filetype($dir . "/" . $object) == "dir") {
478
                        self::rRmDir($dir . "/" . $object);
479
                    } else {
480
                        unlink($dir . "/" . $object);
481
                    }
482
                }
483
            }
484
            if ($objects !== false) {
485
                reset($objects);
486
            }
487
            rmdir($dir);
488
        }
489
    }
490
491
    /**
492
     * Генерация сертификата средствами openssl.
493
     *
494
     * @param ?array $options
495
     * @param ?array $config_args_pkey
496
     * @param ?array $config_args_csr
497
     *
498
     * @return array
499
     */
500
    public static function generateSslCert($options = null, $config_args_pkey = null, $config_args_csr = null): array
501
    {
502
        // Инициализация настроек.
503
        if ( ! $options) {
504
            $options = [
505
                "countryName"            => 'RU',
506
                "stateOrProvinceName"    => 'Moscow',
507
                "localityName"           => 'Zelenograd',
508
                "organizationName"       => 'MIKO LLC',
509
                "organizationalUnitName" => 'Software development',
510
                "commonName"             => 'MIKO PBX',
511
                "emailAddress"           => '[email protected]',
512
            ];
513
        }
514
515
        if ( ! $config_args_csr) {
516
            $config_args_csr = ['digest_alg' => 'sha256'];
517
        }
518
519
        if ( ! $config_args_pkey) {
520
            $config_args_pkey = [
521
                "private_key_bits" => 2048,
522
                "private_key_type" => OPENSSL_KEYTYPE_RSA,
523
            ];
524
        }
525
526
        // Генерация ключей.
527
        $private_key = openssl_pkey_new($config_args_pkey);
528
        $csr         = openssl_csr_new($options, $private_key, $config_args_csr);
0 ignored issues
show
Bug introduced by
It seems like $private_key can also be of type resource; however, parameter $private_key of openssl_csr_new() does only seem to accept OpenSSLAsymmetricKey, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

528
        $csr         = openssl_csr_new($options, /** @scrutinizer ignore-type */ $private_key, $config_args_csr);
Loading history...
529
        $x509        = openssl_csr_sign($csr, null, $private_key, $days = 3650, $config_args_csr);
530
531
        // Экспорт ключей.
532
        openssl_x509_export($x509, $certout);
533
        openssl_pkey_export($private_key, $pkeyout);
534
        // echo $pkeyout; // -> WEBHTTPSPrivateKey
535
        // echo $certout; // -> WEBHTTPSPublicKey
536
        return ['PublicKey' => $certout, 'PrivateKey' => $pkeyout];
537
    }
538
539
    /**
540
     * @return bool
541
     */
542
    public static function isSystemctl(): bool
543
    {
544
        return (stripos(php_uname('v'), 'debian') !== false);
545
    }
546
547
    public static function isDocker(): bool
548
    {
549
        return file_exists('/.dockerenv');
550
    }
551
552
    /**
553
     * Выводить текстовое сообщение "done" подсвечивает зеленым цветом.
554
     */
555
    public static function echoDone(bool $result=true): void
556
    {
557
        if($result === false){
558
            echo "\033[31;1mFAIL\033[0m \n";
559
        }else{
560
            echo "\033[32;1mDONE\033[0m \n";
561
        }
562
    }
563
564
    /**
565
     * Создание символической ссылки, если необходимо.
566
     *
567
     * @param $target
568
     * @param $link
569
     * @param bool $isFile
570
     *
571
     * @return bool
572
     */
573
    public static function createUpdateSymlink($target, $link, $isFile=false): bool
574
    {
575
        $need_create_link = true;
576
        if (is_link($link)) {
577
            $old_target       = readlink($link);
578
            $need_create_link = ($old_target != $target);
579
            // Если необходимо, удаляем старую ссылку.
580
            if ($need_create_link) {
581
                $cpPath = self::which('cp');
582
                Processes::mwExec("{$cpPath} {$old_target}/* {$target}");
583
                unlink($link);
584
            }
585
        } elseif (is_dir($link)) {
586
            // Это должна быть именно ссылка. Файл удаляем.
587
            rmdir($link);
588
        } elseif (file_exists($link)) {
589
            // Это должна быть именно ссылка. Файл удаляем.
590
            unlink($link);
591
        }
592
        if($isFile === false){
593
            self::mwMkdir($target);
594
        }
595
        if ($need_create_link) {
596
            $lnPath = self::which('ln');
597
            Processes::mwExec("{$lnPath} -s {$target}  {$link}");
598
        }
599
600
        return $need_create_link;
601
    }
602
603
    /**
604
     * Create folder if it not exist.
605
     *
606
     * @param      $parameters string one or multiple paths separated by space
607
     *
608
     * @param bool $addWWWRights
609
     *
610
     * @return bool
611
     */
612
    public static function mwMkdir(string $parameters, bool $addWWWRights = false): bool
613
    {
614
        $result = true;
615
        if (posix_getuid() === 0) {
616
            $arrPaths = explode(' ', $parameters);
617
            if (count($arrPaths) > 0) {
618
                foreach ($arrPaths as $path) {
619
                    if ( ! empty($path)
620
                        && ! file_exists($path)
621
                        && ! mkdir($path, 0755, true)
622
                        && ! is_dir($path)) {
623
                        $result = false;
624
                        self::sysLogMsg('Util', 'Error on create folder ' . $path, LOG_ERR);
625
                    }
626
                    if ($addWWWRights) {
627
                        self::addRegularWWWRights($path);
628
                    }
629
                }
630
            }
631
        }
632
633
        return $result;
634
    }
635
636
    /**
637
     * Apply regular rights for folders and files
638
     *
639
     * @param $folder
640
     */
641
    public static function addRegularWWWRights($folder): void
642
    {
643
        if (posix_getuid() === 0) {
644
            $findPath  = self::which('find');
645
            $chownPath = self::which('chown');
646
            $chmodPath = self::which('chmod');
647
            Processes::mwExec("{$findPath} {$folder} -type d -exec {$chmodPath} 755 {} \;");
648
            Processes::mwExec("{$findPath} {$folder} -type f -exec {$chmodPath} 644 {} \;");
649
            Processes::mwExec("{$chownPath} -R www:www {$folder}");
650
        }
651
    }
652
653
    /**
654
     * Print message and write it to syslog
655
     *
656
     * @param $message
657
     */
658
    public static function echoWithSyslog($message): void
659
    {
660
        echo $message;
661
        self::sysLogMsg(static::class, $message, LOG_INFO);
662
    }
663
664
    /**
665
     * Apply executable rights for files
666
     *
667
     * @param $folder
668
     */
669
    public static function addExecutableRights($folder): void
670
    {
671
        if (posix_getuid() === 0) {
672
            $findPath  = self::which('find');
673
            $chmodPath = self::which('chmod');
674
            Processes::mwExec("{$findPath} {$folder} -type f -exec {$chmodPath} 755 {} \;");
675
        }
676
    }
677
678
    /**
679
     * Разбор INI конфига
680
     *
681
     * @param string $manual_attributes
682
     *
683
     * @return array
684
     */
685
    public static function parseIniSettings(string $manual_attributes): array
686
    {
687
        $tmp_data = base64_decode($manual_attributes);
688
        if (base64_encode($tmp_data) === $manual_attributes) {
689
            $manual_attributes = $tmp_data;
690
        }
691
        unset($tmp_data);
692
        // TRIMMING
693
        $tmp_arr = explode("\n", $manual_attributes);
694
        foreach ($tmp_arr as &$row) {
695
            $row = trim($row);
696
            $pos = strpos($row, ']');
697
            if ($pos !== false && strpos($row, '[') === 0) {
698
                $row = "\n" . substr($row, 0, $pos);
699
            }
700
        }
701
        unset($row);
702
        $manual_attributes = implode("\n", $tmp_arr);
703
        // TRIMMING END
704
705
        $manual_data = [];
706
        $sections    = explode("\n[", str_replace(']', '', $manual_attributes));
707
        foreach ($sections as $section) {
708
            $data_rows    = explode("\n", trim($section));
709
            $section_name = trim($data_rows[0] ?? '');
710
            if ( ! empty($section_name)) {
711
                unset($data_rows[0]);
712
                $manual_data[$section_name] = [];
713
                foreach ($data_rows as $row) {
714
                    if (strpos($row, '=') === false) {
715
                        continue;
716
                    }
717
                    $key       = '';
718
                    $arr_value = explode('=', $row);
719
                    if (count($arr_value) > 1) {
720
                        $key = trim($arr_value[0]);
721
                        unset($arr_value[0]);
722
                        $value = trim(implode('=', $arr_value));
723
                    }
724
                    if (empty($value) || empty($key)) {
725
                        continue;
726
                    }
727
                    $manual_data[$section_name][$key] = $value;
728
                }
729
            }
730
        }
731
732
        return $manual_data;
733
    }
734
735
    /**
736
     * Converts multidimensional array into single array
737
     *
738
     * @param $array
739
     *
740
     * @return array
741
     */
742
    public static function flattenArray(array $array)
743
    {
744
        $result = [];
745
        foreach ($array as $value) {
746
            if (is_array($value)) {
747
                $result = array_merge($result, self::flattenArray($value));
748
            } else {
749
                $result[] = $value;
750
            }
751
        }
752
753
        return $result;
754
    }
755
756
    /**
757
     * Try to find full path to php file by class name
758
     *
759
     * @param $className
760
     *
761
     * @return string|null
762
     */
763
    public static function getFilePathByClassName($className): ?string
764
    {
765
        $filename = null;
766
        try {
767
            $reflection = new ReflectionClass($className);
768
            $filename   = $reflection->getFileName();
769
        } catch (ReflectionException $exception) {
770
            self::sysLogMsg(__METHOD__, 'ReflectionException ' . $exception->getMessage(), LOG_ERR);
771
        }
772
773
        return $filename;
774
    }
775
776
    /**
777
     * DEPRICATED
778
     * Возвращает PID процесса по его имени.
779
     *
780
     * @param        $name
781
     * @param string $exclude
782
     *
783
     * @return string
784
     */
785
    public static function getPidOfProcess($name, $exclude = ''): string
786
    {
787
        self::sysLogMsg('Util', 'Deprecated call ' . __METHOD__ . ' from ' . static::class, LOG_DEBUG);
788
789
        return Processes::getPidOfProcess($name, $exclude);
790
    }
791
792
    /**
793
     * DEPRICATED
794
     * Manages a daemon/worker process
795
     * Returns process statuses by name of it
796
     *
797
     * @param $cmd
798
     * @param $param
799
     * @param $proc_name
800
     * @param $action
801
     * @param $out_file
802
     *
803
     * @return array | bool
804
     */
805
    public static function processWorker($cmd, $param, $proc_name, $action, $out_file = '/dev/null')
806
    {
807
        self::sysLogMsg('Util', 'Deprecated call ' . __METHOD__ . ' from ' . static::class, LOG_DEBUG);
808
809
        return Processes::processWorker($cmd, $param, $proc_name, $action, $out_file);
810
    }
811
812
    /**
813
     * DEPRICATED
814
     * Process PHP workers
815
     *
816
     * @param string $className
817
     * @param string $param
818
     * @param string $action
819
     */
820
    public static function processPHPWorker(
821
        string $className,
822
        string $param = 'start',
823
        string $action = 'restart'
824
    ): void {
825
        self::sysLogMsg('Util', 'Deprecated call ' . __METHOD__ . ' from ' . static::class, LOG_DEBUG);
826
        Processes::processPHPWorker($className, $param, $action);
827
    }
828
829
    /**
830
     * DEPRICATED
831
     * Kills process/daemon by name
832
     *
833
     * @param $procName
834
     *
835
     * @return int|null
836
     */
837
    public static function killByName($procName): ?int
838
    {
839
        self::sysLogMsg('Util', 'Deprecated call ' . __METHOD__ . ' from ' . static::class, LOG_DEBUG);
840
841
        return Processes::killByName($procName);
842
    }
843
844
    /**
845
     * DEPRICATED
846
     * Executes command exec() as background process.
847
     *
848
     * @param $command
849
     * @param $out_file
850
     * @param $sleep_time
851
     */
852
    public static function mwExecBg($command, $out_file = '/dev/null', $sleep_time = 0): void
853
    {
854
        self::sysLogMsg('Util', 'Deprecated call ' . __METHOD__ . ' from ' . static::class, LOG_DEBUG);
855
        Processes::mwExecBg($command, $out_file, $sleep_time);
856
    }
857
858
    /**
859
     * DEPRICATED
860
     * Executes command exec() as background process with an execution timeout.
861
     *
862
     * @param        $command
863
     * @param int    $timeout
864
     * @param string $logname
865
     */
866
    public static function mwExecBgWithTimeout($command, $timeout = 4, $logname = '/dev/null'): void
867
    {
868
        self::sysLogMsg('Util', 'Deprecated call ' . __METHOD__ . ' from ' . static::class, LOG_DEBUG);
869
        Processes::mwExecBgWithTimeout($command, $timeout, $logname);
870
    }
871
872
    /**
873
     * DEPRICATED
874
     * Executes multiple commands.
875
     *
876
     * @param        $arr_cmds
877
     * @param array  $out
878
     * @param string $logname
879
     */
880
    public static function mwExecCommands($arr_cmds, &$out = [], $logname = ''): void
881
    {
882
        self::sysLogMsg('Util', 'Deprecated call ' . __METHOD__ . ' from ' . static::class, LOG_DEBUG);
883
        Processes::mwExecCommands($arr_cmds, $out, $logname);
884
    }
885
886
    /**
887
     * Добавляем задачу для уведомлений.
888
     *
889
     * @param string $tube
890
     * @param        $data
891
     */
892
    public function addJobToBeanstalk(string $tube, $data): void
893
    {
894
        $queue = new BeanstalkClient($tube);
895
        $queue->publish(json_encode($data));
896
    }
897
898
899
}