Updated Drupal to 8.6. This goes with the following updates because it's possible...
[yaffs-website] / web / core / lib / Drupal / Core / Mail / MailFormatHelper.php
1 <?php
2
3 namespace Drupal\Core\Mail;
4
5 use Drupal\Component\Utility\Html;
6 use Drupal\Component\Utility\Xss;
7 use Drupal\Core\Site\Settings;
8
9 /**
10  * Defines a class containing utility methods for formatting mail messages.
11  */
12 class MailFormatHelper {
13
14   /**
15    * Internal array of urls replaced with tokens.
16    *
17    * @var array
18    */
19   protected static $urls = [];
20
21   /**
22    * Quoted regex expression based on base path.
23    *
24    * @var string
25    */
26   protected static $regexp;
27
28   /**
29    * Array of tags supported.
30    *
31    * @var array
32    */
33   protected static $supportedTags = [];
34
35   /**
36    * Performs format=flowed soft wrapping for mail (RFC 3676).
37    *
38    * We use delsp=yes wrapping, but only break non-spaced languages when
39    * absolutely necessary to avoid compatibility issues.
40    *
41    * We deliberately use LF rather than CRLF, see MailManagerInterface::mail().
42    *
43    * @param string $text
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.
48    *
49    * @return string
50    *   The content of the email as a string with formatting applied.
51    */
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);
67     }
68     else {
69       // Wrap this line.
70       static::wrapMailLine($text, 0, ['soft' => $soft, 'length' => strlen($indent)]);
71     }
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));
78
79     return $text;
80   }
81
82   /**
83    * Transforms an HTML string into plain text, preserving its structure.
84    *
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.
87    *
88    * We deliberately use LF rather than CRLF, see MailManagerInterface::mail().
89    *
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>
93    *
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.
99    *
100    * @return string
101    *   The transformed string.
102    */
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',
109       ];
110     }
111
112     // Make sure only supported tags are kept.
113     $allowed_tags = isset($allowed_tags) ? array_intersect(static::$supportedTags, $allowed_tags) : static::$supportedTags;
114
115     // Make sure tags, entities and attributes are well-formed and properly
116     // nested.
117     $string = Html::normalize(Xss::filter($string, $allowed_tags));
118
119     // Apply inline styles.
120     $string = preg_replace('!</?(em|i)((?> +)[^>]*)?>!i', '/', $string);
121     $string = preg_replace('!</?(strong|b)((?> +)[^>]*)?>!i', '*', $string);
122
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();
130     $footnotes = '';
131     if (count($urls)) {
132       $footnotes .= "\n";
133       for ($i = 0, $max = count($urls); $i < $max; $i++) {
134         $footnotes .= '[' . ($i + 1) . '] ' . $urls[$i] . "\n";
135       }
136     }
137
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
142     // required).
143     // Odd/even counter (tag or no tag).
144     $tag = FALSE;
145     // Case conversion function.
146     $casing = NULL;
147     $output = '';
148     // All current indentation string chunks.
149     $indent = [];
150     // Array of counters for opened lists.
151     $lists = [];
152     foreach ($split as $value) {
153       // Holds a string ready to be formatted and output.
154       $chunk = NULL;
155
156       // Process HTML tags (but don't output any literally).
157       if ($tag) {
158         list($tagname) = explode(' ', strtolower($value), 2);
159         switch ($tagname) {
160           // List counters.
161           case 'ul':
162             array_unshift($lists, '*');
163             break;
164
165           case 'ol':
166             array_unshift($lists, 1);
167             break;
168
169           case '/ul':
170           case '/ol':
171             array_shift($lists);
172             // Ensure blank new-line.
173             $chunk = '';
174             break;
175
176           // Quotation/list markers, non-fancy headers.
177           case 'blockquote':
178             // Format=flowed indentation cannot be mixed with lists.
179             $indent[] = count($lists) ? ' "' : '>';
180             break;
181
182           case 'li':
183             $indent[] = isset($lists[0]) && is_numeric($lists[0]) ? ' ' . $lists[0]++ . ') ' : ' * ';
184             break;
185
186           case 'dd':
187             $indent[] = '    ';
188             break;
189
190           case 'h3':
191             $indent[] = '.... ';
192             break;
193
194           case 'h4':
195             $indent[] = '.. ';
196             break;
197
198           case '/blockquote':
199             if (count($lists)) {
200               // Append closing quote for inline quotes (immediately).
201               $output = rtrim($output, "> \n") . "\"\n";
202               // Ensure blank new-line.
203               $chunk = '';
204             }
205             // Intentional fall-through to the processing for '/li' and '/dd'.
206           case '/li':
207           case '/dd':
208             array_pop($indent);
209             break;
210
211           case '/h3':
212           case '/h4':
213             array_pop($indent);
214             // Intentional fall-through to the processing for '/h5' and '/h6'.
215           case '/h5':
216           case '/h6':
217             // Ensure blank new-line.
218             $chunk = '';
219             break;
220
221           // Fancy headers.
222           case 'h1':
223             $indent[] = '======== ';
224             $casing = 'mb_strtoupper';
225             break;
226
227           case 'h2':
228             $indent[] = '-------- ';
229             $casing = 'mb_strtoupper';
230             break;
231
232           case '/h1':
233           case '/h2':
234             $casing = NULL;
235             // Pad the line with dashes.
236             $output = static::htmlToTextPad($output, ($tagname == '/h1') ? '=' : '-', ' ');
237             array_pop($indent);
238             // Ensure blank new-line.
239             $chunk = '';
240             break;
241
242           // Horizontal rulers.
243           case 'hr':
244             // Insert immediately.
245             $output .= static::wrapMail('', implode('', $indent)) . "\n";
246             $output = static::htmlToTextPad($output, '-');
247             break;
248
249           // Paragraphs and definition lists.
250           case '/p':
251           case '/dl':
252             // Ensure blank new-line.
253             $chunk = '';
254             break;
255         }
256       }
257       // Process blocks of text.
258       else {
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)) {
263           $chunk = $value;
264         }
265       }
266
267       // See if there is something waiting to be output.
268       if (isset($chunk)) {
269         // Apply any necessary case conversion.
270         if (isset($casing)) {
271           $chunk = call_user_func($casing, $chunk);
272         }
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);
278       }
279
280       $tag = !$tag;
281     }
282
283     return $output . $footnotes;
284   }
285
286   /**
287    * Wraps words on a single line.
288    *
289    * Callback for array_walk() within
290    * \Drupal\Core\Mail\MailFormatHelper::wrapMail().
291    *
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:
297    * @code
298    * Content-Type:
299    * application/vnd.openxmlformats-officedocument.wordprocessingml.document;
300    * name="hello_drupal.docx"
301    * @endcode
302    */
303   protected static function wrapMailLine(&$line, $key, $values) {
304     $line_is_mime_header = FALSE;
305     $mime_headers = [
306       'Content-Type',
307       'Content-Transfer-Encoding',
308       'Content-Disposition',
309       'Content-Description',
310     ];
311
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;
316         break;
317       }
318     }
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");
322     }
323     // Break really long words at the maximum width allowed.
324     $line = wordwrap($line, 996 - $values['length'], $values['soft'] ? " \n" : "\n", TRUE);
325   }
326
327   /**
328    * Keeps track of URLs and replaces them with placeholder tokens.
329    *
330    * Callback for preg_replace_callback() within
331    * \Drupal\Core\Mail\MailFormatHelper::htmlToText().
332    */
333   protected static function htmlToMailUrls($match = NULL, $reset = FALSE) {
334     // @todo Use request context instead.
335     global $base_url, $base_path;
336
337     if ($reset) {
338       // Reset internal URL list.
339       static::$urls = [];
340     }
341     else {
342       if (empty(static::$regexp)) {
343         static::$regexp = '@^' . preg_quote($base_path, '@') . '@';
344       }
345       if ($match) {
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) . ']';
350       }
351     }
352     return static::$urls;
353   }
354
355   /**
356    * Replaces non-quotation markers from a piece of indentation with spaces.
357    *
358    * Callback for array_map() within
359    * \Drupal\Core\Mail\MailFormatHelper::htmlToText().
360    */
361   protected static function htmlToTextClean($indent) {
362     return preg_replace('/[^>]/', ' ', $indent);
363   }
364
365   /**
366    * Pads the last line with the given character.
367    *
368    * @param string $text
369    *   The text to pad.
370    * @param string $pad
371    *   The character to pad the end of the string with.
372    * @param string $prefix
373    *   (optional) Prefix to add to the string.
374    *
375    * @return string
376    *   The padded string.
377    *
378    * @see \Drupal\Core\Mail\MailFormatHelper::htmlToText()
379    */
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) {
385       $p = -1;
386     }
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";
390   }
391
392 }