/** * Takes an unencoded string and produces a string encoded according to * RFC 2231 from it. * @param string $string to encode * @param int $firstLineOffset * @param int $maxLineLength, optional, 0 indicates the default of 75 bytes * @return string */ public function encodeString($string, $firstLineOffset = 0, $maxLineLength = 0) { $lines = array(); $lineCount = 0; $lines[] = ''; $currentLine =& $lines[$lineCount++]; if (0 >= $maxLineLength) { $maxLineLength = 75; } $this->_charStream->flushContents(); $this->_charStream->importString($string); $thisLineLength = $maxLineLength - $firstLineOffset; while (false !== $char = $this->_charStream->read(4)) { $encodedChar = rawurlencode($char); if (0 != strlen($currentLine) && strlen($currentLine . $encodedChar) > $thisLineLength) { $lines[] = ''; $currentLine =& $lines[$lineCount++]; $thisLineLength = $maxLineLength; } $currentLine .= $encodedChar; } return implode("\r\n", $lines); }
/** * Takes an unencoded string and produces a QP encoded string from it. * QP encoded strings have a maximum line length of 76 characters. * If the first line needs to be shorter, indicate the difference with * $firstLineOffset. * @param string $string to encode * @param int $firstLineOffset, optional * @param int $maxLineLength, optional, 0 indicates the default of 76 chars * @return string */ public function encodeString($string, $firstLineOffset = 0, $maxLineLength = 0) { if ($maxLineLength > 76 || $maxLineLength <= 0) { $maxLineLength = 76; } $thisLineLength = $maxLineLength - $firstLineOffset; $lines = array(); $lNo = 0; $lines[$lNo] = ''; $currentLine =& $lines[$lNo++]; $size = $lineLen = 0; $this->_charStream->flushContents(); $this->_charStream->importString($string); //Fetching more than 4 chars at one is slower, as is fetching fewer bytes // Conveniently 4 chars is the UTF-8 safe number since UTF-8 has up to 6 // bytes per char and (6 * 4 * 3 = 72 chars per line) * =NN is 3 bytes while (false !== ($bytes = $this->_nextSequence())) { //If we're filtering the input if (isset($this->_filter)) { //If we can't filter because we need more bytes while ($this->_filter->shouldBuffer($bytes)) { //Then collect bytes into the buffer if (false === ($moreBytes = $this->_nextSequence(1))) { break; } foreach ($moreBytes as $b) { $bytes[] = $b; } } //And filter them $bytes = $this->_filter->filter($bytes); } $enc = $this->_encodeByteSequence($bytes, $size); if ($currentLine && $lineLen + $size >= $thisLineLength) { $lines[$lNo] = ''; $currentLine =& $lines[$lNo++]; $thisLineLength = $maxLineLength; $lineLen = 0; } $lineLen += $size; $currentLine .= $enc; } return $this->_standardize(implode("=\r\n", $lines)); }