Rfc2231Encoder.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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. * @param Swift_CharacterStream
  26. */
  27. public function __construct(Swift_CharacterStream $charStream)
  28. {
  29. $this->_charStream = $charStream;
  30. }
  31. /**
  32. * Takes an unencoded string and produces a string encoded according to
  33. * RFC 2231 from it.
  34. *
  35. * @param string $string
  36. * @param int $firstLineOffset
  37. * @param int $maxLineLength optional, 0 indicates the default of 75 bytes
  38. *
  39. * @return string
  40. */
  41. public function encodeString($string, $firstLineOffset = 0, $maxLineLength = 0)
  42. {
  43. $lines = array(); $lineCount = 0;
  44. $lines[] = '';
  45. $currentLine =& $lines[$lineCount++];
  46. if (0 >= $maxLineLength) {
  47. $maxLineLength = 75;
  48. }
  49. $this->_charStream->flushContents();
  50. $this->_charStream->importString($string);
  51. $thisLineLength = $maxLineLength - $firstLineOffset;
  52. while (false !== $char = $this->_charStream->read(4)) {
  53. $encodedChar = rawurlencode($char);
  54. if (0 != strlen($currentLine)
  55. && strlen($currentLine . $encodedChar) > $thisLineLength)
  56. {
  57. $lines[] = '';
  58. $currentLine =& $lines[$lineCount++];
  59. $thisLineLength = $maxLineLength;
  60. }
  61. $currentLine .= $encodedChar;
  62. }
  63. return implode("\r\n", $lines);
  64. }
  65. /**
  66. * Updates the charset used.
  67. *
  68. * @param string $charset
  69. */
  70. public function charsetChanged($charset)
  71. {
  72. $this->_charStream->setCharacterSet($charset);
  73. }
  74. }