AbstractHeader.php 11KB

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