|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace PHPVideoToolkit; |
| 4 | + |
| 5 | +/** |
| 6 | + * ProcessUtils is a bunch of utility methods taken from Symphony. |
| 7 | + * |
| 8 | + * This class contains static methods only and is not meant to be instantiated. |
| 9 | + * |
| 10 | + * @author Martin Hasoň <[email protected]> |
| 11 | + */ |
| 12 | +class ProcessUtils |
| 13 | +{ |
| 14 | + /** |
| 15 | + * This class should not be instantiated. |
| 16 | + */ |
| 17 | + private function __construct() |
| 18 | + { |
| 19 | + } |
| 20 | + |
| 21 | + /** |
| 22 | + * Escapes a string to be used as a shell argument. |
| 23 | + * |
| 24 | + * @param string $argument The argument that will be escaped |
| 25 | + * |
| 26 | + * @return string The escaped argument |
| 27 | + */ |
| 28 | + public static function escapeArgument($argument) |
| 29 | + { |
| 30 | + //Fix for PHP bug #43784 escapeshellarg removes % from given string |
| 31 | + //Fix for PHP bug #49446 escapeshellarg doesn't work on Windows |
| 32 | + //@see https://bugs.php.net/bug.php?id=43784 |
| 33 | + //@see https://bugs.php.net/bug.php?id=49446 |
| 34 | + if ('\\' === DIRECTORY_SEPARATOR) { |
| 35 | + if ('' === $argument) { |
| 36 | + return escapeshellarg($argument); |
| 37 | + } |
| 38 | + |
| 39 | + $escapedArgument = ''; |
| 40 | + $quote = false; |
| 41 | + foreach (preg_split('/(")/', $argument, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE) as $part) { |
| 42 | + if ('"' === $part) { |
| 43 | + $escapedArgument .= '\\"'; |
| 44 | + } elseif (self::isSurroundedBy($part, '%')) { |
| 45 | + // Avoid environment variable expansion |
| 46 | + $escapedArgument .= '^%"'.substr($part, 1, -1).'"^%'; |
| 47 | + } else { |
| 48 | + // escape trailing backslash |
| 49 | + if ('\\' === substr($part, -1)) { |
| 50 | + $part .= '\\'; |
| 51 | + } |
| 52 | + $quote = true; |
| 53 | + $escapedArgument .= $part; |
| 54 | + } |
| 55 | + } |
| 56 | + if ($quote) { |
| 57 | + $escapedArgument = '"'.$escapedArgument.'"'; |
| 58 | + } |
| 59 | + |
| 60 | + return $escapedArgument; |
| 61 | + } |
| 62 | + |
| 63 | + return escapeshellarg($argument); |
| 64 | + } |
| 65 | + |
| 66 | + private static function isSurroundedBy($arg, $char) |
| 67 | + { |
| 68 | + return 2 < strlen($arg) && $char === $arg[0] && $char === $arg[strlen($arg) - 1]; |
| 69 | + } |
| 70 | +} |
0 commit comments