Rfc2231Encoder.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <?php
  2. /*
  3. * This file is part of SwiftMailer.
  4. * (c) 2004-2009 Chris Corbyn
  5. *
  6. * For the full copyright and license information, please view the LICENSE
  7. * file that was distributed with this source code.
  8. */
  9. /**
  10. * Handles RFC 2231 specified Encoding in Swift Mailer.
  11. *
  12. * @author Chris Corbyn
  13. */
  14. class Swift_Encoder_Rfc2231Encoder implements Swift_Encoder
  15. {
  16. /**
  17. * A character stream to use when reading a string as characters instead of bytes.
  18. *
  19. * @var Swift_CharacterStream
  20. */
  21. private $charStream;
  22. /**
  23. * Creates a new Rfc2231Encoder using the given character stream instance.
  24. */
  25. public function __construct(Swift_CharacterStream $charStream)
  26. {
  27. $this->charStream = $charStream;
  28. }
  29. /**
  30. * Takes an unencoded string and produces a string encoded according to
  31. * RFC 2231 from it.
  32. *
  33. * @param string $string
  34. * @param int $firstLineOffset
  35. * @param int $maxLineLength optional, 0 indicates the default of 75 bytes
  36. *
  37. * @return string
  38. */
  39. public function encodeString($string, $firstLineOffset = 0, $maxLineLength = 0)
  40. {
  41. $lines = [];
  42. $lineCount = 0;
  43. $lines[] = '';
  44. $currentLine = &$lines[$lineCount++];
  45. if (0 >= $maxLineLength) {
  46. $maxLineLength = 75;
  47. }
  48. $this->charStream->flushContents();
  49. $this->charStream->importString($string);
  50. $thisLineLength = $maxLineLength - $firstLineOffset;
  51. while (false !== $char = $this->charStream->read(4)) {
  52. $encodedChar = rawurlencode($char);
  53. if (0 != \strlen($currentLine)
  54. && \strlen($currentLine.$encodedChar) > $thisLineLength) {
  55. $lines[] = '';
  56. $currentLine = &$lines[$lineCount++];
  57. $thisLineLength = $maxLineLength;
  58. }
  59. $currentLine .= $encodedChar;
  60. }
  61. return implode("\r\n", $lines);
  62. }
  63. /**
  64. * Updates the charset used.
  65. *
  66. * @param string $charset
  67. */
  68. public function charsetChanged($charset)
  69. {
  70. $this->charStream->setCharacterSet($charset);
  71. }
  72. /**
  73. * Make a deep copy of object.
  74. */
  75. public function __clone()
  76. {
  77. $this->charStream = clone $this->charStream;
  78. }
  79. }