1<?php
2
3namespace Drupal\Component\Render;
4
5use Drupal\Component\Utility\Html;
6use Drupal\Component\Utility\UrlHelper;
7
8/**
9 * Formats a string for HTML display by replacing variable placeholders.
10 *
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.
17 *
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.
24 *
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
30 *   risk. Examples:
31 *   @code
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]);
38 *   @endcode
39 *   Only the "href" attribute is supported via the special ":variable"
40 *   placeholder, to allow simple links to be inserted:
41 *   @code
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
47 *     // protocols):
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]);
51 *   @endcode
52 * To build non-minimal HTML, use an HTML template language such as Twig,
53 * rather than this class.
54 *
55 * @ingroup sanitization
56 *
57 * @see \Drupal\Core\StringTranslation\TranslatableMarkup
58 * @see \Drupal\Core\StringTranslation\PluralTranslatableMarkup
59 * @see \Drupal\Component\Render\FormattableMarkup::placeholderFormat()
60 */
61class FormattableMarkup implements MarkupInterface, \Countable {
62
63  /**
64   * The string containing placeholders.
65   *
66   * @var string
67   */
68  protected $string;
69
70  /**
71   * The arguments to replace placeholders with.
72   *
73   * @var array
74   */
75  protected $arguments = [];
76
77  /**
78   * Constructs a new class instance.
79   *
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.
87   *
88   * @see \Drupal\Component\Render\FormattableMarkup::placeholderFormat()
89   */
90  public function __construct($string, array $arguments) {
91    $this->string = (string) $string;
92    $this->arguments = $arguments;
93  }
94
95  /**
96   * {@inheritdoc}
97   */
98  public function __toString() {
99    return static::placeholderFormat($this->string, $this->arguments);
100  }
101
102  /**
103   * Returns the string length.
104   *
105   * @return int
106   *   The length of the string.
107   */
108  public function count() {
109    return mb_strlen($this->string);
110  }
111
112  /**
113   * Returns a representation of the object for use in JSON serialization.
114   *
115   * @return string
116   *   The safe string content.
117   */
118  public function jsonSerialize() {
119    return $this->__toString();
120  }
121
122  /**
123   * Replaces placeholders in a string with values.
124   *
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.
129   * @param array $args
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().
145   *       @code
146   *         $this->placeholderFormat('This will force HTML-escaping of the replacement value: @text', ['@text' => (string) $safe_string_interface_object));
147   *       @endcode
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>
152   *     tags.
153   *     A call like:
154   *     @code
155   *       $string = "%output_text";
156   *       $arguments = ['%output_text' => 'text output here.'];
157   *       $this->placeholderFormat($string, $arguments);
158   *     @endcode
159   *     makes the following HTML code:
160   *     @code
161   *       <em class="placeholder">text output here.</em>
162   *     @endcode
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
169   *     wrapped in quotes:
170   *     @code
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]);
175   *     @endcode
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.
182   *
183   * @return string
184   *   A formatted HTML string with the placeholders replaced.
185   *
186   * @ingroup sanitization
187   *
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()
193   */
194  protected static function placeholderFormat($string, array $args) {
195    // Transform arguments before inserting them.
196    foreach ($args as $key => $value) {
197      switch ($key[0]) {
198        case '@':
199          // Escape if the value is not an object from a class that implements
200          // \Drupal\Component\Render\MarkupInterface, for example strings will
201          // be escaped.
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);
207          break;
208
209        case ':':
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);
222          break;
223
224        case '%':
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
229          // wrapping markup.
230          $args[$key] = '<em class="placeholder">' . static::placeholderEscape($value) . '</em>';
231          break;
232
233        default:
234          // Deprecate support for random variables that won't be replaced.
235          if (ctype_alpha($key[0]) && strpos($string, $key) === FALSE) {
236            @trigger_error(sprintf('Support for keys without a placeholder prefix is deprecated in Drupal 9.1.0 and will be removed in Drupal 10.0.0. Invalid placeholder (%s) with string: "%s"', $key, $string), E_USER_DEPRECATED);
237          }
238          else {
239            trigger_error(sprintf('Invalid placeholder (%s) with string: "%s"', $key, $string), E_USER_WARNING);
240          }
241          // No replacement possible therefore we can discard the argument.
242          unset($args[$key]);
243          break;
244      }
245    }
246
247    return strtr($string, $args);
248  }
249
250  /**
251   * Escapes a placeholder replacement value if needed.
252   *
253   * @param string|\Drupal\Component\Render\MarkupInterface $value
254   *   A placeholder replacement value.
255   *
256   * @return string
257   *   The properly escaped replacement value.
258   */
259  protected static function placeholderEscape($value) {
260    return $value instanceof MarkupInterface ? (string) $value : Html::escape($value);
261  }
262
263}
264