AbstractHeader.php 11 KB

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