Rfc2231Encoder.php 2.2KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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, $maxLineLength = 0)
  40. {
  41. $lines = array(); $lineCount = 0;
  42. $lines[] = '';
  43. $currentLine =& $lines[$lineCount++];
  44. if (0 >= $maxLineLength) {
  45. $maxLineLength = 75;
  46. }
  47. $this->_charStream->flushContents();
  48. $this->_charStream->importString($string);
  49. $thisLineLength = $maxLineLength - $firstLineOffset;
  50. while (false !== $char = $this->_charStream->read(4)) {
  51. $encodedChar = rawurlencode($char);
  52. if (0 != strlen($currentLine)
  53. && strlen($currentLine . $encodedChar) > $thisLineLength)
  54. {
  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. * @param string $charset
  66. */
  67. public function charsetChanged($charset)
  68. {
  69. $this->_charStream->setCharacterSet($charset);
  70. }
  71. }