Chris@17: []:;@\,."'; Chris@17: Chris@17: /** Chris@17: * Return a RFC-2822 compliant "display-name" component. Chris@17: * Chris@17: * The "display-name" component is used in mail header "Originator" fields Chris@17: * (From, Sender, Reply-to) to give a human-friendly description of the Chris@17: * address, i.e. From: My Display Name . RFC-822 and Chris@17: * RFC-2822 define its syntax and rules. This method gets as input a string Chris@17: * to be used as "display-name" and formats it to be RFC compliant. Chris@17: * Chris@17: * @param string $string Chris@17: * A string to be used as "display-name". Chris@17: * Chris@17: * @return string Chris@17: * A RFC compliant version of the string, ready to be used as Chris@17: * "display-name" in mail originator header fields. Chris@17: */ Chris@17: public static function formatDisplayName($string) { Chris@17: // Make sure we don't process html-encoded characters. They may create Chris@17: // unneeded trouble if left encoded, besides they will be correctly Chris@17: // processed if decoded. Chris@17: $string = Html::decodeEntities($string); Chris@17: Chris@17: // If string contains non-ASCII characters it must be (short) encoded Chris@17: // according to RFC-2047. The output of a "B" (Base64) encoded-word is Chris@17: // always safe to be used as display-name. Chris@17: $safe_display_name = Unicode::mimeHeaderEncode($string, TRUE); Chris@17: Chris@17: // Encoded-words are always safe to be used as display-name because don't Chris@17: // contain any RFC 2822 "specials" characters. However Chris@17: // Unicode::mimeHeaderEncode() encodes a string only if it contains any Chris@17: // non-ASCII characters, and leaves its value untouched (un-encoded) if Chris@17: // ASCII only. For this reason in order to produce a valid display-name we Chris@17: // still need to make sure there are no "specials" characters left. Chris@17: if (preg_match('/[' . preg_quote(Mail::RFC_2822_SPECIALS) . ']/', $safe_display_name)) { Chris@17: Chris@17: // If string is already quoted, it may or may not be escaped properly, so Chris@17: // don't trust it and reset. Chris@17: if (preg_match('/^"(.+)"$/', $safe_display_name, $matches)) { Chris@17: $safe_display_name = str_replace(['\\\\', '\\"'], ['\\', '"'], $matches[1]); Chris@17: } Chris@17: Chris@17: // Transform the string in a RFC-2822 "quoted-string" by wrapping it in Chris@17: // double-quotes. Also make sure '"' and '\' occurrences are escaped. Chris@17: $safe_display_name = '"' . str_replace(['\\', '"'], ['\\\\', '\\"'], $safe_display_name) . '"'; Chris@17: Chris@17: } Chris@17: Chris@17: return $safe_display_name; Chris@17: } Chris@17: Chris@17: }