Encode a given string in mail header compatible base64 encoding.

@param string $str
@param string $charset
@param int $lineLength Defaults to {@link LINELENGTH}
@param int $lineEnd Defaults to {@link LINEEND}
@return string
171229
public static function encodeBase64Header($str,
        $charset,
        $lineLength = self::LINELENGTH,
        $lineEnd = self::LINEEND)
    {
        $prefix = '=?' . $charset . '?B?';
        $suffix = '?=';
        $remainingLength = $lineLength - strlen($prefix) - strlen($suffix);

        $encodedValue = self::encodeBase64($str, $remainingLength, $lineEnd);
        $encodedValue = str_replace($lineEnd, $suffix . $lineEnd . ' ' . $prefix, $encodedValue);
        $encodedValue = $prefix . $encodedValue . $suffix;
        return $encodedValue;
    }
1182710
public static function getLength($str)
    {
        $bytes = 0;
        $chars = 0;
        while ($bytes < strlen($str)) {
            $charBytes = 1;
            if ((ord($str[$bytes]) & 0xC0) == 0xC0) {
                $charBytes++;
                if (ord($str[$bytes]) & 0x20 ) {
                    $charBytes++;
                    if (ord($str[$bytes]) & 0x10 ) {
                        $charBytes++;
                    }
                }
            }

            if ($bytes + $charBytes > strlen($str)) {
                // wrong character
                break;
            }

            $chars++;
            $bytes += $charBytes;
        }

        return $chars;
    }
199318
public static function encode(String $str) : String
    {
        return str_replace(array_keys(self::$phpTagChars), array_values(self::$phpTagChars), $str);
    }
1289280
public function limtitLines($str, $lines = 1)
    {
        $line = "\n";
        for ($i=2; $i<=$lines; $i++) {
            $line .= "\n";
        }
        return preg_replace("/[\r\n]+/", "$line", $str);
    }
409560
public function encodeString($string, $firstLineOffset = 0, $maxLineLength = 0)
    {
        if ($this->canonical) {
            $string = $this->canonicalize($string);
        }

        return $this->safeWordwrap($string, $maxLineLength, "\r\n");
    }
947429
function serialize($charset_encoding='')
		{
			if ($charset_encoding != '')
				$this->content_type = 'text/xml; charset=' . $charset_encoding;
			else
				$this->content_type = 'text/xml';
			if ($GLOBALS['xmlrpc_null_apache_encoding'])
			{
				$result = "<methodResponse xmlns:ex=\"".$GLOBALS['xmlrpc_null_apache_encoding_ns']."\">\n";
			}
			else
			{
			$result = "<methodResponse>\n";
			}
			if($this->errno)
			{
				// G. Giunta 2005/2/13: let non-ASCII response messages be tolerated by clients
				// by xml-encoding non ascii chars
				$result .= "<fault>\n" .
"<value>\n<struct><member><name>faultCode</name>\n<value><int>" . $this->errno .
"</int></value>\n</member>\n<member>\n<name>faultString</name>\n<value><string>" .
xmlrpc_encode_entitites($this->errstr, $GLOBALS['xmlrpc_internalencoding'], $charset_encoding) . "</string></value>\n</member>\n" .
"</struct>\n</value>\n</fault>";
			}
			else
			{
				if(!is_object($this->val) || !is_a($this->val, 'xmlrpcval'))
				{
					if (is_string($this->val) && $this->valtyp == 'xml')
					{
						$result .= "<params>\n<param>\n" .
							$this->val .
							"</param>\n</params>";
					}
					else
					{
						/// @todo try to build something serializable?
						die('cannot serialize xmlrpcresp objects whose content is native php values');
					}
				}
				else
				{
					$result .= "<params>\n<param>\n" .
						$this->val->serialize($charset_encoding) .
						"</param>\n</params>";
				}
			}
			$result .= "\n</methodResponse>";
			$this->payload = $result;
			return $result;
		}
1239114
public static InputStream wrapString(String str, Charset charset) {   
    return new ByteArrayInputStream(str.getBytes(charset));  
  }
1314624
public function encodeQ($str, $position = 'text')
    {
        // There should not be any EOL in the string
        $pattern = '';
        $encoded = str_replace(array("\r", "\n"), '', $str);
        switch (strtolower($position)) {
            case 'phrase':
                // RFC 2047 section 5.3
                $pattern = '^A-Za-z0-9!*+\/ -';
                break;
            /** @noinspection PhpMissingBreakStatementInspection */
            case 'comment':
                // RFC 2047 section 5.2
                $pattern = '\(\)"';
                // intentional fall-through
                // for this reason we build the $pattern without including delimiters and []
            case 'text':
            default:
                // RFC 2047 section 5.1
                // Replace every high ascii, control, =, ? and _ characters
                $pattern = '\000-\011\013\014\016-\037\075\077\137\177-\377' . $pattern;
                break;
        }
        $matches = array();
        if (preg_match_all("/[{$pattern}]/", $encoded, $matches)) {
            // If the string contains an '=', make sure it's the first thing we replace
            // so as to avoid double-encoding
            $eqkey = array_search('=', $matches[0]);
            if ($eqkey !== false) {
                unset($matches[0][$eqkey]);
                array_unshift($matches[0], '=');
            }
            foreach (array_unique($matches[0]) as $char) {
                $encoded = str_replace($char, '=' . sprintf('%02X', ord($char)), $encoded);
            }
        }
        // Replace every spaces to _ (more readable than =20)
        return str_replace(' ', '_', $encoded);
    }
