FormattableMarkup.php 11 KB

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