FormattableMarkup.php 11 KB

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