3 namespace Drupal\Component\Render;
5 use Drupal\Component\Utility\Html;
6 use Drupal\Component\Utility\UrlHelper;
9 * Formats a string for HTML display by replacing variable placeholders.
11 * When cast to a string, this object replaces variable placeholders in the
12 * string with the arguments passed in during construction and escapes the
13 * values so they can be safely displayed as HTML. See the documentation of
14 * \Drupal\Component\Render\FormattableMarkup::placeholderFormat() for details
15 * on the supported placeholders and how to use them securely. Incorrect use of
16 * this class can result in security vulnerabilities.
18 * In most cases, you should use TranslatableMarkup or PluralTranslatableMarkup
19 * rather than this object, since they will translate the text (on
20 * non-English-only sites) in addition to formatting it. Variables concatenated
21 * without the insertion of language-specific words or punctuation are some
22 * examples where translation is not applicable and using this class directly
23 * directly is appropriate.
25 * This class is designed for formatting messages that are mostly text, not as
26 * an HTML template language. As such:
27 * - The passed in string should contain no (or minimal) HTML.
28 * - Variable placeholders should not be used within the "<" and ">" of an
29 * HTML tag, such as in HTML attribute values. This would be a security
32 * // Insecure (placeholder within "<" and ">"):
33 * $this->placeholderFormat('<@variable>text</@variable>', ['@variable' => $variable]);
34 * // Insecure (placeholder within "<" and ">"):
35 * $this->placeholderFormat('<a @variable>link text</a>', ['@variable' => $variable]);
36 * // Insecure (placeholder within "<" and ">"):
37 * $this->placeholderFormat('<a title="@variable">link text</a>', ['@variable' => $variable]);
39 * Only the "href" attribute is supported via the special ":variable"
40 * placeholder, to allow simple links to be inserted:
42 * // Secure (usage of ":variable" placeholder for href attribute):
43 * $this->placeholderFormat('<a href=":variable">link text</a>', [':variable' , $variable]);
44 * // Secure (usage of ":variable" placeholder for href attribute):
45 * $this->placeholderFormat('<a href=":variable" title="static text">link text</a>', [':variable' => $variable]);
46 * // Insecure (the "@variable" placeholder does not filter dangerous
48 * $this->placeholderFormat('<a href="@variable">link text</a>', ['@variable' => $variable]);
49 * // Insecure ("@variable" placeholder within "<" and ">"):
50 * $this->placeholderFormat('<a href=":url" title="@variable">link text</a>', [':url' => $url, '@variable' => $variable]);
52 * To build non-minimal HTML, use an HTML template language such as Twig,
53 * rather than this class.
55 * @ingroup sanitization
57 * @see \Drupal\Core\StringTranslation\TranslatableMarkup
58 * @see \Drupal\Core\StringTranslation\PluralTranslatableMarkup
59 * @see \Drupal\Component\Render\FormattableMarkup::placeholderFormat()
61 class FormattableMarkup implements MarkupInterface, \Countable {
64 * The string containing placeholders.
71 * The arguments to replace placeholders with.
75 protected $arguments = [];
78 * Constructs a new class instance.
80 * @param string $string
81 * A string containing placeholders. The string itself will not be escaped,
82 * any unsafe content must be in $args and inserted via placeholders.
83 * @param array $arguments
84 * An array with placeholder replacements, keyed by placeholder. See
85 * \Drupal\Component\Render\FormattableMarkup::placeholderFormat() for
86 * additional information about placeholders.
88 * @see \Drupal\Component\Render\FormattableMarkup::placeholderFormat()
90 public function __construct($string, array $arguments) {
91 $this->string = (string) $string;
92 $this->arguments = $arguments;
98 public function __toString() {
99 return static::placeholderFormat($this->string, $this->arguments);
103 * Returns the string length.
106 * The length of the string.
108 public function count() {
109 return mb_strlen($this->string);
113 * Returns a representation of the object for use in JSON serialization.
116 * The safe string content.
118 public function jsonSerialize() {
119 return $this->__toString();
123 * Replaces placeholders in a string with values.
125 * @param string $string
126 * A string containing placeholders. The string itself is expected to be
127 * safe and correct HTML. Any unsafe content must be in $args and
128 * inserted via placeholders.
130 * An associative array of replacements. Each array key should be the same
131 * as a placeholder in $string. The corresponding value should be a string
132 * or an object that implements
133 * \Drupal\Component\Render\MarkupInterface. The value replaces the
134 * placeholder in $string. Sanitization and formatting will be done before
135 * replacement. The type of sanitization and formatting depends on the first
136 * character of the key:
137 * - @variable: When the placeholder replacement value is:
138 * - A string, the replaced value in the returned string will be sanitized
139 * using \Drupal\Component\Utility\Html::escape().
140 * - A MarkupInterface object, the replaced value in the returned string
141 * will not be sanitized.
142 * - A MarkupInterface object cast to a string, the replaced value in the
143 * returned string be forcibly sanitized using
144 * \Drupal\Component\Utility\Html::escape().
146 * $this->placeholderFormat('This will force HTML-escaping of the replacement value: @text', ['@text' => (string) $safe_string_interface_object));
148 * Use this placeholder as the default choice for anything displayed on
149 * the site, but not within HTML attributes, JavaScript, or CSS. Doing so
150 * is a security risk.
151 * - %variable: Use when the replacement value is to be wrapped in <em>
155 * $string = "%output_text";
156 * $arguments = ['%output_text' => 'text output here.'];
157 * $this->placeholderFormat($string, $arguments);
159 * makes the following HTML code:
161 * <em class="placeholder">text output here.</em>
163 * As with @variable, do not use this within HTML attributes, JavaScript,
164 * or CSS. Doing so is a security risk.
165 * - :variable: Return value is escaped with
166 * \Drupal\Component\Utility\Html::escape() and filtered for dangerous
167 * protocols using UrlHelper::stripDangerousProtocols(). Use this when
168 * using the "href" attribute, ensuring the attribute value is always
171 * // Secure (with quotes):
172 * $this->placeholderFormat('<a href=":url">@variable</a>', [':url' => $url, '@variable' => $variable]);
173 * // Insecure (without quotes):
174 * $this->placeholderFormat('<a href=:url>@variable</a>', [':url' => $url, '@variable' => $variable]);
176 * When ":variable" comes from arbitrary user input, the result is secure,
177 * but not guaranteed to be a valid URL (which means the resulting output
178 * could fail HTML validation). To guarantee a valid URL, use
179 * Url::fromUri($user_input)->toString() (which either throws an exception
180 * or returns a well-formed URL) before passing the result into a
181 * ":variable" placeholder.
184 * A formatted HTML string with the placeholders replaced.
186 * @ingroup sanitization
188 * @see \Drupal\Core\StringTranslation\TranslatableMarkup
189 * @see \Drupal\Core\StringTranslation\PluralTranslatableMarkup
190 * @see \Drupal\Component\Utility\Html::escape()
191 * @see \Drupal\Component\Utility\UrlHelper::stripDangerousProtocols()
192 * @see \Drupal\Core\Url::fromUri()
194 protected static function placeholderFormat($string, array $args) {
195 // Transform arguments before inserting them.
196 foreach ($args as $key => $value) {
199 // Escape if the value is not an object from a class that implements
200 // \Drupal\Component\Render\MarkupInterface, for example strings will
202 // Strings that are safe within HTML fragments, but not within other
203 // contexts, may still be an instance of
204 // \Drupal\Component\Render\MarkupInterface, so this placeholder type
205 // must not be used within HTML attributes, JavaScript, or CSS.
206 $args[$key] = static::placeholderEscape($value);
210 // Strip URL protocols that can be XSS vectors.
211 $value = UrlHelper::stripDangerousProtocols($value);
212 // Escape unconditionally, without checking whether the value is an
213 // instance of \Drupal\Component\Render\MarkupInterface. This forces
214 // characters that are unsafe for use in an "href" HTML attribute to
215 // be encoded. If a caller wants to pass a value that is extracted
216 // from HTML and therefore is already HTML encoded, it must invoke
217 // \Drupal\Component\Render\OutputStrategyInterface::renderFromHtml()
218 // on it prior to passing it in as a placeholder value of this type.
219 // @todo Add some advice and stronger warnings.
220 // https://www.drupal.org/node/2569041.
221 $args[$key] = Html::escape($value);
225 // Similarly to @, escape non-safe values. Also, add wrapping markup
226 // in order to render as a placeholder. Not for use within attributes,
227 // per the warning above about
228 // \Drupal\Component\Render\MarkupInterface and also due to the
230 $args[$key] = '<em class="placeholder">' . static::placeholderEscape($value) . '</em>';
234 // We do not trigger an error for placeholder that start with an
235 // alphabetic character.
236 // @todo https://www.drupal.org/node/2807743 Change to an exception
237 // and always throw regardless of the first character.
238 if (!ctype_alpha($key[0])) {
239 // We trigger an error as we may want to introduce new placeholders
240 // in the future without breaking backward compatibility.
241 trigger_error('Invalid placeholder (' . $key . ') in string: ' . $string, E_USER_ERROR);
243 elseif (strpos($string, $key) !== FALSE) {
244 trigger_error('Invalid placeholder (' . $key . ') in string: ' . $string, E_USER_DEPRECATED);
246 // No replacement possible therefore we can discard the argument.
252 return strtr($string, $args);
256 * Escapes a placeholder replacement value if needed.
258 * @param string|\Drupal\Component\Render\MarkupInterface $value
259 * A placeholder replacement value.
262 * The properly escaped replacement value.
264 protected static function placeholderEscape($value) {
265 return $value instanceof MarkupInterface ? (string) $value : Html::escape($value);