You are here

public static function ConversionHelper::escapeDnValue in Lightweight Directory Access Protocol (LDAP) 8.3

Escapes a DN value according to RFC 2253.

Escapes the given VALUES according to RFC 2253 so that they can be safely used in LDAP DNs. The characters ",", "+", """, "\", "<", ">", ";", "#", "=" with a special meaning in RFC 2252 are preceded by a backslash. Control characters with an ASCII code < 32 are represented as \hexpair. Finally all leading and trailing spaces are converted to sequences of \20.

@static

Parameters

array|string $values: An array containing the DN values that should be escaped.

Return value

array The array $values, but escaped.

1 call to ConversionHelper::escapeDnValue()
MassageAttributes::storeLdapAttributeValue in ldap_servers/src/Helper/MassageAttributes.php
Prepare text for storing LDAP attribute values.

File

ldap_servers/src/Helper/ConversionHelper.php, line 125

Class

ConversionHelper
Conversion helper to escape values correctly for LDAP filters.

Namespace

Drupal\ldap_servers\Helper

Code

public static function escapeDnValue($values) {

  // Parameter validation.
  $inputIsScalar = is_scalar($values);
  if ($inputIsScalar) {
    $values = [
      $values,
    ];
  }
  foreach ($values as $key => $val) {

    // Escaping of filter meta characters.
    $val = str_replace('\\', '\\\\', $val);
    $val = str_replace(',', '\\,', $val);
    $val = str_replace('+', '\\+', $val);
    $val = str_replace('"', '\\"', $val);
    $val = str_replace('<', '\\<', $val);
    $val = str_replace('>', '\\>', $val);
    $val = str_replace(';', '\\;', $val);
    $val = str_replace('#', '\\#', $val);
    $val = str_replace('=', '\\=', $val);

    // ASCII < 32 escaping.
    $val = self::asc2hex32($val);

    // Convert all leading and trailing spaces to sequences of \20.
    if (preg_match('/^(\\s*)(.+?)(\\s*)$/', $val, $matches)) {
      $val = $matches[2];
      for ($i = 0; $i < strlen($matches[1]); $i++) {
        $val = '\\20' . $val;
      }
      for ($i = 0; $i < strlen($matches[3]); $i++) {
        $val = $val . '\\20';
      }
    }
    if (NULL === $val) {

      // Apply escaped "null" if string is empty.
      $val = '\\0';
    }
    $values[$key] = $val;
  }
  if ($inputIsScalar) {
    return $values[0];
  }
  else {
    return $values;
  }
}