AbstractHeader.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  1. <?php
  2. /*
  3. * This file is part of SwiftMailer.
  4. * (c) 2004-2009 Chris Corbyn
  5. *
  6. * For the full copyright and license information, please view the LICENSE
  7. * file that was distributed with this source code.
  8. */
  9. /**
  10. * An abstract base MIME Header.
  11. *
  12. * @author Chris Corbyn
  13. */
  14. abstract class Swift_Mime_Headers_AbstractHeader implements Swift_Mime_Header
  15. {
  16. /**
  17. * The name of this Header.
  18. *
  19. * @var string
  20. */
  21. private $_name;
  22. /**
  23. * The Grammar used for this Header.
  24. *
  25. * @var Swift_Mime_Grammar
  26. */
  27. private $_grammar;
  28. /**
  29. * The Encoder used to encode this Header.
  30. *
  31. * @var Swift_Encoder
  32. */
  33. private $_encoder;
  34. /**
  35. * The maximum length of a line in the header.
  36. *
  37. * @var int
  38. */
  39. private $_lineLength = 78;
  40. /**
  41. * The language used in this Header.
  42. *
  43. * @var string
  44. */
  45. private $_lang;
  46. /**
  47. * The character set of the text in this Header.
  48. *
  49. * @var string
  50. */
  51. private $_charset = 'utf-8';
  52. /**
  53. * The value of this Header, cached.
  54. *
  55. * @var string
  56. */
  57. private $_cachedValue = null;
  58. /**
  59. * Creates a new Header.
  60. *
  61. * @param Swift_Mime_Grammar $grammar
  62. */
  63. public function __construct(Swift_Mime_Grammar $grammar)
  64. {
  65. $this->setGrammar($grammar);
  66. }
  67. /**
  68. * Set the character set used in this Header.
  69. *
  70. * @param string $charset
  71. */
  72. public function setCharset($charset)
  73. {
  74. $this->clearCachedValueIf($charset != $this->_charset);
  75. $this->_charset = $charset;
  76. if (isset($this->_encoder)) {
  77. $this->_encoder->charsetChanged($charset);
  78. }
  79. }
  80. /**
  81. * Get the character set used in this Header.
  82. *
  83. * @return string
  84. */
  85. public function getCharset()
  86. {
  87. return $this->_charset;
  88. }
  89. /**
  90. * Set the language used in this Header.
  91. *
  92. * For example, for US English, 'en-us'.
  93. * This can be unspecified.
  94. *
  95. * @param string $lang
  96. */
  97. public function setLanguage($lang)
  98. {
  99. $this->clearCachedValueIf($this->_lang != $lang);
  100. $this->_lang = $lang;
  101. }
  102. /**
  103. * Get the language used in this Header.
  104. *
  105. * @return string
  106. */
  107. public function getLanguage()
  108. {
  109. return $this->_lang;
  110. }
  111. /**
  112. * Set the encoder used for encoding the header.
  113. *
  114. * @param Swift_Mime_HeaderEncoder $encoder
  115. */
  116. public function setEncoder(Swift_Mime_HeaderEncoder $encoder)
  117. {
  118. $this->_encoder = $encoder;
  119. $this->setCachedValue(null);
  120. }
  121. /**
  122. * Get the encoder used for encoding this Header.
  123. *
  124. * @return Swift_Mime_HeaderEncoder
  125. */
  126. public function getEncoder()
  127. {
  128. return $this->_encoder;
  129. }
  130. /**
  131. * Set the grammar used for the header.
  132. *
  133. * @param Swift_Mime_Grammar $grammar
  134. */
  135. public function setGrammar(Swift_Mime_Grammar $grammar)
  136. {
  137. $this->_grammar = $grammar;
  138. $this->setCachedValue(null);
  139. }
  140. /**
  141. * Get the grammar used for this Header.
  142. *
  143. * @return Swift_Mime_Grammar
  144. */
  145. public function getGrammar()
  146. {
  147. return $this->_grammar;
  148. }
  149. /**
  150. * Get the name of this header (e.g. charset).
  151. *
  152. * @return string
  153. */
  154. public function getFieldName()
  155. {
  156. return $this->_name;
  157. }
  158. /**
  159. * Set the maximum length of lines in the header (excluding EOL).
  160. *
  161. * @param int $lineLength
  162. */
  163. public function setMaxLineLength($lineLength)
  164. {
  165. $this->clearCachedValueIf($this->_lineLength != $lineLength);
  166. $this->_lineLength = $lineLength;
  167. }
  168. /**
  169. * Get the maximum permitted length of lines in this Header.
  170. *
  171. * @return int
  172. */
  173. public function getMaxLineLength()
  174. {
  175. return $this->_lineLength;
  176. }
  177. /**
  178. * Get this Header rendered as a RFC 2822 compliant string.
  179. *
  180. * @return string
  181. *
  182. * @throws Swift_RfcComplianceException
  183. */
  184. public function toString()
  185. {
  186. return $this->_tokensToString($this->toTokens());
  187. }
  188. /**
  189. * Returns a string representation of this object.
  190. *
  191. * @return string
  192. *
  193. * @see toString()
  194. */
  195. public function __toString()
  196. {
  197. return $this->toString();
  198. }
  199. // -- Points of extension
  200. /**
  201. * Set the name of this Header field.
  202. *
  203. * @param string $name
  204. */
  205. protected function setFieldName($name)
  206. {
  207. $this->_name = $name;
  208. }
  209. /**
  210. * Produces a compliant, formatted RFC 2822 'phrase' based on the string given.
  211. *
  212. * @param Swift_Mime_Header $header
  213. * @param string $string as displayed
  214. * @param string $charset of the text
  215. * @param Swift_Mime_HeaderEncoder $encoder
  216. * @param bool $shorten the first line to make remove for header name
  217. *
  218. * @return string
  219. */
  220. protected function createPhrase(Swift_Mime_Header $header, $string, $charset, Swift_Mime_HeaderEncoder $encoder = null, $shorten = false)
  221. {
  222. // Treat token as exactly what was given
  223. $phraseStr = $string;
  224. // If it's not valid
  225. if (!preg_match('/^' . $this->getGrammar()->getDefinition('phrase') . '$/D', $phraseStr)) {
  226. // .. but it is just ascii text, try escaping some characters
  227. // and make it a quoted-string
  228. if (preg_match('/^' . $this->getGrammar()->getDefinition('text') . '*$/D', $phraseStr)) {
  229. $phraseStr = $this->getGrammar()->escapeSpecials(
  230. $phraseStr, array('"'), $this->getGrammar()->getSpecials()
  231. );
  232. $phraseStr = '"' . $phraseStr . '"';
  233. } else { // ... otherwise it needs encoding
  234. // Determine space remaining on line if first line
  235. if ($shorten) {
  236. $usedLength = strlen($header->getFieldName() . ': ');
  237. } else {
  238. $usedLength = 0;
  239. }
  240. $phraseStr = $this->encodeWords($header, $string, $usedLength);
  241. }
  242. }
  243. return $phraseStr;
  244. }
  245. /**
  246. * Encode needed word tokens within a string of input.
  247. *
  248. * @param Swift_Mime_Header $header
  249. * @param string $input
  250. * @param string $usedLength optional
  251. *
  252. * @return string
  253. */
  254. protected function encodeWords(Swift_Mime_Header $header, $input, $usedLength = -1)
  255. {
  256. $value = '';
  257. $tokens = $this->getEncodableWordTokens($input);
  258. foreach ($tokens as $token) {
  259. // See RFC 2822, Sect 2.2 (really 2.2 ??)
  260. if ($this->tokenNeedsEncoding($token)) {
  261. // Don't encode starting WSP
  262. $firstChar = substr($token, 0, 1);
  263. switch ($firstChar) {
  264. case ' ':
  265. case "\t":
  266. $value .= $firstChar;
  267. $token = substr($token, 1);
  268. }
  269. if (-1 == $usedLength) {
  270. $usedLength = strlen($header->getFieldName() . ': ') + strlen($value);
  271. }
  272. $value .= $this->getTokenAsEncodedWord($token, $usedLength);
  273. $header->setMaxLineLength(76); // Forcefully override
  274. } else {
  275. $value .= $token;
  276. }
  277. }
  278. return $value;
  279. }
  280. /**
  281. * Test if a token needs to be encoded or not.
  282. *
  283. * @param string $token
  284. *
  285. * @return bool
  286. */
  287. protected function tokenNeedsEncoding($token)
  288. {
  289. return preg_match('~[\x00-\x08\x10-\x19\x7F-\xFF\r\n]~', $token);
  290. }
  291. /**
  292. * Splits a string into tokens in blocks of words which can be encoded quickly.
  293. *
  294. * @param string $string
  295. *
  296. * @return string[]
  297. */
  298. protected function getEncodableWordTokens($string)
  299. {
  300. $tokens = array();
  301. $encodedToken = '';
  302. // Split at all whitespace boundaries
  303. foreach (preg_split('~(?=[\t ])~', $string) as $token) {
  304. if ($this->tokenNeedsEncoding($token)) {
  305. $encodedToken .= $token;
  306. } else {
  307. if (strlen($encodedToken) > 0) {
  308. $tokens[] = $encodedToken;
  309. $encodedToken = '';
  310. }
  311. $tokens[] = $token;
  312. }
  313. }
  314. if (strlen($encodedToken)) {
  315. $tokens[] = $encodedToken;
  316. }
  317. return $tokens;
  318. }
  319. /**
  320. * Get a token as an encoded word for safe insertion into headers.
  321. *
  322. * @param string $token token to encode
  323. * @param int $firstLineOffset optional
  324. *
  325. * @return string
  326. */
  327. protected function getTokenAsEncodedWord($token, $firstLineOffset = 0)
  328. {
  329. // Adjust $firstLineOffset to account for space needed for syntax
  330. $charsetDecl = $this->_charset;
  331. if (isset($this->_lang)) {
  332. $charsetDecl .= '*' . $this->_lang;
  333. }
  334. $encodingWrapperLength = strlen(
  335. '=?' . $charsetDecl . '?' . $this->_encoder->getName() . '??='
  336. );
  337. if ($firstLineOffset >= 75) { //Does this logic need to be here?
  338. $firstLineOffset = 0;
  339. }
  340. $encodedTextLines = explode("\r\n",
  341. $this->_encoder->encodeString(
  342. $token, $firstLineOffset, 75 - $encodingWrapperLength, $this->_charset
  343. )
  344. );
  345. if (strtolower($this->_charset) !== 'iso-2022-jp') { // special encoding for iso-2022-jp using mb_encode_mimeheader
  346. foreach ($encodedTextLines as $lineNum => $line) {
  347. $encodedTextLines[$lineNum] = '=?' . $charsetDecl .
  348. '?' . $this->_encoder->getName() .
  349. '?' . $line . '?=';
  350. }
  351. }
  352. return implode("\r\n ", $encodedTextLines);
  353. }
  354. /**
  355. * Generates tokens from the given string which include CRLF as individual tokens.
  356. *
  357. * @param string $token
  358. *
  359. * @return string[]
  360. */
  361. protected function generateTokenLines($token)
  362. {
  363. return preg_split('~(\r\n)~', $token, -1, PREG_SPLIT_DELIM_CAPTURE);
  364. }
  365. /**
  366. * Set a value into the cache.
  367. *
  368. * @param string $value
  369. */
  370. protected function setCachedValue($value)
  371. {
  372. $this->_cachedValue = $value;
  373. }
  374. /**
  375. * Get the value in the cache.
  376. *
  377. * @return string
  378. */
  379. protected function getCachedValue()
  380. {
  381. return $this->_cachedValue;
  382. }
  383. /**
  384. * Clear the cached value if $condition is met.
  385. *
  386. * @param bool $condition
  387. */
  388. protected function clearCachedValueIf($condition)
  389. {
  390. if ($condition) {
  391. $this->setCachedValue(null);
  392. }
  393. }
  394. /**
  395. * Generate a list of all tokens in the final header.
  396. *
  397. * @param string $string The string to tokenize
  398. *
  399. * @return array An array of tokens as strings
  400. */
  401. protected function toTokens($string = null)
  402. {
  403. if (is_null($string)) {
  404. $string = $this->getFieldBody();
  405. }
  406. $tokens = array();
  407. // Generate atoms; split at all invisible boundaries followed by WSP
  408. foreach (preg_split('~(?=[ \t])~', $string) as $token) {
  409. $newTokens = $this->generateTokenLines($token);
  410. foreach ($newTokens as $newToken) {
  411. $tokens[] = $newToken;
  412. }
  413. }
  414. return $tokens;
  415. }
  416. /**
  417. * Takes an array of tokens which appear in the header and turns them into
  418. * an RFC 2822 compliant string, adding FWSP where needed.
  419. *
  420. * @param string[] $tokens
  421. *
  422. * @return string
  423. */
  424. private function _tokensToString(array $tokens)
  425. {
  426. $lineCount = 0;
  427. $headerLines = array();
  428. $headerLines[] = $this->_name . ': ';
  429. $currentLine =& $headerLines[$lineCount++];
  430. // Build all tokens back into compliant header
  431. foreach ($tokens as $i => $token) {
  432. // Line longer than specified maximum or token was just a new line
  433. if (("\r\n" == $token) ||
  434. ($i > 0 && strlen($currentLine . $token) > $this->_lineLength)
  435. && 0 < strlen($currentLine))
  436. {
  437. $headerLines[] = '';
  438. $currentLine =& $headerLines[$lineCount++];
  439. }
  440. // Append token to the line
  441. if ("\r\n" != $token) {
  442. $currentLine .= $token;
  443. }
  444. }
  445. // Implode with FWS (RFC 2822, 2.2.3)
  446. return implode("\r\n", $headerLines) . "\r\n";
  447. }
  448. }