Further Drupal 8.6.4 changes. Some core files were not committed before a commit...
[yaffs-website] / web / core / lib / Drupal / Component / Utility / Mail.php
1 <?php
2
3 namespace Drupal\Component\Utility;
4
5 /**
6  * Provides helpers to ensure emails are compliant with RFCs.
7  *
8  * @ingroup utility
9  */
10 class Mail {
11
12   /**
13    * RFC-2822 "specials" characters.
14    */
15   const RFC_2822_SPECIALS = '()<>[]:;@\,."';
16
17   /**
18    * Return a RFC-2822 compliant "display-name" component.
19    *
20    * The "display-name" component is used in mail header "Originator" fields
21    * (From, Sender, Reply-to) to give a human-friendly description of the
22    * address, i.e. From: My Display Name <xyz@example.org>. RFC-822 and
23    * RFC-2822 define its syntax and rules. This method gets as input a string
24    * to be used as "display-name" and formats it to be RFC compliant.
25    *
26    * @param string $string
27    *   A string to be used as "display-name".
28    *
29    * @return string
30    *   A RFC compliant version of the string, ready to be used as
31    *   "display-name" in mail originator header fields.
32    */
33   public static function formatDisplayName($string) {
34     // Make sure we don't process html-encoded characters. They may create
35     // unneeded trouble if left encoded, besides they will be correctly
36     // processed if decoded.
37     $string = Html::decodeEntities($string);
38
39     // If string contains non-ASCII characters it must be (short) encoded
40     // according to RFC-2047. The output of a "B" (Base64) encoded-word is
41     // always safe to be used as display-name.
42     $safe_display_name = Unicode::mimeHeaderEncode($string, TRUE);
43
44     // Encoded-words are always safe to be used as display-name because don't
45     // contain any RFC 2822 "specials" characters. However
46     // Unicode::mimeHeaderEncode() encodes a string only if it contains any
47     // non-ASCII characters, and leaves its value untouched (un-encoded) if
48     // ASCII only. For this reason in order to produce a valid display-name we
49     // still need to make sure there are no "specials" characters left.
50     if (preg_match('/[' . preg_quote(Mail::RFC_2822_SPECIALS) . ']/', $safe_display_name)) {
51
52       // If string is already quoted, it may or may not be escaped properly, so
53       // don't trust it and reset.
54       if (preg_match('/^"(.+)"$/', $safe_display_name, $matches)) {
55         $safe_display_name = str_replace(['\\\\', '\\"'], ['\\', '"'], $matches[1]);
56       }
57
58       // Transform the string in a RFC-2822 "quoted-string" by wrapping it in
59       // double-quotes. Also make sure '"' and '\' occurrences are escaped.
60       $safe_display_name = '"' . str_replace(['\\', '"'], ['\\\\', '\\"'], $safe_display_name) . '"';
61
62     }
63
64     return $safe_display_name;
65   }
66
67 }