4 * This file is part of SwiftMailer.
5 * (c) 2004-2009 Chris Corbyn
7 * For the full copyright and license information, please view the LICENSE
8 * file that was distributed with this source code.
11 //@require 'Swift/Mime/ContentEncoder.php';
12 //@require 'Swift/InputByteStream.php';
13 //@require 'Swift/OutputByteStream.php';
16 * Handles binary/7/8-bit Transfer Encoding in Swift Mailer.
19 * @author Chris Corbyn
21 class Swift_Mime_ContentEncoder_PlainContentEncoder
22 implements Swift_Mime_ContentEncoder
26 * The name of this encoding scheme (probably 7bit or 8bit).
33 * True if canonical transformations should be done.
40 * Creates a new PlainContentEncoder with $name (probably 7bit or 8bit).
42 * @param boolean $canonical If canonicalization transformation should be done.
44 public function __construct($name, $canonical = false)
47 $this->_canonical
= $canonical;
51 * Encode a given string to produce an encoded string.
52 * @param string $string
53 * @param int $firstLineOffset, ignored
54 * @param int $maxLineLength - 0 means no wrapping will occur
57 public function encodeString($string, $firstLineOffset = 0,
60 if ($this->_canonical
)
62 $string = $this->_canonicalize($string);
64 return $this->_safeWordWrap($string, $maxLineLength, "\r\n");
68 * Encode stream $in to stream $out.
69 * @param Swift_OutputByteStream $in
70 * @param Swift_InputByteStream $out
71 * @param int $firstLineOffset, ignored
72 * @param int $maxLineLength, optional, 0 means no wrapping will occur
74 public function encodeByteStream(
75 Swift_OutputByteStream
$os, Swift_InputByteStream
$is, $firstLineOffset = 0,
79 while (false !== $bytes = $os->read(8192))
81 $toencode = $leftOver . $bytes;
82 if ($this->_canonical
)
84 $toencode = $this->_canonicalize($toencode);
86 $wrapped = $this->_safeWordWrap($toencode, $maxLineLength, "\r\n");
87 $lastLinePos = strrpos($wrapped, "\r\n");
88 $leftOver = substr($wrapped, $lastLinePos);
89 $wrapped = substr($wrapped, 0, $lastLinePos);
93 if (strlen($leftOver))
95 $is->write($leftOver);
100 * Get the name of this encoding scheme.
103 public function getName()
111 public function charsetChanged($charset)
115 // -- Private methods
118 * A safer (but weaker) wordwrap for unicode.
119 * @param string $string
125 private function _safeWordwrap($string, $length = 75, $le = "\r\n")
132 $originalLines = explode($le, $string);
137 foreach ($originalLines as $originalLine)
140 $currentLine =& $lines[$lineCount++
];
142 //$chunks = preg_split('/(?<=[\ \t,\.!\?\-&\+\/])/', $originalLine);
143 $chunks = preg_split('/(?<=\s)/', $originalLine);
145 foreach ($chunks as $chunk)
147 if (0 != strlen($currentLine)
148 && strlen($currentLine . $chunk) > $length)
151 $currentLine =& $lines[$lineCount++
];
153 $currentLine .= $chunk;
157 return implode("\r\n", $lines);
161 * Canonicalize string input (fix CRLF).
162 * @param string $string
166 private function _canonicalize($string)
169 array("\r\n", "\r", "\n"),
170 array("\n", "\n", "\r\n"),