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