annotate core/lib/Drupal/Component/Render/FormattableMarkup.php @ 14:1fec387a4317

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