You are here

public function ShellManager::escapeShellArg in FillPDF 5.0.x

Same name and namespace in other branches
  1. 8.4 src/ShellManager.php \Drupal\fillpdf\ShellManager::escapeShellArg()

Escapes a string.

PHP escapeshellarg() drops non-ascii characters, this is a replacement.

Stop-gap replacement until core issue #1561214 has been solved. Solution proposed in #1502924-8.

PHP escapeshellarg() on Windows also drops % (percentage sign) characters. We prevent this by replacing it with a pattern that should be highly unlikely to appear in the string itself and does not contain any "dangerous" character at all (very wide definition of dangerous). After escaping we replace that pattern back with a % character.

Parameters

string $arg: The string to escape.

Return value

string Escaped string.

Overrides ShellManagerInterface::escapeShellArg

See also

https://www.drupal.org/project/drupal/issues/1561214

File

src/ShellManager.php, line 63

Class

ShellManager
Manage execution of shell commands.

Namespace

Drupal\fillpdf

Code

public function escapeShellArg($arg) {

  // Put the configured locale in a static to avoid multiple config get calls
  // in the same request.
  static $config_locale;
  if (!isset($config_locale)) {
    $config_locale = $this->configFactory
      ->get('fillpdf.settings')
      ->get('shell_locale');
  }
  $current_locale = setlocale(LC_CTYPE, 0);
  if ($this
    ->isWindows()) {

    // Temporarily replace % characters.
    $arg = str_replace('%', static::PERCENTAGE_REPLACE, $arg);
  }
  if ($current_locale !== $config_locale) {

    // Temporarily swap the current locale with the configured one, if
    // available. Otherwise fall back.
    setlocale(LC_CTYPE, [
      $config_locale,
      'C.UTF-8',
      $current_locale,
    ]);
  }
  $arg_escaped = escapeshellarg($arg);
  if ($current_locale !== $config_locale) {

    // Restore the current locale.
    setlocale(LC_CTYPE, $current_locale);
  }

  // Get our % characters back.
  if ($this
    ->isWindows()) {
    $arg_escaped = str_replace(static::PERCENTAGE_REPLACE, '%', $arg_escaped);
  }
  return $arg_escaped;
}