Rfc2231Encoder.php 2.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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. * @package Swift
  13. * @subpackage Encoder
  14. * @author Chris Corbyn
  15. */
  16. class Swift_Encoder_Rfc2231Encoder implements Swift_Encoder
  17. {
  18. /**
  19. * A character stream to use when reading a string as characters instead of bytes.
  20. *
  21. * @var Swift_CharacterStream
  22. */
  23. private $_charStream;
  24. /**
  25. * Creates a new Rfc2231Encoder using the given character stream instance.
  26. *
  27. * @param Swift_CharacterStream
  28. */
  29. public function __construct(Swift_CharacterStream $charStream)
  30. {
  31. $this->_charStream = $charStream;
  32. }
  33. /**
  34. * Takes an unencoded string and produces a string encoded according to
  35. * RFC 2231 from it.
  36. *
  37. * @param string $string
  38. * @param integer $firstLineOffset
  39. * @param integer $maxLineLength optional, 0 indicates the default of 75 bytes
  40. *
  41. * @return string
  42. */
  43. public function encodeString($string, $firstLineOffset = 0, $maxLineLength = 0)
  44. {
  45. $lines = array(); $lineCount = 0;
  46. $lines[] = '';
  47. $currentLine =& $lines[$lineCount++];
  48. if (0 >= $maxLineLength) {
  49. $maxLineLength = 75;
  50. }
  51. $this->_charStream->flushContents();
  52. $this->_charStream->importString($string);
  53. $thisLineLength = $maxLineLength - $firstLineOffset;
  54. while (false !== $char = $this->_charStream->read(4)) {
  55. $encodedChar = rawurlencode($char);
  56. if (0 != strlen($currentLine)
  57. && strlen($currentLine . $encodedChar) > $thisLineLength)
  58. {
  59. $lines[] = '';
  60. $currentLine =& $lines[$lineCount++];
  61. $thisLineLength = $maxLineLength;
  62. }
  63. $currentLine .= $encodedChar;
  64. }
  65. return implode("\r\n", $lines);
  66. }
  67. /**
  68. * Updates the charset used.
  69. *
  70. * @param string $charset
  71. */
  72. public function charsetChanged($charset)
  73. {
  74. $this->_charStream->setCharacterSet($charset);
  75. }
  76. }