| Total Complexity | 117 |
| Total Lines | 850 |
| Duplicated Lines | 0 % |
| Changes | 4 | ||
| Bugs | 0 | Features | 0 |
Complex classes like Util often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use Util, and based on these observations, apply Extract Interface, too.
| 1 | <?php |
||
| 23 | class Util |
||
| 24 | { |
||
| 25 | |||
| 26 | /** |
||
| 27 | * @param $options |
||
| 28 | * @param $manual_attributes |
||
| 29 | * @param $section |
||
| 30 | * |
||
| 31 | * @return string |
||
| 32 | */ |
||
| 33 | public static function overrideConfigurationArray($options, $manual_attributes, $section): string |
||
| 57 | } |
||
| 58 | |||
| 59 | /** |
||
| 60 | * Инициация телефонного звонка. |
||
| 61 | * |
||
| 62 | * @param $peer_number |
||
| 63 | * @param $peer_mobile |
||
| 64 | * @param $dest_number |
||
| 65 | * |
||
| 66 | * @return array |
||
| 67 | * @throws Exception |
||
| 68 | */ |
||
| 69 | public static function amiOriginate($peer_number, $peer_mobile, $dest_number): array |
||
| 70 | { |
||
| 71 | $am = self::getAstManager('off'); |
||
| 72 | $channel = 'Local/' . $peer_number . '@internal-originate'; |
||
| 73 | $context = 'all_peers'; |
||
| 74 | $IS_ORGNT = self::generateRandomString(); |
||
| 75 | $variable = "_IS_ORGNT={$IS_ORGNT},pt1c_cid={$dest_number},_extenfrom1c={$peer_number},__peer_mobile={$peer_mobile},_FROM_PEER={$peer_number}"; |
||
| 76 | |||
| 77 | return $am->Originate( |
||
| 78 | $channel, |
||
| 79 | $dest_number, |
||
| 80 | $context, |
||
| 81 | '1', |
||
| 82 | null, |
||
| 83 | null, |
||
| 84 | null, |
||
| 85 | null, |
||
| 86 | $variable, |
||
| 87 | null, |
||
| 88 | true |
||
| 89 | ); |
||
| 90 | } |
||
| 91 | |||
| 92 | /** |
||
| 93 | * Получаем объект менеджер asterisk. |
||
| 94 | * |
||
| 95 | * @param string $events |
||
| 96 | * |
||
| 97 | * @return AsteriskManager |
||
| 98 | */ |
||
| 99 | public static function getAstManager($events = 'on'): AsteriskManager |
||
| 100 | { |
||
| 101 | if ($events === 'on') { |
||
| 102 | $nameService = 'amiListner'; |
||
| 103 | } else { |
||
| 104 | $nameService = 'amiCommander'; |
||
| 105 | } |
||
| 106 | |||
| 107 | $di = Di::getDefault(); |
||
| 108 | $am = $di->getShared($nameService); |
||
| 109 | if (is_resource($am->socket)) { |
||
| 110 | return $am; |
||
| 111 | } |
||
| 112 | |||
| 113 | return $di->get($nameService); |
||
| 114 | } |
||
| 115 | |||
| 116 | /** |
||
| 117 | * Генератор произвольной строки. |
||
| 118 | * |
||
| 119 | * @param int $length |
||
| 120 | * |
||
| 121 | * @return string |
||
| 122 | */ |
||
| 123 | public static function generateRandomString($length = 10): string |
||
| 124 | { |
||
| 125 | $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; |
||
| 126 | $charactersLength = strlen($characters); |
||
| 127 | $randomString = ''; |
||
| 128 | for ($i = 0; $i < $length; $i++) { |
||
| 129 | try { |
||
| 130 | $randomString .= $characters[random_int(0, $charactersLength - 1)]; |
||
| 131 | } catch (Throwable $e) { |
||
| 132 | $randomString = ''; |
||
| 133 | } |
||
| 134 | } |
||
| 135 | |||
| 136 | return $randomString; |
||
| 137 | } |
||
| 138 | |||
| 139 | /** |
||
| 140 | * Json validate |
||
| 141 | * |
||
| 142 | * @param $jsonString |
||
| 143 | * |
||
| 144 | * @return bool |
||
| 145 | */ |
||
| 146 | public static function isJson($jsonString): bool |
||
| 147 | { |
||
| 148 | json_decode($jsonString, true); |
||
| 149 | |||
| 150 | return (json_last_error() === JSON_ERROR_NONE); |
||
| 151 | } |
||
| 152 | |||
| 153 | /** |
||
| 154 | * Возвращает размер файла в Мб. |
||
| 155 | * |
||
| 156 | * @param $filename |
||
| 157 | * |
||
| 158 | * @return float|int |
||
| 159 | */ |
||
| 160 | public static function mFileSize($filename) |
||
| 161 | { |
||
| 162 | $size = 0; |
||
| 163 | if (file_exists($filename)) { |
||
| 164 | $tmp_size = filesize($filename); |
||
| 165 | if ($tmp_size !== false) { |
||
| 166 | // Получим размер в Мб. |
||
| 167 | $size = $tmp_size; |
||
| 168 | } |
||
| 169 | } |
||
| 170 | |||
| 171 | return $size; |
||
| 172 | } |
||
| 173 | |||
| 174 | /** |
||
| 175 | * Возвращает указанное количество X. |
||
| 176 | * |
||
| 177 | * @param $length |
||
| 178 | * |
||
| 179 | * @return string |
||
| 180 | */ |
||
| 181 | public static function getExtensionX($length): string |
||
| 182 | { |
||
| 183 | $extension = ''; |
||
| 184 | for ($i = 0; $i < $length; $i++) { |
||
| 185 | $extension .= 'X'; |
||
| 186 | } |
||
| 187 | |||
| 188 | return $extension; |
||
| 189 | } |
||
| 190 | |||
| 191 | /** |
||
| 192 | * Проверяет существование файла. |
||
| 193 | * |
||
| 194 | * @param $filename |
||
| 195 | * |
||
| 196 | * @return bool |
||
| 197 | */ |
||
| 198 | public static function recFileExists($filename): ?bool |
||
| 199 | { |
||
| 200 | return (file_exists($filename) && filesize($filename) > 0); |
||
| 201 | } |
||
| 202 | |||
| 203 | /** |
||
| 204 | * Если переданный параметр - число, то будет возвращена дата. |
||
| 205 | * |
||
| 206 | * @param $data |
||
| 207 | * |
||
| 208 | * @return string |
||
| 209 | */ |
||
| 210 | public static function numberToDate($data): string |
||
| 211 | { |
||
| 212 | $re_number = '/^\d+.\d+$/'; |
||
| 213 | preg_match_all($re_number, $data, $matches, PREG_SET_ORDER, 0); |
||
| 214 | if (count($matches) > 0) { |
||
| 215 | $data = date('Y.m.d-H:i:s', $data); |
||
| 216 | } |
||
| 217 | |||
| 218 | return $data; |
||
| 219 | } |
||
| 220 | |||
| 221 | /** |
||
| 222 | * Записывает данные в файл. |
||
| 223 | * |
||
| 224 | * @param $filename |
||
| 225 | * @param $data |
||
| 226 | */ |
||
| 227 | public static function fileWriteContent($filename, $data): void |
||
| 228 | { |
||
| 229 | /** @var CustomFiles $res */ |
||
| 230 | $res = CustomFiles::findFirst("filepath = '{$filename}'"); |
||
| 231 | |||
| 232 | $filename_orgn = "{$filename}.orgn"; |
||
| 233 | if (($res === null || $res->mode === 'none') && file_exists($filename_orgn)) { |
||
| 234 | unlink($filename_orgn); |
||
| 235 | } elseif ($res !== null && $res->mode !== 'none') { |
||
| 236 | // Запишем оригинальный файл. |
||
| 237 | file_put_contents($filename_orgn, $data); |
||
| 238 | } |
||
| 239 | |||
| 240 | if ($res === null) { |
||
| 241 | // Файл еще не зарегистрирован в базе. Сделаем это. |
||
| 242 | $res = new CustomFiles(); |
||
| 243 | $res->writeAttribute('filepath', $filename); |
||
| 244 | $res->writeAttribute('mode', 'none'); |
||
| 245 | $res->save(); |
||
| 246 | } elseif ($res->mode === 'append') { |
||
| 247 | // Добавить к файлу. |
||
| 248 | $data .= "\n\n"; |
||
| 249 | $data .= base64_decode($res->content); |
||
| 250 | } elseif ($res->mode === 'override') { |
||
| 251 | // Переопределить файл. |
||
| 252 | $data = base64_decode($res->content); |
||
| 253 | } |
||
| 254 | file_put_contents($filename, $data); |
||
| 255 | } |
||
| 256 | |||
| 257 | /** |
||
| 258 | * Пишем лог в базу данных. |
||
| 259 | * |
||
| 260 | * @param $app |
||
| 261 | * @param $data_obj |
||
| 262 | */ |
||
| 263 | public static function logMsgDb($app, $data_obj): void |
||
| 264 | { |
||
| 265 | try { |
||
| 266 | $data = new CallEventsLogs(); |
||
| 267 | $data->writeAttribute('eventtime', date("Y-m-d H:i:s")); |
||
| 268 | $data->writeAttribute('app', $app); |
||
| 269 | $data->writeAttribute('datajson', json_encode($data_obj, JSON_UNESCAPED_SLASHES)); |
||
| 270 | |||
| 271 | if (is_array($data_obj) && isset($data_obj['linkedid'])) { |
||
| 272 | $data->writeAttribute('linkedid', $data_obj['linkedid']); |
||
| 273 | } |
||
| 274 | $data->save(); |
||
| 275 | } catch (Exception $e) { |
||
| 276 | self::sysLogMsg('logMsgDb', $e->getMessage()); |
||
| 277 | } |
||
| 278 | } |
||
| 279 | |||
| 280 | /** |
||
| 281 | * Add message to Syslog. |
||
| 282 | * |
||
| 283 | * @param $log_name |
||
| 284 | * @param $text |
||
| 285 | * @param ?int $level |
||
| 286 | * @param ?int $facility |
||
| 287 | */ |
||
| 288 | public static function sysLogMsg($log_name, $text, $level = null, $facility = LOG_AUTH): void |
||
| 289 | { |
||
| 290 | $level = ($level === null) ? LOG_WARNING : $level; |
||
| 291 | openlog("$log_name", LOG_PID | LOG_PERROR, $facility); |
||
| 292 | syslog($level, "$text"); |
||
| 293 | closelog(); |
||
| 294 | } |
||
| 295 | |||
| 296 | /** |
||
| 297 | * Возвращает текущую дату в виде строки с точностью до милисекунд. |
||
| 298 | * |
||
| 299 | * @return string |
||
| 300 | */ |
||
| 301 | public static function getNowDate(): ?string |
||
| 302 | { |
||
| 303 | $result = null; |
||
| 304 | try { |
||
| 305 | $d = new DateTime(); |
||
| 306 | $result = $d->format("Y-m-d H:i:s.v"); |
||
| 307 | } catch (Exception $e) { |
||
| 308 | unset($e); |
||
| 309 | } |
||
| 310 | |||
| 311 | return $result; |
||
| 312 | } |
||
| 313 | |||
| 314 | /** |
||
| 315 | * Получает расширение файла. |
||
| 316 | * |
||
| 317 | * @param $filename |
||
| 318 | * |
||
| 319 | * @return mixed |
||
| 320 | */ |
||
| 321 | public static function getExtensionOfFile($filename) |
||
| 322 | { |
||
| 323 | $path_parts = pathinfo($filename); |
||
| 324 | |||
| 325 | return $path_parts['extension'] ?? ''; |
||
| 326 | } |
||
| 327 | |||
| 328 | /** |
||
| 329 | * Удаляет расширение файла. |
||
| 330 | * |
||
| 331 | * @param $filename |
||
| 332 | * @param string $delimiter |
||
| 333 | * |
||
| 334 | * @return string |
||
| 335 | */ |
||
| 336 | public static function trimExtensionForFile($filename, $delimiter = '.'): string |
||
| 337 | { |
||
| 338 | // Отсечем расширение файла. |
||
| 339 | $tmp_arr = explode((string)$delimiter, $filename); |
||
| 340 | if (count($tmp_arr) > 1) { |
||
| 341 | unset($tmp_arr[count($tmp_arr) - 1]); |
||
| 342 | $filename = implode((string)$delimiter, $tmp_arr); |
||
| 343 | } |
||
| 344 | |||
| 345 | return $filename; |
||
| 346 | } |
||
| 347 | |||
| 348 | /** |
||
| 349 | * Получаем размер файла / директории. |
||
| 350 | * |
||
| 351 | * @param $filename |
||
| 352 | * |
||
| 353 | * @return float |
||
| 354 | */ |
||
| 355 | public static function getSizeOfFile($filename): float |
||
| 356 | { |
||
| 357 | $result = 0; |
||
| 358 | if (file_exists($filename)) { |
||
| 359 | $duPath = self::which('du'); |
||
| 360 | $awkPath = self::which('awk'); |
||
| 361 | Processes::mwExec("{$duPath} -d 0 -k '{$filename}' | {$awkPath} '{ print $1}'", $out); |
||
| 362 | $time_str = implode($out); |
||
| 363 | preg_match_all('/^\d+$/', $time_str, $matches, PREG_SET_ORDER, 0); |
||
| 364 | if (count($matches) > 0) { |
||
| 365 | $result = round(1 * $time_str / 1024, 2); |
||
| 366 | } |
||
| 367 | } |
||
| 368 | |||
| 369 | return $result; |
||
| 370 | } |
||
| 371 | |||
| 372 | /** |
||
| 373 | * Return full path to executable binary |
||
| 374 | * |
||
| 375 | * @param string $cmd - name of file |
||
| 376 | * |
||
| 377 | * @return string |
||
| 378 | */ |
||
| 379 | public static function which(string $cmd): string |
||
| 380 | { |
||
| 381 | global $_ENV; |
||
| 382 | if (array_key_exists('PATH', $_ENV)) { |
||
| 383 | $binaryFolders = $_ENV['PATH']; |
||
| 384 | |||
| 385 | foreach (explode(':', $binaryFolders) as $path) { |
||
| 386 | if (is_executable("{$path}/{$cmd}")) { |
||
| 387 | return "{$path}/{$cmd}"; |
||
| 388 | } |
||
| 389 | } |
||
| 390 | } |
||
| 391 | $binaryFolders = |
||
| 392 | [ |
||
| 393 | '/bin', |
||
| 394 | '/sbin', |
||
| 395 | '/usr/bin', |
||
| 396 | '/usr/sbin', |
||
| 397 | '/usr/local/bin', |
||
| 398 | '/usr/local/sbin', |
||
| 399 | ]; |
||
| 400 | foreach ($binaryFolders as $path) { |
||
| 401 | if (is_executable("{$path}/{$cmd}")) { |
||
| 402 | return "{$path}/{$cmd}"; |
||
| 403 | } |
||
| 404 | } |
||
| 405 | |||
| 406 | return $cmd; |
||
| 407 | } |
||
| 408 | |||
| 409 | /** |
||
| 410 | * DEPRICATED |
||
| 411 | * Executes command exec(). |
||
| 412 | * |
||
| 413 | * @param $command |
||
| 414 | * @param $outArr |
||
| 415 | * @param $retVal |
||
| 416 | * |
||
| 417 | * @return int |
||
| 418 | */ |
||
| 419 | public static function mwExec($command, &$outArr = null, &$retVal = null): int |
||
| 420 | { |
||
| 421 | self::sysLogMsg('Util', 'Deprecated call ' . __METHOD__ . ' from ' . static::class); |
||
| 422 | |||
| 423 | return Processes::mwExec($command, $outArr, $retVal); |
||
| 424 | } |
||
| 425 | |||
| 426 | /** |
||
| 427 | * Устанавливаем шрифт для консоли. |
||
| 428 | */ |
||
| 429 | public static function setCyrillicFont(): void |
||
| 430 | { |
||
| 431 | $setfontPath = self::which('setfont'); |
||
| 432 | Processes::mwExec("{$setfontPath} /usr/share/consolefonts/Cyr_a8x16.psfu.gz 2>/dev/null"); |
||
| 433 | } |
||
| 434 | |||
| 435 | /** |
||
| 436 | * Получить перевод строки текста. |
||
| 437 | * |
||
| 438 | * @param $text |
||
| 439 | * |
||
| 440 | * @return mixed |
||
| 441 | */ |
||
| 442 | public static function translate($text) |
||
| 443 | { |
||
| 444 | $di = Di::getDefault(); |
||
| 445 | if ($di !== null) { |
||
| 446 | return $di->getShared('translation')->_($text); |
||
| 447 | } else { |
||
| 448 | return $text; |
||
| 449 | } |
||
| 450 | } |
||
| 451 | |||
| 452 | /** |
||
| 453 | * |
||
| 454 | * Delete a directory RECURSIVELY |
||
| 455 | * |
||
| 456 | * @param string $dir - directory path |
||
| 457 | * |
||
| 458 | * @link http://php.net/manual/en/function.rmdir.php |
||
| 459 | */ |
||
| 460 | public static function rRmDir(string $dir): void |
||
| 461 | { |
||
| 462 | if (is_dir($dir)) { |
||
| 463 | $objects = scandir($dir); |
||
| 464 | foreach ($objects as $object) { |
||
| 465 | if ($object != "." && $object != "..") { |
||
| 466 | if (filetype($dir . "/" . $object) == "dir") { |
||
| 467 | self::rRmDir($dir . "/" . $object); |
||
| 468 | } else { |
||
| 469 | unlink($dir . "/" . $object); |
||
| 470 | } |
||
| 471 | } |
||
| 472 | } |
||
| 473 | if ($objects !== false) { |
||
| 474 | reset($objects); |
||
| 475 | } |
||
| 476 | rmdir($dir); |
||
| 477 | } |
||
| 478 | } |
||
| 479 | |||
| 480 | /** |
||
| 481 | * Генерация сертификата средствами openssl. |
||
| 482 | * |
||
| 483 | * @param ?array $options |
||
| 484 | * @param ?array $config_args_pkey |
||
| 485 | * @param ?array $config_args_csr |
||
| 486 | * |
||
| 487 | * @return array |
||
| 488 | */ |
||
| 489 | public static function generateSslCert($options = null, $config_args_pkey = null, $config_args_csr = null): array |
||
| 490 | { |
||
| 491 | // Инициализация настроек. |
||
| 492 | if ( ! $options) { |
||
| 493 | $options = [ |
||
| 494 | "countryName" => 'RU', |
||
| 495 | "stateOrProvinceName" => 'Moscow', |
||
| 496 | "localityName" => 'Zelenograd', |
||
| 497 | "organizationName" => 'MIKO LLC', |
||
| 498 | "organizationalUnitName" => 'Software development', |
||
| 499 | "commonName" => 'MIKO PBX', |
||
| 500 | "emailAddress" => '[email protected]', |
||
| 501 | ]; |
||
| 502 | } |
||
| 503 | |||
| 504 | if ( ! $config_args_csr) { |
||
| 505 | $config_args_csr = ['digest_alg' => 'sha256']; |
||
| 506 | } |
||
| 507 | |||
| 508 | if ( ! $config_args_pkey) { |
||
| 509 | $config_args_pkey = [ |
||
| 510 | "private_key_bits" => 2048, |
||
| 511 | "private_key_type" => OPENSSL_KEYTYPE_RSA, |
||
| 512 | ]; |
||
| 513 | } |
||
| 514 | |||
| 515 | // Генерация ключей. |
||
| 516 | $private_key = openssl_pkey_new($config_args_pkey); |
||
| 517 | $csr = openssl_csr_new($options, $private_key, $config_args_csr); |
||
| 518 | $x509 = openssl_csr_sign($csr, null, $private_key, $days = 3650, $config_args_csr); |
||
| 519 | |||
| 520 | // Экспорт ключей. |
||
| 521 | openssl_x509_export($x509, $certout); |
||
| 522 | openssl_pkey_export($private_key, $pkeyout); |
||
| 523 | // echo $pkeyout; // -> WEBHTTPSPrivateKey |
||
| 524 | // echo $certout; // -> WEBHTTPSPublicKey |
||
| 525 | return ['PublicKey' => $certout, 'PrivateKey' => $pkeyout]; |
||
| 526 | } |
||
| 527 | |||
| 528 | /** |
||
| 529 | * @return bool |
||
| 530 | */ |
||
| 531 | public static function isSystemctl(): bool |
||
| 532 | { |
||
| 533 | return (stripos(php_uname('v'), 'debian') !== false); |
||
| 534 | } |
||
| 535 | |||
| 536 | /** |
||
| 537 | * Выводить текстовое сообщение "done" подсвечивает зеленым цветом. |
||
| 538 | */ |
||
| 539 | public static function echoGreenDone(): void |
||
| 540 | { |
||
| 541 | echo "\033[32;1mdone\033[0m \n"; |
||
| 542 | } |
||
| 543 | |||
| 544 | /** |
||
| 545 | * Создание символической ссылки, если необходимо. |
||
| 546 | * |
||
| 547 | * @param $target |
||
| 548 | * @param $link |
||
| 549 | * |
||
| 550 | * @return bool |
||
| 551 | */ |
||
| 552 | public static function createUpdateSymlink($target, $link): bool |
||
| 553 | { |
||
| 554 | $need_create_link = true; |
||
| 555 | if (is_link($link)) { |
||
| 556 | $old_target = readlink($link); |
||
| 557 | $need_create_link = ($old_target != $target); |
||
| 558 | // Если необходимо, удаляем старую ссылку. |
||
| 559 | if ($need_create_link) { |
||
| 560 | $cpPath = self::which('cp'); |
||
| 561 | Processes::mwExec("{$cpPath} {$old_target}/* {$target}"); |
||
| 562 | unlink($link); |
||
| 563 | } |
||
| 564 | } elseif (is_dir($link)) { |
||
| 565 | // Это должна быть именно ссылка. Файл удаляем. |
||
| 566 | rmdir($link); |
||
| 567 | } elseif (file_exists($link)) { |
||
| 568 | // Это должна быть именно ссылка. Файл удаляем. |
||
| 569 | unlink($link); |
||
| 570 | } |
||
| 571 | self::mwMkdir($target); |
||
| 572 | if ($need_create_link) { |
||
| 573 | $lnPath = self::which('ln'); |
||
| 574 | Processes::mwExec("{$lnPath} -s {$target} {$link}"); |
||
| 575 | } |
||
| 576 | |||
| 577 | return $need_create_link; |
||
| 578 | } |
||
| 579 | |||
| 580 | /** |
||
| 581 | * Create folder if it not exist. |
||
| 582 | * |
||
| 583 | * @param $parameters string one or multiple paths separated by space |
||
| 584 | * |
||
| 585 | * @param bool $addWWWRights |
||
| 586 | * |
||
| 587 | * @return bool |
||
| 588 | */ |
||
| 589 | public static function mwMkdir(string $parameters, bool $addWWWRights = false): bool |
||
| 590 | { |
||
| 591 | $result = true; |
||
| 592 | if (posix_getuid() === 0) { |
||
| 593 | $arrPaths = explode(' ', $parameters); |
||
| 594 | if (count($arrPaths) > 0) { |
||
| 595 | foreach ($arrPaths as $path) { |
||
| 596 | if ( ! empty($path) |
||
| 597 | && ! file_exists($path) |
||
| 598 | && ! mkdir($path, 0755, true) |
||
| 599 | && ! is_dir($path)) { |
||
| 600 | $result = false; |
||
| 601 | self::sysLogMsg('Util', 'Error on create folder ' . $path); |
||
| 602 | } |
||
| 603 | if ($addWWWRights) { |
||
| 604 | self::addRegularWWWRights($path); |
||
| 605 | } |
||
| 606 | } |
||
| 607 | } |
||
| 608 | } |
||
| 609 | |||
| 610 | return $result; |
||
| 611 | } |
||
| 612 | |||
| 613 | /** |
||
| 614 | * Apply regular rights for folders and files |
||
| 615 | * |
||
| 616 | * @param $folder |
||
| 617 | */ |
||
| 618 | public static function addRegularWWWRights($folder): void |
||
| 619 | { |
||
| 620 | if (posix_getuid() === 0) { |
||
| 621 | $findPath = self::which('find'); |
||
| 622 | $chownPath = self::which('chown'); |
||
| 623 | $chmodPath = self::which('chmod'); |
||
| 624 | Processes::mwExec("{$findPath} {$folder} -type d -exec {$chmodPath} 755 {} \;"); |
||
| 625 | Processes::mwExec("{$findPath} {$folder} -type f -exec {$chmodPath} 644 {} \;"); |
||
| 626 | Processes::mwExec("{$chownPath} -R www:www {$folder}"); |
||
| 627 | } |
||
| 628 | } |
||
| 629 | |||
| 630 | /** |
||
| 631 | * Print message and write it to syslog |
||
| 632 | * |
||
| 633 | * @param $message |
||
| 634 | */ |
||
| 635 | public static function echoWithSyslog($message): void |
||
| 636 | { |
||
| 637 | echo $message; |
||
| 638 | self::sysLogMsg(static::class, $message, LOG_INFO); |
||
| 639 | } |
||
| 640 | |||
| 641 | /** |
||
| 642 | * Apply executable rights for files |
||
| 643 | * |
||
| 644 | * @param $folder |
||
| 645 | */ |
||
| 646 | public static function addExecutableRights($folder): void |
||
| 647 | { |
||
| 648 | if (posix_getuid() === 0) { |
||
| 649 | $findPath = self::which('find'); |
||
| 650 | $chmodPath = self::which('chmod'); |
||
| 651 | Processes::mwExec("{$findPath} {$folder} -type f -exec {$chmodPath} 755 {} \;"); |
||
| 652 | } |
||
| 653 | } |
||
| 654 | |||
| 655 | /** |
||
| 656 | * Разбор INI конфига |
||
| 657 | * |
||
| 658 | * @param string $manual_attributes |
||
| 659 | * |
||
| 660 | * @return array |
||
| 661 | */ |
||
| 662 | public static function parseIniSettings(string $manual_attributes): array |
||
| 663 | { |
||
| 664 | $tmp_data = base64_decode($manual_attributes); |
||
| 665 | if (base64_encode($tmp_data) === $manual_attributes) { |
||
| 666 | $manual_attributes = $tmp_data; |
||
| 667 | } |
||
| 668 | unset($tmp_data); |
||
| 669 | // TRIMMING |
||
| 670 | $tmp_arr = explode("\n", $manual_attributes); |
||
| 671 | foreach ($tmp_arr as &$row) { |
||
| 672 | $row = trim($row); |
||
| 673 | $pos = strpos($row, ']'); |
||
| 674 | if ($pos !== false && strpos($row, '[') === 0) { |
||
| 675 | $row = "\n" . substr($row, 0, $pos); |
||
| 676 | } |
||
| 677 | } |
||
| 678 | unset($row); |
||
| 679 | $manual_attributes = implode("\n", $tmp_arr); |
||
| 680 | // TRIMMING END |
||
| 681 | |||
| 682 | $manual_data = []; |
||
| 683 | $sections = explode("\n[", str_replace(']', '', $manual_attributes)); |
||
| 684 | foreach ($sections as $section) { |
||
| 685 | $data_rows = explode("\n", trim($section)); |
||
| 686 | $section_name = trim($data_rows[0] ?? ''); |
||
| 687 | if ( ! empty($section_name)) { |
||
| 688 | unset($data_rows[0]); |
||
| 689 | $manual_data[$section_name] = []; |
||
| 690 | foreach ($data_rows as $row) { |
||
| 691 | if (strpos($row, '=') === false) { |
||
| 692 | continue; |
||
| 693 | } |
||
| 694 | $key = ''; |
||
| 695 | $arr_value = explode('=', $row); |
||
| 696 | if (count($arr_value) > 1) { |
||
| 697 | $key = trim($arr_value[0]); |
||
| 698 | unset($arr_value[0]); |
||
| 699 | $value = trim(implode('=', $arr_value)); |
||
| 700 | } |
||
| 701 | if (empty($value) || empty($key)) { |
||
| 702 | continue; |
||
| 703 | } |
||
| 704 | $manual_data[$section_name][$key] = $value; |
||
| 705 | } |
||
| 706 | } |
||
| 707 | } |
||
| 708 | |||
| 709 | return $manual_data; |
||
| 710 | } |
||
| 711 | |||
| 712 | /** |
||
| 713 | * Converts multidimensional array into single array |
||
| 714 | * |
||
| 715 | * @param $array |
||
| 716 | * |
||
| 717 | * @return array |
||
| 718 | */ |
||
| 719 | public static function flattenArray(array $array) |
||
| 720 | { |
||
| 721 | $result = []; |
||
| 722 | foreach ($array as $value) { |
||
| 723 | if (is_array($value)) { |
||
| 724 | $result = array_merge($result, self::flattenArray($value)); |
||
| 725 | } else { |
||
| 726 | $result[] = $value; |
||
| 727 | } |
||
| 728 | } |
||
| 729 | |||
| 730 | return $result; |
||
| 731 | } |
||
| 732 | |||
| 733 | /** |
||
| 734 | * Try to find full path to php file by class name |
||
| 735 | * |
||
| 736 | * @param $className |
||
| 737 | * |
||
| 738 | * @return string|null |
||
| 739 | */ |
||
| 740 | public static function getFilePathByClassName($className): ?string |
||
| 741 | { |
||
| 742 | $filename = null; |
||
| 743 | try { |
||
| 744 | $reflection = new ReflectionClass($className); |
||
| 745 | $filename = $reflection->getFileName(); |
||
| 746 | } catch (ReflectionException $exception) { |
||
| 747 | self::sysLogMsg('Util', 'Error ' . $exception->getMessage()); |
||
| 748 | } |
||
| 749 | |||
| 750 | return $filename; |
||
| 751 | } |
||
| 752 | |||
| 753 | /** |
||
| 754 | * DEPRICATED |
||
| 755 | * Возвращает PID процесса по его имени. |
||
| 756 | * |
||
| 757 | * @param $name |
||
| 758 | * @param string $exclude |
||
| 759 | * |
||
| 760 | * @return string |
||
| 761 | */ |
||
| 762 | public static function getPidOfProcess($name, $exclude = ''): string |
||
| 763 | { |
||
| 764 | self::sysLogMsg('Util', 'Deprecated call ' . __METHOD__ . ' from ' . static::class); |
||
| 765 | |||
| 766 | return Processes::getPidOfProcess($name, $exclude); |
||
| 767 | } |
||
| 768 | |||
| 769 | /** |
||
| 770 | * DEPRICATED |
||
| 771 | * Manages a daemon/worker process |
||
| 772 | * Returns process statuses by name of it |
||
| 773 | * |
||
| 774 | * @param $cmd |
||
| 775 | * @param $param |
||
| 776 | * @param $proc_name |
||
| 777 | * @param $action |
||
| 778 | * @param $out_file |
||
| 779 | * |
||
| 780 | * @return array | bool |
||
| 781 | */ |
||
| 782 | public static function processWorker($cmd, $param, $proc_name, $action, $out_file = '/dev/null') |
||
| 783 | { |
||
| 784 | self::sysLogMsg('Util', 'Deprecated call ' . __METHOD__ . ' from ' . static::class); |
||
| 785 | |||
| 786 | return Processes::processWorker($cmd, $param, $proc_name, $action, $out_file); |
||
| 787 | } |
||
| 788 | |||
| 789 | /** |
||
| 790 | * DEPRICATED |
||
| 791 | * Process PHP workers |
||
| 792 | * |
||
| 793 | * @param string $className |
||
| 794 | * @param string $param |
||
| 795 | * @param string $action |
||
| 796 | */ |
||
| 797 | public static function processPHPWorker( |
||
| 798 | string $className, |
||
| 799 | string $param = 'start', |
||
| 800 | string $action = 'restart' |
||
| 801 | ): void { |
||
| 802 | self::sysLogMsg('Util', 'Deprecated call ' . __METHOD__ . ' from ' . static::class); |
||
| 803 | Processes::processPHPWorker($className, $param, $action); |
||
| 804 | } |
||
| 805 | |||
| 806 | /** |
||
| 807 | * DEPRICATED |
||
| 808 | * Kills process/daemon by name |
||
| 809 | * |
||
| 810 | * @param $procName |
||
| 811 | * |
||
| 812 | * @return int|null |
||
| 813 | */ |
||
| 814 | public static function killByName($procName): ?int |
||
| 819 | } |
||
| 820 | |||
| 821 | /** |
||
| 822 | * DEPRICATED |
||
| 823 | * Executes command exec() as background process. |
||
| 824 | * |
||
| 825 | * @param $command |
||
| 826 | * @param $out_file |
||
| 827 | * @param $sleep_time |
||
| 828 | */ |
||
| 829 | public static function mwExecBg($command, $out_file = '/dev/null', $sleep_time = 0): void |
||
| 830 | { |
||
| 831 | self::sysLogMsg('Util', 'Deprecated call ' . __METHOD__ . ' from ' . static::class); |
||
| 832 | Processes::mwExecBg($command, $out_file, $sleep_time); |
||
| 833 | } |
||
| 834 | |||
| 835 | /** |
||
| 836 | * DEPRICATED |
||
| 837 | * Executes command exec() as background process with an execution timeout. |
||
| 838 | * |
||
| 839 | * @param $command |
||
| 840 | * @param int $timeout |
||
| 841 | * @param string $logname |
||
| 842 | */ |
||
| 843 | public static function mwExecBgWithTimeout($command, $timeout = 4, $logname = '/dev/null'): void |
||
| 847 | } |
||
| 848 | |||
| 849 | /** |
||
| 850 | * DEPRICATED |
||
| 851 | * Executes multiple commands. |
||
| 852 | * |
||
| 853 | * @param $arr_cmds |
||
| 854 | * @param array $out |
||
| 855 | * @param string $logname |
||
| 856 | */ |
||
| 857 | public static function mwExecCommands($arr_cmds, &$out = [], $logname = ''): void |
||
| 858 | { |
||
| 859 | self::sysLogMsg('Util', 'Deprecated call ' . __METHOD__ . ' from ' . static::class); |
||
| 860 | Processes::mwExecCommands($arr_cmds, $out, $logname); |
||
| 861 | } |
||
| 862 | |||
| 863 | /** |
||
| 864 | * Добавляем задачу для уведомлений. |
||
| 865 | * |
||
| 866 | * @param string $tube |
||
| 867 | * @param $data |
||
| 868 | */ |
||
| 869 | public function addJobToBeanstalk(string $tube, $data): void |
||
| 870 | { |
||
| 871 | $queue = new BeanstalkClient($tube); |
||
| 872 | $queue->publish(json_encode($data)); |
||
| 873 | } |
||
| 874 | |||
| 875 | |||
| 876 | } |