AbstractHeader.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  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. 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]*(?:\r\n))?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(?:\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. }
  96. return $phraseStr;
  97. }
  98. /**
  99. * Encode needed word tokens within a string of input.
  100. */
  101. protected function encodeWords(HeaderInterface $header, string $input, int $usedLength = -1): string
  102. {
  103. $value = '';
  104. $tokens = $this->getEncodableWordTokens($input);
  105. foreach ($tokens as $token) {
  106. // See RFC 2822, Sect 2.2 (really 2.2 ??)
  107. if ($this->tokenNeedsEncoding($token)) {
  108. // Don't encode starting WSP
  109. $firstChar = substr($token, 0, 1);
  110. switch ($firstChar) {
  111. case ' ':
  112. case "\t":
  113. $value .= $firstChar;
  114. $token = substr($token, 1);
  115. }
  116. if (-1 == $usedLength) {
  117. $usedLength = \strlen($header->getName().': ') + \strlen($value);
  118. }
  119. $value .= $this->getTokenAsEncodedWord($token, $usedLength);
  120. } else {
  121. $value .= $token;
  122. }
  123. }
  124. return $value;
  125. }
  126. protected function tokenNeedsEncoding(string $token): bool
  127. {
  128. return (bool) preg_match('~[\x00-\x08\x10-\x19\x7F-\xFF\r\n]~', $token);
  129. }
  130. /**
  131. * Splits a string into tokens in blocks of words which can be encoded quickly.
  132. *
  133. * @return string[]
  134. */
  135. protected function getEncodableWordTokens(string $string): array
  136. {
  137. $tokens = [];
  138. $encodedToken = '';
  139. // Split at all whitespace boundaries
  140. foreach (preg_split('~(?=[\t ])~', $string) as $token) {
  141. if ($this->tokenNeedsEncoding($token)) {
  142. $encodedToken .= $token;
  143. } else {
  144. if (\strlen($encodedToken) > 0) {
  145. $tokens[] = $encodedToken;
  146. $encodedToken = '';
  147. }
  148. $tokens[] = $token;
  149. }
  150. }
  151. if (\strlen($encodedToken)) {
  152. $tokens[] = $encodedToken;
  153. }
  154. return $tokens;
  155. }
  156. /**
  157. * Get a token as an encoded word for safe insertion into headers.
  158. */
  159. protected function getTokenAsEncodedWord(string $token, int $firstLineOffset = 0): string
  160. {
  161. if (null === self::$encoder) {
  162. self::$encoder = new QpMimeHeaderEncoder();
  163. }
  164. // Adjust $firstLineOffset to account for space needed for syntax
  165. $charsetDecl = $this->charset;
  166. if (null !== $this->lang) {
  167. $charsetDecl .= '*'.$this->lang;
  168. }
  169. $encodingWrapperLength = \strlen('=?'.$charsetDecl.'?'.self::$encoder->getName().'??=');
  170. if ($firstLineOffset >= 75) {
  171. //Does this logic need to be here?
  172. $firstLineOffset = 0;
  173. }
  174. $encodedTextLines = explode("\r\n",
  175. self::$encoder->encodeString($token, $this->charset, $firstLineOffset, 75 - $encodingWrapperLength)
  176. );
  177. if ('iso-2022-jp' !== strtolower($this->charset)) {
  178. // special encoding for iso-2022-jp using mb_encode_mimeheader
  179. foreach ($encodedTextLines as $lineNum => $line) {
  180. $encodedTextLines[$lineNum] = '=?'.$charsetDecl.'?'.self::$encoder->getName().'?'.$line.'?=';
  181. }
  182. }
  183. return implode("\r\n ", $encodedTextLines);
  184. }
  185. /**
  186. * Generates tokens from the given string which include CRLF as individual tokens.
  187. *
  188. * @return string[]
  189. */
  190. protected function generateTokenLines(string $token): array
  191. {
  192. return preg_split('~(\r\n)~', $token, -1, \PREG_SPLIT_DELIM_CAPTURE);
  193. }
  194. /**
  195. * Generate a list of all tokens in the final header.
  196. */
  197. protected function toTokens(string $string = null): array
  198. {
  199. if (null === $string) {
  200. $string = $this->getBodyAsString();
  201. }
  202. $tokens = [];
  203. // Generate atoms; split at all invisible boundaries followed by WSP
  204. foreach (preg_split('~(?=[ \t])~', $string) as $token) {
  205. $newTokens = $this->generateTokenLines($token);
  206. foreach ($newTokens as $newToken) {
  207. $tokens[] = $newToken;
  208. }
  209. }
  210. return $tokens;
  211. }
  212. /**
  213. * Takes an array of tokens which appear in the header and turns them into
  214. * an RFC 2822 compliant string, adding FWSP where needed.
  215. *
  216. * @param string[] $tokens
  217. */
  218. private function tokensToString(array $tokens): string
  219. {
  220. $lineCount = 0;
  221. $headerLines = [];
  222. $headerLines[] = $this->name.': ';
  223. $currentLine = &$headerLines[$lineCount++];
  224. // Build all tokens back into compliant header
  225. foreach ($tokens as $i => $token) {
  226. // Line longer than specified maximum or token was just a new line
  227. if (("\r\n" === $token) ||
  228. ($i > 0 && \strlen($currentLine.$token) > $this->lineLength)
  229. && 0 < \strlen($currentLine)) {
  230. $headerLines[] = '';
  231. $currentLine = &$headerLines[$lineCount++];
  232. }
  233. // Append token to the line
  234. if ("\r\n" !== $token) {
  235. $currentLine .= $token;
  236. }
  237. }
  238. // Implode with FWS (RFC 2822, 2.2.3)
  239. return implode("\r\n", $headerLines);
  240. }
  241. }