3 namespace Drupal\Core\Mail;
5 use Drupal\Component\Utility\Html;
6 use Drupal\Component\Utility\Xss;
7 use Drupal\Core\Site\Settings;
10 * Defines a class containing utility methods for formatting mail messages.
12 class MailFormatHelper {
15 * Internal array of urls replaced with tokens.
19 protected static $urls = [];
22 * Quoted regex expression based on base path.
26 protected static $regexp;
29 * Array of tags supported.
33 protected static $supportedTags = [];
36 * Performs format=flowed soft wrapping for mail (RFC 3676).
38 * We use delsp=yes wrapping, but only break non-spaced languages when
39 * absolutely necessary to avoid compatibility issues.
41 * We deliberately use LF rather than CRLF, see MailManagerInterface::mail().
44 * The plain text to process.
45 * @param string $indent
46 * (optional) A string to indent the text with. Only '>' characters are
47 * repeated on subsequent wrapped lines. Others are replaced by spaces.
50 * The content of the email as a string with formatting applied.
52 public static function wrapMail($text, $indent = '') {
53 // Convert CRLF into LF.
54 $text = str_replace("\r", '', $text);
55 // See if soft-wrapping is allowed.
56 $clean_indent = static::htmlToTextClean($indent);
57 $soft = strpos($clean_indent, ' ') === FALSE;
58 // Check if the string has line breaks.
59 if (strpos($text, "\n") !== FALSE) {
60 // Remove trailing spaces to make existing breaks hard, but leave
61 // signature marker untouched (RFC 3676, Section 4.3).
62 $text = preg_replace('/(?(?<!^--) +\n| +\n)/m', "\n", $text);
63 // Wrap each line at the needed width.
64 $lines = explode("\n", $text);
65 array_walk($lines, '\Drupal\Core\Mail\MailFormatHelper::wrapMailLine', ['soft' => $soft, 'length' => strlen($indent)]);
66 $text = implode("\n", $lines);
70 static::wrapMailLine($text, 0, ['soft' => $soft, 'length' => strlen($indent)]);
72 // Empty lines with nothing but spaces.
73 $text = preg_replace('/^ +\n/m', "\n", $text);
74 // Space-stuff special lines.
75 $text = preg_replace('/^(>| |From)/m', ' $1', $text);
76 // Apply indentation. We only include non-'>' indentation on the first line.
77 $text = $indent . substr(preg_replace('/^/m', $clean_indent, $text), strlen($indent));
83 * Transforms an HTML string into plain text, preserving its structure.
85 * The output will be suitable for use as 'format=flowed; delsp=yes' text
86 * (RFC 3676) and can be passed directly to MailManagerInterface::mail() for sending.
88 * We deliberately use LF rather than CRLF, see MailManagerInterface::mail().
90 * This function provides suitable alternatives for the following tags:
91 * <a> <em> <i> <strong> <b> <br> <p> <blockquote> <ul> <ol> <li> <dl> <dt>
92 * <dd> <h1> <h2> <h3> <h4> <h5> <h6> <hr>
94 * @param string $string
95 * The string to be transformed.
96 * @param array $allowed_tags
97 * (optional) If supplied, a list of tags that will be transformed. If
98 * omitted, all supported tags are transformed.
101 * The transformed string.
103 public static function htmlToText($string, $allowed_tags = NULL) {
104 // Cache list of supported tags.
105 if (empty(static::$supportedTags)) {
106 static::$supportedTags = ['a', 'em', 'i', 'strong', 'b', 'br', 'p',
107 'blockquote', 'ul', 'ol', 'li', 'dl', 'dt', 'dd', 'h1', 'h2', 'h3',
108 'h4', 'h5', 'h6', 'hr',
112 // Make sure only supported tags are kept.
113 $allowed_tags = isset($allowed_tags) ? array_intersect(static::$supportedTags, $allowed_tags) : static::$supportedTags;
115 // Make sure tags, entities and attributes are well-formed and properly
117 $string = Html::normalize(Xss::filter($string, $allowed_tags));
119 // Apply inline styles.
120 $string = preg_replace('!</?(em|i)((?> +)[^>]*)?>!i', '/', $string);
121 $string = preg_replace('!</?(strong|b)((?> +)[^>]*)?>!i', '*', $string);
123 // Replace inline <a> tags with the text of link and a footnote.
124 // 'See <a href="https://www.drupal.org">the Drupal site</a>' becomes
125 // 'See the Drupal site [1]' with the URL included as a footnote.
126 static::htmlToMailUrls(NULL, TRUE);
127 $pattern = '@(<a[^>]+?href="([^"]*)"[^>]*?>(.+?)</a>)@i';
128 $string = preg_replace_callback($pattern, 'static::htmlToMailUrls', $string);
129 $urls = static::htmlToMailUrls();
133 for ($i = 0, $max = count($urls); $i < $max; $i++) {
134 $footnotes .= '[' . ($i + 1) . '] ' . $urls[$i] . "\n";
138 // Split tags from text.
139 $split = preg_split('/<([^>]+?)>/', $string, -1, PREG_SPLIT_DELIM_CAPTURE);
140 // Note: PHP ensures the array consists of alternating delimiters and
141 // literals and begins and ends with a literal (inserting $null as
143 // Odd/even counter (tag or no tag).
145 // Case conversion function.
148 // All current indentation string chunks.
150 // Array of counters for opened lists.
152 foreach ($split as $value) {
153 // Holds a string ready to be formatted and output.
156 // Process HTML tags (but don't output any literally).
158 list($tagname) = explode(' ', strtolower($value), 2);
162 array_unshift($lists, '*');
166 array_unshift($lists, 1);
172 // Ensure blank new-line.
176 // Quotation/list markers, non-fancy headers.
178 // Format=flowed indentation cannot be mixed with lists.
179 $indent[] = count($lists) ? ' "' : '>';
183 $indent[] = isset($lists[0]) && is_numeric($lists[0]) ? ' ' . $lists[0]++ . ') ' : ' * ';
200 // Append closing quote for inline quotes (immediately).
201 $output = rtrim($output, "> \n") . "\"\n";
202 // Ensure blank new-line.
205 // Intentional fall-through to the processing for '/li' and '/dd'.
214 // Intentional fall-through to the processing for '/h5' and '/h6'.
217 // Ensure blank new-line.
223 $indent[] = '======== ';
224 $casing = 'mb_strtoupper';
228 $indent[] = '-------- ';
229 $casing = 'mb_strtoupper';
235 // Pad the line with dashes.
236 $output = static::htmlToTextPad($output, ($tagname == '/h1') ? '=' : '-', ' ');
238 // Ensure blank new-line.
242 // Horizontal rulers.
244 // Insert immediately.
245 $output .= static::wrapMail('', implode('', $indent)) . "\n";
246 $output = static::htmlToTextPad($output, '-');
249 // Paragraphs and definition lists.
252 // Ensure blank new-line.
257 // Process blocks of text.
259 // Convert inline HTML text to plain text; not removing line-breaks or
260 // white-space, since that breaks newlines when sanitizing plain-text.
261 $value = trim(Html::decodeEntities($value));
262 if (mb_strlen($value)) {
267 // See if there is something waiting to be output.
269 // Apply any necessary case conversion.
270 if (isset($casing)) {
271 $chunk = call_user_func($casing, $chunk);
273 $line_endings = Settings::get('mail_line_endings', PHP_EOL);
274 // Format it and apply the current indentation.
275 $output .= static::wrapMail($chunk, implode('', $indent)) . $line_endings;
276 // Remove non-quotation markers from indentation.
277 $indent = array_map('\Drupal\Core\Mail\MailFormatHelper::htmlToTextClean', $indent);
283 return $output . $footnotes;
287 * Wraps words on a single line.
289 * Callback for array_walk() within
290 * \Drupal\Core\Mail\MailFormatHelper::wrapMail().
292 * Note that we are skipping MIME content header lines, because attached
293 * files, especially applications, could have long MIME types or long
294 * filenames which result in line length longer than the 77 characters limit
295 * and wrapping that line will break the email format. For instance, the
296 * attached file hello_drupal.docx will produce the following Content-Type:
299 * application/vnd.openxmlformats-officedocument.wordprocessingml.document;
300 * name="hello_drupal.docx"
303 protected static function wrapMailLine(&$line, $key, $values) {
304 $line_is_mime_header = FALSE;
307 'Content-Transfer-Encoding',
308 'Content-Disposition',
309 'Content-Description',
312 // Do not break MIME headers which could be longer than 77 characters.
313 foreach ($mime_headers as $header) {
314 if (strpos($line, $header . ': ') === 0) {
315 $line_is_mime_header = TRUE;
319 if (!$line_is_mime_header) {
320 // Use soft-breaks only for purely quoted or unindented text.
321 $line = wordwrap($line, 77 - $values['length'], $values['soft'] ? " \n" : "\n");
323 // Break really long words at the maximum width allowed.
324 $line = wordwrap($line, 996 - $values['length'], $values['soft'] ? " \n" : "\n", TRUE);
328 * Keeps track of URLs and replaces them with placeholder tokens.
330 * Callback for preg_replace_callback() within
331 * \Drupal\Core\Mail\MailFormatHelper::htmlToText().
333 protected static function htmlToMailUrls($match = NULL, $reset = FALSE) {
334 // @todo Use request context instead.
335 global $base_url, $base_path;
338 // Reset internal URL list.
342 if (empty(static::$regexp)) {
343 static::$regexp = '@^' . preg_quote($base_path, '@') . '@';
346 list(, , $url, $label) = $match;
347 // Ensure all URLs are absolute.
348 static::$urls[] = strpos($url, '://') ? $url : preg_replace(static::$regexp, $base_url . '/', $url);
349 return $label . ' [' . count(static::$urls) . ']';
352 return static::$urls;
356 * Replaces non-quotation markers from a piece of indentation with spaces.
358 * Callback for array_map() within
359 * \Drupal\Core\Mail\MailFormatHelper::htmlToText().
361 protected static function htmlToTextClean($indent) {
362 return preg_replace('/[^>]/', ' ', $indent);
366 * Pads the last line with the given character.
368 * @param string $text
371 * The character to pad the end of the string with.
372 * @param string $prefix
373 * (optional) Prefix to add to the string.
378 * @see \Drupal\Core\Mail\MailFormatHelper::htmlToText()
380 protected static function htmlToTextPad($text, $pad, $prefix = '') {
381 // Remove last line break.
382 $text = substr($text, 0, -1);
383 // Calculate needed padding space and add it.
384 if (($p = strrpos($text, "\n")) === FALSE) {
387 $n = max(0, 79 - (strlen($text) - $p) - strlen($prefix));
388 // Add prefix and padding, and restore linebreak.
389 return $text . $prefix . str_repeat($pad, $n) . "\n";