Cancelled
Push — develop ( 93afd0...c67955 )
by Портнов
04:03
created

Util::getCountCols()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

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