QpContentEncoder.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Mime\Encoder;
  11. /**
  12. * @author Lars Strojny
  13. */
  14. final class QpContentEncoder implements ContentEncoderInterface
  15. {
  16. public function encodeByteStream($stream, int $maxLineLength = 0): iterable
  17. {
  18. if (!\is_resource($stream)) {
  19. throw new \TypeError(sprintf('Method "%s" takes a stream as a first argument.', __METHOD__));
  20. }
  21. // we don't use PHP stream filters here as the content should be small enough
  22. if (stream_get_meta_data($stream)['seekable'] ?? false) {
  23. rewind($stream);
  24. }
  25. yield $this->encodeString(stream_get_contents($stream), 'utf-8', 0, $maxLineLength);
  26. }
  27. public function getName(): string
  28. {
  29. return 'quoted-printable';
  30. }
  31. public function encodeString(string $string, ?string $charset = 'utf-8', int $firstLineOffset = 0, int $maxLineLength = 0): string
  32. {
  33. return $this->standardize(quoted_printable_encode($string));
  34. }
  35. /**
  36. * Make sure CRLF is correct and HT/SPACE are in valid places.
  37. */
  38. private function standardize(string $string): string
  39. {
  40. // transform CR or LF to CRLF
  41. $string = preg_replace('~=0D(?!=0A)|(?<!=0D)=0A~', '=0D=0A', $string);
  42. // transform =0D=0A to CRLF
  43. $string = str_replace(["\t=0D=0A", ' =0D=0A', '=0D=0A'], ["=09\r\n", "=20\r\n", "\r\n"], $string);
  44. switch (\ord(substr($string, -1))) {
  45. case 0x09:
  46. $string = substr_replace($string, '=09', -1);
  47. break;
  48. case 0x20:
  49. $string = substr_replace($string, '=20', -1);
  50. break;
  51. }
  52. return $string;
  53. }
  54. }