MailFormatHelper.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. <?php
  2. namespace Drupal\Core\Mail;
  3. use Drupal\Component\Utility\Html;
  4. use Drupal\Component\Utility\Xss;
  5. use Drupal\Core\Site\Settings;
  6. /**
  7. * Defines a class containing utility methods for formatting mail messages.
  8. */
  9. class MailFormatHelper {
  10. /**
  11. * Internal array of urls replaced with tokens.
  12. *
  13. * @var array
  14. */
  15. protected static $urls = [];
  16. /**
  17. * Quoted regex expression based on base path.
  18. *
  19. * @var string
  20. */
  21. protected static $regexp;
  22. /**
  23. * Array of tags supported.
  24. *
  25. * @var array
  26. */
  27. protected static $supportedTags = [];
  28. /**
  29. * Performs format=flowed soft wrapping for mail (RFC 3676).
  30. *
  31. * We use delsp=yes wrapping, but only break non-spaced languages when
  32. * absolutely necessary to avoid compatibility issues.
  33. *
  34. * We deliberately use LF rather than CRLF, see MailManagerInterface::mail().
  35. *
  36. * @param string $text
  37. * The plain text to process.
  38. * @param string $indent
  39. * (optional) A string to indent the text with. Only '>' characters are
  40. * repeated on subsequent wrapped lines. Others are replaced by spaces.
  41. *
  42. * @return string
  43. * The content of the email as a string with formatting applied.
  44. */
  45. public static function wrapMail($text, $indent = '') {
  46. // Convert CRLF into LF.
  47. $text = str_replace("\r", '', $text);
  48. // See if soft-wrapping is allowed.
  49. $clean_indent = static::htmlToTextClean($indent);
  50. $soft = strpos($clean_indent, ' ') === FALSE;
  51. // Check if the string has line breaks.
  52. if (strpos($text, "\n") !== FALSE) {
  53. // Remove trailing spaces to make existing breaks hard, but leave
  54. // signature marker untouched (RFC 3676, Section 4.3).
  55. $text = preg_replace('/(?(?<!^--) +\n| +\n)/m', "\n", $text);
  56. // Wrap each line at the needed width.
  57. $lines = explode("\n", $text);
  58. array_walk($lines, '\Drupal\Core\Mail\MailFormatHelper::wrapMailLine', ['soft' => $soft, 'length' => strlen($indent)]);
  59. $text = implode("\n", $lines);
  60. }
  61. else {
  62. // Wrap this line.
  63. static::wrapMailLine($text, 0, ['soft' => $soft, 'length' => strlen($indent)]);
  64. }
  65. // Empty lines with nothing but spaces.
  66. $text = preg_replace('/^ +\n/m', "\n", $text);
  67. // Space-stuff special lines.
  68. $text = preg_replace('/^(>| |From)/m', ' $1', $text);
  69. // Apply indentation. We only include non-'>' indentation on the first line.
  70. $text = $indent . substr(preg_replace('/^/m', $clean_indent, $text), strlen($indent));
  71. return $text;
  72. }
  73. /**
  74. * Transforms an HTML string into plain text, preserving its structure.
  75. *
  76. * The output will be suitable for use as 'format=flowed; delsp=yes' text
  77. * (RFC 3676) and can be passed directly to MailManagerInterface::mail() for sending.
  78. *
  79. * We deliberately use LF rather than CRLF, see MailManagerInterface::mail().
  80. *
  81. * This function provides suitable alternatives for the following tags:
  82. * <a> <em> <i> <strong> <b> <br> <p> <blockquote> <ul> <ol> <li> <dl> <dt>
  83. * <dd> <h1> <h2> <h3> <h4> <h5> <h6> <hr>
  84. *
  85. * @param string $string
  86. * The string to be transformed.
  87. * @param array $allowed_tags
  88. * (optional) If supplied, a list of tags that will be transformed. If
  89. * omitted, all supported tags are transformed.
  90. *
  91. * @return string
  92. * The transformed string.
  93. */
  94. public static function htmlToText($string, $allowed_tags = NULL) {
  95. // Cache list of supported tags.
  96. if (empty(static::$supportedTags)) {
  97. static::$supportedTags = ['a', 'em', 'i', 'strong', 'b', 'br', 'p',
  98. 'blockquote', 'ul', 'ol', 'li', 'dl', 'dt', 'dd', 'h1', 'h2', 'h3',
  99. 'h4', 'h5', 'h6', 'hr',
  100. ];
  101. }
  102. // Make sure only supported tags are kept.
  103. $allowed_tags = isset($allowed_tags) ? array_intersect(static::$supportedTags, $allowed_tags) : static::$supportedTags;
  104. // Make sure tags, entities and attributes are well-formed and properly
  105. // nested.
  106. $string = Html::normalize(Xss::filter($string, $allowed_tags));
  107. // Apply inline styles.
  108. $string = preg_replace('!</?(em|i)((?> +)[^>]*)?>!i', '/', $string);
  109. $string = preg_replace('!</?(strong|b)((?> +)[^>]*)?>!i', '*', $string);
  110. // Replace inline <a> tags with the text of link and a footnote.
  111. // 'See <a href="https://www.drupal.org">the Drupal site</a>' becomes
  112. // 'See the Drupal site [1]' with the URL included as a footnote.
  113. static::htmlToMailUrls(NULL, TRUE);
  114. $pattern = '@(<a[^>]+?href="([^"]*)"[^>]*?>(.+?)</a>)@i';
  115. $string = preg_replace_callback($pattern, 'static::htmlToMailUrls', $string);
  116. $urls = static::htmlToMailUrls();
  117. $footnotes = '';
  118. if (count($urls)) {
  119. $footnotes .= "\n";
  120. for ($i = 0, $max = count($urls); $i < $max; $i++) {
  121. $footnotes .= '[' . ($i + 1) . '] ' . $urls[$i] . "\n";
  122. }
  123. }
  124. // Split tags from text.
  125. $split = preg_split('/<([^>]+?)>/', $string, -1, PREG_SPLIT_DELIM_CAPTURE);
  126. // Note: PHP ensures the array consists of alternating delimiters and
  127. // literals and begins and ends with a literal (inserting $null as
  128. // required).
  129. // Odd/even counter (tag or no tag).
  130. $tag = FALSE;
  131. // Case conversion function.
  132. $casing = NULL;
  133. $output = '';
  134. // All current indentation string chunks.
  135. $indent = [];
  136. // Array of counters for opened lists.
  137. $lists = [];
  138. foreach ($split as $value) {
  139. // Holds a string ready to be formatted and output.
  140. $chunk = NULL;
  141. // Process HTML tags (but don't output any literally).
  142. if ($tag) {
  143. list($tagname) = explode(' ', strtolower($value), 2);
  144. switch ($tagname) {
  145. // List counters.
  146. case 'ul':
  147. array_unshift($lists, '*');
  148. break;
  149. case 'ol':
  150. array_unshift($lists, 1);
  151. break;
  152. case '/ul':
  153. case '/ol':
  154. array_shift($lists);
  155. // Ensure blank new-line.
  156. $chunk = '';
  157. break;
  158. // Quotation/list markers, non-fancy headers.
  159. case 'blockquote':
  160. // Format=flowed indentation cannot be mixed with lists.
  161. $indent[] = count($lists) ? ' "' : '>';
  162. break;
  163. case 'li':
  164. $indent[] = isset($lists[0]) && is_numeric($lists[0]) ? ' ' . $lists[0]++ . ') ' : ' * ';
  165. break;
  166. case 'dd':
  167. $indent[] = ' ';
  168. break;
  169. case 'h3':
  170. $indent[] = '.... ';
  171. break;
  172. case 'h4':
  173. $indent[] = '.. ';
  174. break;
  175. case '/blockquote':
  176. if (count($lists)) {
  177. // Append closing quote for inline quotes (immediately).
  178. $output = rtrim($output, "> \n") . "\"\n";
  179. // Ensure blank new-line.
  180. $chunk = '';
  181. }
  182. // Intentional fall-through to the processing for '/li' and '/dd'.
  183. case '/li':
  184. case '/dd':
  185. array_pop($indent);
  186. break;
  187. case '/h3':
  188. case '/h4':
  189. array_pop($indent);
  190. // Intentional fall-through to the processing for '/h5' and '/h6'.
  191. case '/h5':
  192. case '/h6':
  193. // Ensure blank new-line.
  194. $chunk = '';
  195. break;
  196. // Fancy headers.
  197. case 'h1':
  198. $indent[] = '======== ';
  199. $casing = 'mb_strtoupper';
  200. break;
  201. case 'h2':
  202. $indent[] = '-------- ';
  203. $casing = 'mb_strtoupper';
  204. break;
  205. case '/h1':
  206. case '/h2':
  207. $casing = NULL;
  208. // Pad the line with dashes.
  209. $output = static::htmlToTextPad($output, ($tagname == '/h1') ? '=' : '-', ' ');
  210. array_pop($indent);
  211. // Ensure blank new-line.
  212. $chunk = '';
  213. break;
  214. // Horizontal rulers.
  215. case 'hr':
  216. // Insert immediately.
  217. $output .= static::wrapMail('', implode('', $indent)) . "\n";
  218. $output = static::htmlToTextPad($output, '-');
  219. break;
  220. // Paragraphs and definition lists.
  221. case '/p':
  222. case '/dl':
  223. // Ensure blank new-line.
  224. $chunk = '';
  225. break;
  226. }
  227. }
  228. // Process blocks of text.
  229. else {
  230. // Convert inline HTML text to plain text; not removing line-breaks or
  231. // white-space, since that breaks newlines when sanitizing plain-text.
  232. $value = trim(Html::decodeEntities($value));
  233. if (mb_strlen($value)) {
  234. $chunk = $value;
  235. }
  236. }
  237. // See if there is something waiting to be output.
  238. if (isset($chunk)) {
  239. // Apply any necessary case conversion.
  240. if (isset($casing)) {
  241. $chunk = call_user_func($casing, $chunk);
  242. }
  243. $line_endings = Settings::get('mail_line_endings', PHP_EOL);
  244. // Format it and apply the current indentation.
  245. $output .= static::wrapMail($chunk, implode('', $indent)) . $line_endings;
  246. // Remove non-quotation markers from indentation.
  247. $indent = array_map('\Drupal\Core\Mail\MailFormatHelper::htmlToTextClean', $indent);
  248. }
  249. $tag = !$tag;
  250. }
  251. return $output . $footnotes;
  252. }
  253. /**
  254. * Wraps words on a single line.
  255. *
  256. * Callback for array_walk() within
  257. * \Drupal\Core\Mail\MailFormatHelper::wrapMail().
  258. *
  259. * Note that we are skipping MIME content header lines, because attached
  260. * files, especially applications, could have long MIME types or long
  261. * filenames which result in line length longer than the 77 characters limit
  262. * and wrapping that line will break the email format. For instance, the
  263. * attached file hello_drupal.docx will produce the following Content-Type:
  264. * @code
  265. * Content-Type:
  266. * application/vnd.openxmlformats-officedocument.wordprocessingml.document;
  267. * name="hello_drupal.docx"
  268. * @endcode
  269. */
  270. protected static function wrapMailLine(&$line, $key, $values) {
  271. $line_is_mime_header = FALSE;
  272. $mime_headers = [
  273. 'Content-Type',
  274. 'Content-Transfer-Encoding',
  275. 'Content-Disposition',
  276. 'Content-Description',
  277. ];
  278. // Do not break MIME headers which could be longer than 77 characters.
  279. foreach ($mime_headers as $header) {
  280. if (strpos($line, $header . ': ') === 0) {
  281. $line_is_mime_header = TRUE;
  282. break;
  283. }
  284. }
  285. if (!$line_is_mime_header) {
  286. // Use soft-breaks only for purely quoted or unindented text.
  287. $line = wordwrap($line, 77 - $values['length'], $values['soft'] ? " \n" : "\n");
  288. }
  289. // Break really long words at the maximum width allowed.
  290. $line = wordwrap($line, 996 - $values['length'], $values['soft'] ? " \n" : "\n", TRUE);
  291. }
  292. /**
  293. * Keeps track of URLs and replaces them with placeholder tokens.
  294. *
  295. * Callback for preg_replace_callback() within
  296. * \Drupal\Core\Mail\MailFormatHelper::htmlToText().
  297. */
  298. protected static function htmlToMailUrls($match = NULL, $reset = FALSE) {
  299. // @todo Use request context instead.
  300. global $base_url, $base_path;
  301. if ($reset) {
  302. // Reset internal URL list.
  303. static::$urls = [];
  304. }
  305. else {
  306. if (empty(static::$regexp)) {
  307. static::$regexp = '@^' . preg_quote($base_path, '@') . '@';
  308. }
  309. if ($match) {
  310. list(, , $url, $label) = $match;
  311. // Ensure all URLs are absolute.
  312. static::$urls[] = strpos($url, '://') ? $url : preg_replace(static::$regexp, $base_url . '/', $url);
  313. return $label . ' [' . count(static::$urls) . ']';
  314. }
  315. }
  316. return static::$urls;
  317. }
  318. /**
  319. * Replaces non-quotation markers from a piece of indentation with spaces.
  320. *
  321. * Callback for array_map() within
  322. * \Drupal\Core\Mail\MailFormatHelper::htmlToText().
  323. */
  324. protected static function htmlToTextClean($indent) {
  325. return preg_replace('/[^>]/', ' ', $indent);
  326. }
  327. /**
  328. * Pads the last line with the given character.
  329. *
  330. * @param string $text
  331. * The text to pad.
  332. * @param string $pad
  333. * The character to pad the end of the string with.
  334. * @param string $prefix
  335. * (optional) Prefix to add to the string.
  336. *
  337. * @return string
  338. * The padded string.
  339. *
  340. * @see \Drupal\Core\Mail\MailFormatHelper::htmlToText()
  341. */
  342. protected static function htmlToTextPad($text, $pad, $prefix = '') {
  343. // Remove last line break.
  344. $text = substr($text, 0, -1);
  345. // Calculate needed padding space and add it.
  346. if (($p = strrpos($text, "\n")) === FALSE) {
  347. $p = -1;
  348. }
  349. $n = max(0, 79 - (strlen($text) - $p) - strlen($prefix));
  350. // Add prefix and padding, and restore linebreak.
  351. return $text . $prefix . str_repeat($pad, $n) . "\n";
  352. }
  353. }