AbstractHeader.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Mime\Header;
  11. use Symfony\Component\Mime\Encoder\QpMimeHeaderEncoder;
  12. /**
  13. * An abstract base MIME Header.
  14. *
  15. * @author Chris Corbyn
  16. */
  17. abstract class AbstractHeader implements HeaderInterface
  18. {
  19. public const PHRASE_PATTERN = '(?:(?:(?:(?:(?:(?:(?:[ \t]*(?:\r\n))?[ \t])?(\((?:(?:(?:[ \t]*(?:\r\n))?[ \t])|(?:(?:[\x01-\x08\x0B\x0C\x0E-\x19\x7F]|[\x21-\x27\x2A-\x5B\x5D-\x7E])|(?:\\[\x00-\x08\x0B\x0C\x0E-\x7F])|(?1)))*(?:(?:[ \t]*(?:\r\n))?[ \t])?\)))*(?:(?:(?:(?:[ \t]*(?:\r\n))?[ \t])?(\((?:(?:(?:[ \t]*(?:\r\n))?[ \t])|(?:(?:[\x01-\x08\x0B\x0C\x0E-\x19\x7F]|[\x21-\x27\x2A-\x5B\x5D-\x7E])|(?:\\[\x00-\x08\x0B\x0C\x0E-\x7F])|(?1)))*(?:(?:[ \t]*(?:\r\n))?[ \t])?\)))|(?:(?:[ \t]*(?:\r\n))?[ \t])))?[a-zA-Z0-9!#\$%&\'\*\+\-\/=\?\^_`\{\}\|~]+(?:(?:(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t])?(\((?:(?:(?:[ \t]*(?:\r\n))?[ \t])|(?:(?:[\x01-\x08\x0B\x0C\x0E-\x19\x7F]|[\x21-\x27\x2A-\x5B\x5D-\x7E])|(?:\\[\x00-\x08\x0B\x0C\x0E-\x7F])|(?1)))*(?:(?:[ \t]*(?:\r\n))?[ \t])?\)))*(?:(?:(?:(?:[ \t]*(?:\r\n))?[ \t])?(\((?:(?:(?:[ \t]*(?:\r\n))?[ \t])|(?:(?:[\x01-\x08\x0B\x0C\x0E-\x19\x7F]|[\x21-\x27\x2A-\x5B\x5D-\x7E])|(?:\\[\x00-\x08\x0B\x0C\x0E-\x7F])|(?1)))*(?:(?:[ \t]*(?:\r\n))?[ \t])?\)))|(?:(?:[ \t]*(?:\r\n))?[ \t])))?))+?)';
  20. private static $encoder;
  21. private $name;
  22. private $lineLength = 76;
  23. private $lang;
  24. private $charset = 'utf-8';
  25. public function __construct(string $name)
  26. {
  27. $this->name = $name;
  28. }
  29. public function setCharset(string $charset)
  30. {
  31. $this->charset = $charset;
  32. }
  33. public function getCharset(): ?string
  34. {
  35. return $this->charset;
  36. }
  37. /**
  38. * Set the language used in this Header.
  39. *
  40. * For example, for US English, 'en-us'.
  41. */
  42. public function setLanguage(string $lang)
  43. {
  44. $this->lang = $lang;
  45. }
  46. public function getLanguage(): ?string
  47. {
  48. return $this->lang;
  49. }
  50. public function getName(): string
  51. {
  52. return $this->name;
  53. }
  54. public function setMaxLineLength(int $lineLength)
  55. {
  56. $this->lineLength = $lineLength;
  57. }
  58. public function getMaxLineLength(): int
  59. {
  60. return $this->lineLength;
  61. }
  62. public function toString(): string
  63. {
  64. return $this->tokensToString($this->toTokens());
  65. }
  66. /**
  67. * Produces a compliant, formatted RFC 2822 'phrase' based on the string given.
  68. *
  69. * @param string $string as displayed
  70. * @param bool $shorten the first line to make remove for header name
  71. */
  72. protected function createPhrase(HeaderInterface $header, string $string, string $charset, bool $shorten = false): string
  73. {
  74. // Treat token as exactly what was given
  75. $phraseStr = $string;
  76. // If it's not valid
  77. if (!preg_match('/^'.self::PHRASE_PATTERN.'$/D', $phraseStr)) {
  78. // .. but it is just ascii text, try escaping some characters
  79. // and make it a quoted-string
  80. if (preg_match('/^[\x00-\x08\x0B\x0C\x0E-\x7F]*$/D', $phraseStr)) {
  81. foreach (['\\', '"'] as $char) {
  82. $phraseStr = str_replace($char, '\\'.$char, $phraseStr);
  83. }
  84. $phraseStr = '"'.$phraseStr.'"';
  85. } else {
  86. // ... otherwise it needs encoding
  87. // Determine space remaining on line if first line
  88. if ($shorten) {
  89. $usedLength = \strlen($header->getName().': ');
  90. } else {
  91. $usedLength = 0;
  92. }
  93. $phraseStr = $this->encodeWords($header, $string, $usedLength);
  94. }
  95. } elseif (str_contains($phraseStr, '(')) {
  96. foreach (['\\', '"'] as $char) {
  97. $phraseStr = str_replace($char, '\\'.$char, $phraseStr);
  98. }
  99. $phraseStr = '"'.$phraseStr.'"';
  100. }
  101. return $phraseStr;
  102. }
  103. /**
  104. * Encode needed word tokens within a string of input.
  105. */
  106. protected function encodeWords(HeaderInterface $header, string $input, int $usedLength = -1): string
  107. {
  108. $value = '';
  109. $tokens = $this->getEncodableWordTokens($input);
  110. foreach ($tokens as $token) {
  111. // See RFC 2822, Sect 2.2 (really 2.2 ??)
  112. if ($this->tokenNeedsEncoding($token)) {
  113. // Don't encode starting WSP
  114. $firstChar = substr($token, 0, 1);
  115. switch ($firstChar) {
  116. case ' ':
  117. case "\t":
  118. $value .= $firstChar;
  119. $token = substr($token, 1);
  120. }
  121. if (-1 == $usedLength) {
  122. $usedLength = \strlen($header->getName().': ') + \strlen($value);
  123. }
  124. $value .= $this->getTokenAsEncodedWord($token, $usedLength);
  125. } else {
  126. $value .= $token;
  127. }
  128. }
  129. return $value;
  130. }
  131. protected function tokenNeedsEncoding(string $token): bool
  132. {
  133. return (bool) preg_match('~[\x00-\x08\x10-\x19\x7F-\xFF\r\n]~', $token);
  134. }
  135. /**
  136. * Splits a string into tokens in blocks of words which can be encoded quickly.
  137. *
  138. * @return string[]
  139. */
  140. protected function getEncodableWordTokens(string $string): array
  141. {
  142. $tokens = [];
  143. $encodedToken = '';
  144. // Split at all whitespace boundaries
  145. foreach (preg_split('~(?=[\t ])~', $string) as $token) {
  146. if ($this->tokenNeedsEncoding($token)) {
  147. $encodedToken .= $token;
  148. } else {
  149. if ('' !== $encodedToken) {
  150. $tokens[] = $encodedToken;
  151. $encodedToken = '';
  152. }
  153. $tokens[] = $token;
  154. }
  155. }
  156. if ('' !== $encodedToken) {
  157. $tokens[] = $encodedToken;
  158. }
  159. foreach ($tokens as $i => $token) {
  160. // whitespace(s) between 2 encoded tokens
  161. if (
  162. 0 < $i
  163. && isset($tokens[$i + 1])
  164. && preg_match('~^[\t ]+$~', $token)
  165. && $this->tokenNeedsEncoding($tokens[$i - 1])
  166. && $this->tokenNeedsEncoding($tokens[$i + 1])
  167. ) {
  168. $tokens[$i - 1] .= $token.$tokens[$i + 1];
  169. array_splice($tokens, $i, 2);
  170. }
  171. }
  172. return $tokens;
  173. }
  174. /**
  175. * Get a token as an encoded word for safe insertion into headers.
  176. */
  177. protected function getTokenAsEncodedWord(string $token, int $firstLineOffset = 0): string
  178. {
  179. if (null === self::$encoder) {
  180. self::$encoder = new QpMimeHeaderEncoder();
  181. }
  182. // Adjust $firstLineOffset to account for space needed for syntax
  183. $charsetDecl = $this->charset;
  184. if (null !== $this->lang) {
  185. $charsetDecl .= '*'.$this->lang;
  186. }
  187. $encodingWrapperLength = \strlen('=?'.$charsetDecl.'?'.self::$encoder->getName().'??=');
  188. if ($firstLineOffset >= 75) {
  189. // Does this logic need to be here?
  190. $firstLineOffset = 0;
  191. }
  192. $encodedTextLines = explode("\r\n",
  193. self::$encoder->encodeString($token, $this->charset, $firstLineOffset, 75 - $encodingWrapperLength)
  194. );
  195. if ('iso-2022-jp' !== strtolower($this->charset)) {
  196. // special encoding for iso-2022-jp using mb_encode_mimeheader
  197. foreach ($encodedTextLines as $lineNum => $line) {
  198. $encodedTextLines[$lineNum] = '=?'.$charsetDecl.'?'.self::$encoder->getName().'?'.$line.'?=';
  199. }
  200. }
  201. return implode("\r\n ", $encodedTextLines);
  202. }
  203. /**
  204. * Generates tokens from the given string which include CRLF as individual tokens.
  205. *
  206. * @return string[]
  207. */
  208. protected function generateTokenLines(string $token): array
  209. {
  210. return preg_split('~(\r\n)~', $token, -1, \PREG_SPLIT_DELIM_CAPTURE);
  211. }
  212. /**
  213. * Generate a list of all tokens in the final header.
  214. */
  215. protected function toTokens(?string $string = null): array
  216. {
  217. if (null === $string) {
  218. $string = $this->getBodyAsString();
  219. }
  220. $tokens = [];
  221. // Generate atoms; split at all invisible boundaries followed by WSP
  222. foreach (preg_split('~(?=[ \t])~', $string) as $token) {
  223. $newTokens = $this->generateTokenLines($token);
  224. foreach ($newTokens as $newToken) {
  225. $tokens[] = $newToken;
  226. }
  227. }
  228. return $tokens;
  229. }
  230. /**
  231. * Takes an array of tokens which appear in the header and turns them into
  232. * an RFC 2822 compliant string, adding FWSP where needed.
  233. *
  234. * @param string[] $tokens
  235. */
  236. private function tokensToString(array $tokens): string
  237. {
  238. $lineCount = 0;
  239. $headerLines = [];
  240. $headerLines[] = $this->name.': ';
  241. $currentLine = &$headerLines[$lineCount++];
  242. // Build all tokens back into compliant header
  243. foreach ($tokens as $i => $token) {
  244. // Line longer than specified maximum or token was just a new line
  245. if (("\r\n" === $token) ||
  246. ($i > 0 && \strlen($currentLine.$token) > $this->lineLength)
  247. && '' !== $currentLine) {
  248. $headerLines[] = '';
  249. $currentLine = &$headerLines[$lineCount++];
  250. }
  251. // Append token to the line
  252. if ("\r\n" !== $token) {
  253. $currentLine .= $token;
  254. }
  255. }
  256. // Implode with FWS (RFC 2822, 2.2.3)
  257. return implode("\r\n", $headerLines);
  258. }
  259. }