annotate core/lib/Drupal/Component/Render/FormattableMarkup.php @ 19:fa3358dc1485 tip

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