Rfc2231Encoder.php 2.1KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. * @package Swift
  12. * @subpackage Encoder
  13. * @author Chris Corbyn
  14. */
  15. class Swift_Encoder_Rfc2231Encoder implements Swift_Encoder
  16. {
  17. /**
  18. * A character stream to use when reading a string as characters instead of bytes.
  19. * @var Swift_CharacterStream
  20. * @access private
  21. */
  22. private $_charStream;
  23. /**
  24. * Creates a new Rfc2231Encoder using the given character stream instance.
  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. * @param string $string to encode
  35. * @param int $firstLineOffset
  36. * @param int $maxLineLength, optional, 0 indicates the default of 75 bytes
  37. * @return string
  38. */
  39. public function encodeString($string, $firstLineOffset = 0,
  40. $maxLineLength = 0)
  41. {
  42. $lines = array(); $lineCount = 0;
  43. $lines[] = '';
  44. $currentLine =& $lines[$lineCount++];
  45. if (0 >= $maxLineLength)
  46. {
  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. {
  54. $encodedChar = rawurlencode($char);
  55. if (0 != strlen($currentLine)
  56. && strlen($currentLine . $encodedChar) > $thisLineLength)
  57. {
  58. $lines[] = '';
  59. $currentLine =& $lines[$lineCount++];
  60. $thisLineLength = $maxLineLength;
  61. }
  62. $currentLine .= $encodedChar;
  63. }
  64. return implode("\r\n", $lines);
  65. }
  66. /**
  67. * Updates the charset used.
  68. * @param string $charset
  69. */
  70. public function charsetChanged($charset)
  71. {
  72. $this->_charStream->setCharacterSet($charset);
  73. }
  74. }