AbstractHeader.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  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!#\$%&\'\*\+\-\/=\?\^_`\{\}\|~]+(?:(?:(?:(?:[ \t]*(?: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[ \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. return $tokens;
  160. }
  161. /**
  162. * Get a token as an encoded word for safe insertion into headers.
  163. */
  164. protected function getTokenAsEncodedWord(string $token, int $firstLineOffset = 0): string
  165. {
  166. if (null === self::$encoder) {
  167. self::$encoder = new QpMimeHeaderEncoder();
  168. }
  169. // Adjust $firstLineOffset to account for space needed for syntax
  170. $charsetDecl = $this->charset;
  171. if (null !== $this->lang) {
  172. $charsetDecl .= '*'.$this->lang;
  173. }
  174. $encodingWrapperLength = \strlen('=?'.$charsetDecl.'?'.self::$encoder->getName().'??=');
  175. if ($firstLineOffset >= 75) {
  176. // Does this logic need to be here?
  177. $firstLineOffset = 0;
  178. }
  179. $encodedTextLines = explode("\r\n",
  180. self::$encoder->encodeString($token, $this->charset, $firstLineOffset, 75 - $encodingWrapperLength)
  181. );
  182. if ('iso-2022-jp' !== strtolower($this->charset)) {
  183. // special encoding for iso-2022-jp using mb_encode_mimeheader
  184. foreach ($encodedTextLines as $lineNum => $line) {
  185. $encodedTextLines[$lineNum] = '=?'.$charsetDecl.'?'.self::$encoder->getName().'?'.$line.'?=';
  186. }
  187. }
  188. return implode("\r\n ", $encodedTextLines);
  189. }
  190. /**
  191. * Generates tokens from the given string which include CRLF as individual tokens.
  192. *
  193. * @return string[]
  194. */
  195. protected function generateTokenLines(string $token): array
  196. {
  197. return preg_split('~(\r\n)~', $token, -1, \PREG_SPLIT_DELIM_CAPTURE);
  198. }
  199. /**
  200. * Generate a list of all tokens in the final header.
  201. */
  202. protected function toTokens(string $string = null): array
  203. {
  204. if (null === $string) {
  205. $string = $this->getBodyAsString();
  206. }
  207. $tokens = [];
  208. // Generate atoms; split at all invisible boundaries followed by WSP
  209. foreach (preg_split('~(?=[ \t])~', $string) as $token) {
  210. $newTokens = $this->generateTokenLines($token);
  211. foreach ($newTokens as $newToken) {
  212. $tokens[] = $newToken;
  213. }
  214. }
  215. return $tokens;
  216. }
  217. /**
  218. * Takes an array of tokens which appear in the header and turns them into
  219. * an RFC 2822 compliant string, adding FWSP where needed.
  220. *
  221. * @param string[] $tokens
  222. */
  223. private function tokensToString(array $tokens): string
  224. {
  225. $lineCount = 0;
  226. $headerLines = [];
  227. $headerLines[] = $this->name.': ';
  228. $currentLine = &$headerLines[$lineCount++];
  229. // Build all tokens back into compliant header
  230. foreach ($tokens as $i => $token) {
  231. // Line longer than specified maximum or token was just a new line
  232. if (("\r\n" === $token) ||
  233. ($i > 0 && \strlen($currentLine.$token) > $this->lineLength)
  234. && '' !== $currentLine) {
  235. $headerLines[] = '';
  236. $currentLine = &$headerLines[$lineCount++];
  237. }
  238. // Append token to the line
  239. if ("\r\n" !== $token) {
  240. $currentLine .= $token;
  241. }
  242. }
  243. // Implode with FWS (RFC 2822, 2.2.3)
  244. return implode("\r\n", $headerLines);
  245. }
  246. }