You are here

public static function Unicode::mimeHeaderEncode in Drupal 9

Same name and namespace in other branches
  1. 8 core/lib/Drupal/Component/Utility/Unicode.php \Drupal\Component\Utility\Unicode::mimeHeaderEncode()

Encodes MIME/HTTP headers that contain incorrectly encoded characters.

For example, Unicode::mimeHeaderEncode('tést.txt') returns "=?UTF-8?B?dMOpc3QudHh0?=".

See http://www.rfc-editor.org/rfc/rfc2047.txt for more information.

Notes:

  • Only encode strings that contain non-ASCII characters.
  • We progressively cut-off a chunk with self::truncateBytes(). This ensures each chunk starts and ends on a character boundary.
  • Using \n as the chunk separator may cause problems on some systems and may have to be changed to \r\n or \r.

Parameters

string $string: The header to encode.

bool $shorten: If TRUE, only return the first chunk of a multi-chunk encoded string.

Return value

string The mime-encoded header.

Deprecated

in drupal:9.2.0 and is removed from drupal:10.0.0. Use \Symfony\Component\Mime\Header\UnstructuredHeader instead.

See also

https://www.drupal.org/node/3207439

2 calls to Unicode::mimeHeaderEncode()
Mail::formatDisplayName in core/lib/Drupal/Component/Utility/Mail.php
Return a RFC-2822 compliant "display-name" component.
UnicodeTest::testMimeHeaderEncode in core/tests/Drupal/Tests/Component/Utility/UnicodeTest.php
Tests multibyte encoding.

File

core/lib/Drupal/Component/Utility/Unicode.php, line 402

Class

Unicode
Provides Unicode-related conversions and operations.

Namespace

Drupal\Component\Utility

Code

public static function mimeHeaderEncode($string, $shorten = FALSE) {
  @trigger_error('\\Drupal\\Component\\Utility\\Unicode::mimeHeaderEncode() is deprecated in drupal:9.2.0 and is removed from drupal:10.0.0. Use \\Symfony\\Component\\Mime\\Header\\UnstructuredHeader instead. See https://www.drupal.org/node/3207439', E_USER_DEPRECATED);
  if (preg_match('/[^\\x20-\\x7E]/', $string)) {

    // floor((75 - strlen("=?UTF-8?B??=")) * 0.75);
    $chunk_size = 47;
    $len = strlen($string);
    $output = '';
    while ($len > 0) {
      $chunk = static::truncateBytes($string, $chunk_size);
      $output .= ' =?UTF-8?B?' . base64_encode($chunk) . "?=\n";
      if ($shorten) {
        break;
      }
      $c = strlen($chunk);
      $string = substr($string, $c);
      $len -= $c;
    }
    return trim($output);
  }
  return $string;
}