870754
static public function PackStringWithLength($str)
    {
        $len = strlen($str);
        # UTF-8
        if (!self::ValidateUTF8($str)) {
            throw new Exception('Bad UTF-8 String');
        }
        return pack('n', $len) . $str;
    }
425246
public function str($len, $_charset = null) {
    if($_charset == null) {
      $_charset = $this->_charset;
    }

    $str = '';
    for ($i = 0; $i < $len; $i++) {
      $pos = $this->int(0,strlen($_charset)-1);
      $str .= $_charset[$pos];
    }
    return $str;
  }
281473
public static function textLength($strText, $strEncoding = '')
    {

        if (is_null(self::$blnMbstring)) {
            self::$blnMbstring = extension_loaded('mbstring');
        }

        if (!self::$blnMbstring) {
            $intTextLength = strlen($strText);
        } else {
            if ($strEncoding == '') {
                $intTextLength = mb_strlen($strText);
            } else {
                $intTextLength = mb_strlen($strText, $strEncoding);
            }
        }

        return $intTextLength;
    }
143366
public static function escapeString(string $str): string
    {
        // one of the characters ",", "+", """, "\", "<", ">" or ";"
        $str = preg_replace('/([,\+"\\\<\>;])/u', '\\\\$1', $str);
        // a space character occurring at the end of the string
        $str = preg_replace('/( )$/u', '\\\\$1', $str);
        // a space or "#" character occurring at the beginning of the string
        $str = preg_replace('/^([ #])/u', '\\\\$1', $str);
        // implementation specific special characters
        $str = preg_replace_callback('/([\pC])/u',
            function ($m) {
                $octets = str_split(bin2hex($m[1]), 2);
                return implode("",
                    array_map(
                        function ($octet) {
                            return '\\' . strtoupper($octet);
                        }, $octets));
            }, $str);
        return $str;
    }
823812
public static function base64Encode($str, $stripEgal = true)
    {
        $str64 = base64_encode($str);
        if ($stripEgal) {
            return rtrim(strtr($str64, '+/', '-_'), '=');
        }
        
        return $str64;
    }
575365
public static function format_flowed($text, $length = 72, $charset=null)
    {
        $text = preg_split('/\r?\n/', $text);

        foreach ($text as $idx => $line) {
            if ($line != '-- ') {
                if ($level = strspn($line, '>')) {
                    // remove quote chars
                    $line = substr($line, $level);
                    // remove (optional) space-staffing and spaces before the line end
                    $line = rtrim($line, ' ');
                    if ($line[0] === ' ') $line = substr($line, 1);

                    $prefix = str_repeat('>', $level) . ' ';
                    $line   = $prefix . self::wordwrap($line, $length - $level - 2, " \r\n$prefix", false, $charset);
                }
                else if ($line) {
                    $line = self::wordwrap(rtrim($line), $length - 2, " \r\n", false, $charset);
                    // space-stuffing
                    $line = preg_replace('/(^|\r\n)(From| |>)/', '\\1 \\2', $line);
                }

                $text[$idx] = $line;
            }
        }

        return implode("\r\n", $text);
    }
799016
public function EncodeString($str, $encoding = 'base64')
    {
        $encoded = '';
        switch (strtolower($encoding)) {
            case 'base64':
                $encoded = chunk_split(base64_encode($str), 76, $this->LE);
                break;
            case '7bit':
            case '8bit':
                $encoded = $this->FixEOL($str);
                //Make sure it ends with a line break
                if (substr($encoded, -(strlen($this->LE))) != $this->LE) {
                    $encoded .= $this->LE;
                }

                break;
            case 'binary':
                $encoded = $str;
                break;
            case 'quoted-printable':
                $encoded = $this->EncodeQP($str);
                break;
            default:
                $this->SetError($this->Lang('encoding') . $encoding);
                break;
        }
        return $encoded;
    }
878779
public function encode_qp ($str) {
    $encoded = $this->fix_eol($str);
    if (substr($encoded, -2) != $this->LE)
        $encoded .= $this->LE;

    // Replace every high ascii, control and = characters
    $encoded = preg_replace_callback("/([\001-\010\013\014\016-\037\075\177-\377])/",
              array($this,'qp_replace_high_ascii'), $encoded);
    // Replace every spaces and tabs when it's the last character on a line
    $encoded = preg_replace_callback("/([\011\040])".$this->LE."/",
              array($this,'qp_replace_end_whitespace'), $encoded);

    // Maximum line length of 76 characters before CRLF (74 + space + '=')
    $encoded = $this->word_wrap($encoded, 74, true);

    return $encoded;
  }
711460
public function encodeString($string, $firstLineOffset = 0, $maxLineLength = 0)
    {
        $lines = [];
        $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);
    }