TYPO3  7.6
Base64ContentEncoder.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 
17 {
26  public function encodeByteStream(Swift_OutputByteStream $os, Swift_InputByteStream $is, $firstLineOffset = 0, $maxLineLength = 0)
27  {
28  if (0 >= $maxLineLength || 76 < $maxLineLength) {
29  $maxLineLength = 76;
30  }
31 
32  $remainder = 0;
33  $base64ReadBufferRemainderBytes = null;
34 
35  // To reduce memory usage, the output buffer is streamed to the input buffer like so:
36  // Output Stream => base64encode => wrap line length => Input Stream
37  // HOWEVER it's important to note that base64_encode() should only be passed whole triplets of data (except for the final chunk of data)
38  // otherwise it will assume the input data has *ended* and it will incorrectly pad/terminate the base64 data mid-stream.
39  // We use $base64ReadBufferRemainderBytes to carry over 1-2 "remainder" bytes from the each chunk from OutputStream and pre-pend those onto the
40  // chunk of bytes read in the next iteration.
41  // When the OutputStream is empty, we must flush any remainder bytes.
42  while (true) {
43  $readBytes = $os->read(8192);
44  $atEOF = ($readBytes === false);
45 
46  if ($atEOF) {
47  $streamTheseBytes = $base64ReadBufferRemainderBytes;
48  } else {
49  $streamTheseBytes = $base64ReadBufferRemainderBytes.$readBytes;
50  }
51  $base64ReadBufferRemainderBytes = null;
52  $bytesLength = strlen($streamTheseBytes);
53 
54  if ($bytesLength === 0) { // no data left to encode
55  break;
56  }
57 
58  // if we're not on the last block of the ouput stream, make sure $streamTheseBytes ends with a complete triplet of data
59  // and carry over remainder 1-2 bytes to the next loop iteration
60  if (!$atEOF) {
61  $excessBytes = $bytesLength % 3;
62  if ($excessBytes !== 0) {
63  $base64ReadBufferRemainderBytes = substr($streamTheseBytes, -$excessBytes);
64  $streamTheseBytes = substr($streamTheseBytes, 0, $bytesLength - $excessBytes);
65  }
66  }
67 
68  $encoded = base64_encode($streamTheseBytes);
69  $encodedTransformed = '';
70  $thisMaxLineLength = $maxLineLength - $remainder - $firstLineOffset;
71 
72  while ($thisMaxLineLength < strlen($encoded)) {
73  $encodedTransformed .= substr($encoded, 0, $thisMaxLineLength)."\r\n";
74  $firstLineOffset = 0;
75  $encoded = substr($encoded, $thisMaxLineLength);
76  $thisMaxLineLength = $maxLineLength;
77  $remainder = 0;
78  }
79 
80  if (0 < $remainingLength = strlen($encoded)) {
81  $remainder += $remainingLength;
82  $encodedTransformed .= $encoded;
83  $encoded = null;
84  }
85 
86  $is->write($encodedTransformed);
87 
88  if ($atEOF) {
89  break;
90  }
91  }
92  }
93 
100  public function getName()
101  {
102  return 'base64';
103  }
104 }