XOOPS RMCommon Utilities  2.1.8.91RC
 All Classes Namespaces Files Functions Variables
PlainContentEncoder.php
Go to the documentation of this file.
1 <?php
2 
3 /*
4  * This file is part of SwiftMailer.
5  * (c) 2004-2009 Chris Corbyn
6  *
7  * For the full copyright and license information, please view the LICENSE
8  * file that was distributed with this source code.
9  */
10 
11 //@require 'Swift/Mime/ContentEncoder.php';
12 //@require 'Swift/InputByteStream.php';
13 //@require 'Swift/OutputByteStream.php';
14 
22  implements Swift_Mime_ContentEncoder
23 {
24 
30  private $_name;
31 
37  private $_canonical;
38 
44  public function __construct($name, $canonical = false)
45  {
46  $this->_name = $name;
47  $this->_canonical = $canonical;
48  }
49 
57  public function encodeString($string, $firstLineOffset = 0,
58  $maxLineLength = 0)
59  {
60  if ($this->_canonical)
61  {
62  $string = $this->_canonicalize($string);
63  }
64  return $this->_safeWordWrap($string, $maxLineLength, "\r\n");
65  }
66 
74  public function encodeByteStream(
75  Swift_OutputByteStream $os, Swift_InputByteStream $is, $firstLineOffset = 0,
76  $maxLineLength = 0)
77  {
78  $leftOver = '';
79  while (false !== $bytes = $os->read(8192))
80  {
81  $toencode = $leftOver . $bytes;
82  if ($this->_canonical)
83  {
84  $toencode = $this->_canonicalize($toencode);
85  }
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);
90 
91  $is->write($wrapped);
92  }
93  if (strlen($leftOver))
94  {
95  $is->write($leftOver);
96  }
97  }
98 
103  public function getName()
104  {
105  return $this->_name;
106  }
107 
111  public function charsetChanged($charset)
112  {
113  }
114 
115  // -- Private methods
116 
125  private function _safeWordwrap($string, $length = 75, $le = "\r\n")
126  {
127  if (0 >= $length)
128  {
129  return $string;
130  }
131 
132  $originalLines = explode($le, $string);
133 
134  $lines = array();
135  $lineCount = 0;
136 
137  foreach ($originalLines as $originalLine)
138  {
139  $lines[] = '';
140  $currentLine =& $lines[$lineCount++];
141 
142  //$chunks = preg_split('/(?<=[\ \t,\.!\?\-&\+\/])/', $originalLine);
143  $chunks = preg_split('/(?<=\s)/', $originalLine);
144 
145  foreach ($chunks as $chunk)
146  {
147  if (0 != strlen($currentLine)
148  && strlen($currentLine . $chunk) > $length)
149  {
150  $lines[] = '';
151  $currentLine =& $lines[$lineCount++];
152  }
153  $currentLine .= $chunk;
154  }
155  }
156 
157  return implode("\r\n", $lines);
158  }
159 
166  private function _canonicalize($string)
167  {
168  return str_replace(
169  array("\r\n", "\r", "\n"),
170  array("\n", "\n", "\r\n"),
171  $string
172  );
173  }
174 
175 }