Debian Codegraph @

includes/parser/Sanitizer.php

raw symbols SCIP
1 <?php
2 /**
3 * HTML sanitizer for %MediaWiki.
4 *
5 * Copyright © 2002-2005 Brooke Vibber <[email protected]> et al
6 * https://www.mediawiki.org/
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
22 *
23 * @file
24 * @ingroup Parser
25 */
26
27 namespace MediaWiki\Parser;
28
29 use InvalidArgumentException;
30 use LogicException;
31 use MediaWiki\HookContainer\HookRunner;
32 use MediaWiki\MediaWikiServices;
33 use MediaWiki\Tidy\RemexCompatFormatter;
34 use StringUtils;
35 use UnexpectedValueException;
36 use Wikimedia\RemexHtml\HTMLData;
37 use Wikimedia\RemexHtml\Serializer\Serializer as RemexSerializer;
38 use Wikimedia\RemexHtml\Tokenizer\Tokenizer as RemexTokenizer;
39 use Wikimedia\RemexHtml\TreeBuilder\Dispatcher as RemexDispatcher;
40 use Wikimedia\RemexHtml\TreeBuilder\TreeBuilder as RemexTreeBuilder;
41
42 /**
43 * HTML sanitizer for MediaWiki
44 * @ingroup Parser
45 */
46 class Sanitizer {
47 /**
48 * Regular expression to match various types of character references in
49 * Sanitizer::normalizeCharReferences and Sanitizer::decodeCharReferences.
50 * Note that HTML5 allows some named entities to omit the trailing
51 * semicolon; wikitext entities *must* have a trailing semicolon.
52 */
53 private const CHAR_REFS_REGEX =
54 '/&([A-Za-z0-9\x80-\xff]+;)
55 |&\#([0-9]+);
56 |&\#[xX]([0-9A-Fa-f]+);
57 |&/x';
58
59 /**
60 * Acceptable tag name charset from HTML5 parsing spec
61 * https://www.w3.org/TR/html5/syntax.html#tag-open-state
62 */
63 private const ELEMENT_BITS_REGEX = '!^(/?)([A-Za-z][^\t\n\v />\0]*+)([^>]*?)(/?>)([^<]*)$!';
64
65 /**
66 * Pattern matching evil uris like javascript:
67 * WARNING: DO NOT use this in any place that actually requires denying
68 * certain URIs for security reasons. There are NUMEROUS[1] ways to bypass
69 * pattern-based deny lists; the only way to be secure from javascript:
70 * uri based xss vectors is to allow only things that you know are safe
71 * and deny everything else.
72 * [1]: http://ha.ckers.org/xss.html
73 */
74 private const EVIL_URI_PATTERN = '!(^|\s|\*/\s*)(javascript|vbscript)([^\w]|$)!i';
75 private const XMLNS_ATTRIBUTE_PATTERN = "/^xmlns:[:A-Z_a-z-.0-9]+$/";
76
77 /**
78 * Tells escapeUrlForHtml() to encode the ID using the wiki's primary encoding.
79 *
80 * @since 1.30
81 */
82 public const ID_PRIMARY = 0;
83
84 /**
85 * Tells escapeUrlForHtml() to encode the ID using the fallback encoding, or return false
86 * if no fallback is configured.
87 *
88 * @since 1.30
89 */
90 public const ID_FALLBACK = 1;
91
92 /**
93 * Character entity aliases accepted by MediaWiki in wikitext.
94 * These are not part of the HTML standard.
95 */
96 private const MW_ENTITY_ALIASES = [
97 'רלמ;' => 'rlm;',
98 'رلم;' => 'rlm;',
99 ];
100
101 /**
102 * Lazy-initialised attributes regex, see getAttribsRegex()
103 */
104 private static ?string $attribsRegex = null;
105
106 /**
107 * Regular expression to match HTML/XML attribute pairs within a tag.
108 * Based on https://www.w3.org/TR/html5/syntax.html#before-attribute-name-state
109 * Used in Sanitizer::decodeTagAttributes
110 */
111 private static function getAttribsRegex(): string {
112 if ( self::$attribsRegex === null ) {
113 $spaceChars = '\x09\x0a\x0c\x0d\x20';
114 $space = "[{$spaceChars}]";
115 $attrib = "[^{$spaceChars}\/>=]";
116 $attribFirst = "(?:{$attrib}|=)";
117 self::$attribsRegex =
118 "/({$attribFirst}{$attrib}*)
119 ($space*=$space*
120 (?:
121 # The attribute value: quoted or alone
122 \"([^\"]*)(?:\"|\$)
123 | '([^']*)(?:'|\$)
124 | (((?!$space|>).)*)
125 )
126 )?/sxu";
127 }
128 return self::$attribsRegex;
129 }
130
131 /**
132 * Lazy-initialised attribute name regex, see getAttribNameRegex()
133 */
134 private static ?string $attribNameRegex = null;
135
136 /**
137 * Used in Sanitizer::decodeTagAttributes to filter attributes.
138 */
139 private static function getAttribNameRegex(): string {
140 if ( self::$attribNameRegex === null ) {
141 $attribFirst = "[:_\p{L}\p{N}]";
142 $attrib = "[:_\.\-\p{L}\p{N}]";
143 self::$attribNameRegex = "/^({$attribFirst}{$attrib}*)$/sxu";
144 }
145 return self::$attribNameRegex;
146 }
147
148 /**
149 * Return the various lists of recognized tags
150 * @param string[] $extratags For any extra tags to include
151 * @param string[] $removetags For any tags (default or extra) to exclude
152 * @return array
153 * @internal
154 */
155 public static function getRecognizedTagData( array $extratags = [], array $removetags = [] ): array {
156 static $commonCase, $staticInitialised = false;
157 $isCommonCase = ( $extratags === [] && $removetags === [] );
158 if ( $staticInitialised && $isCommonCase && $commonCase ) {
159 return $commonCase;
160 }
161
162 static $htmlpairsStatic, $htmlsingle, $htmlsingleonly, $htmlnest, $tabletags,
163 $htmllist, $listtags, $htmlsingleallowed, $htmlelementsStatic;
164
165 if ( !$staticInitialised ) {
166 $htmlpairsStatic = [ # Tags that must be closed
167 'b', 'bdi', 'del', 'i', 'ins', 'u', 'font', 'big', 'small', 'sub', 'sup', 'h1',
168 'h2', 'h3', 'h4', 'h5', 'h6', 'cite', 'code', 'em', 's',
169 'strike', 'strong', 'tt', 'var', 'div', 'center',
170 'blockquote', 'ol', 'ul', 'dl', 'table', 'caption', 'pre',
171 'ruby', 'rb', 'rp', 'rt', 'rtc', 'p', 'span', 'abbr', 'dfn',
172 'kbd', 'samp', 'data', 'time', 'mark'
173 ];
174 # These tags can be self-closed. For tags not also on
175 # $htmlsingleonly, a self-closed tag will be emitted as
176 # an empty element (open-tag/close-tag pair).
177 $htmlsingle = [
178 'br', 'wbr', 'hr', 'li', 'dt', 'dd', 'meta', 'link'
179 ];
180
181 # Elements that cannot have close tags. This is (not coincidentally)
182 # also the list of tags for which the HTML 5 parsing algorithm
183 # requires you to "acknowledge the token's self-closing flag", i.e.
184 # a self-closing tag like <br/> is not an HTML 5 parse error only
185 # for this list.
186 $htmlsingleonly = [
187 'br', 'wbr', 'hr', 'meta', 'link'
188 ];
189
190 $htmlnest = [ # Tags that can be nested--??
191 'table', 'tr', 'td', 'th', 'div', 'blockquote', 'ol', 'ul',
192 'li', 'dl', 'dt', 'dd', 'font', 'big', 'small', 'sub', 'sup', 'span',
193 'var', 'kbd', 'samp', 'em', 'strong', 'q', 'ruby', 'bdo'
194 ];
195 $tabletags = [ # Can only appear inside table, we will close them
196 'td', 'th', 'tr',
197 ];
198 $htmllist = [ # Tags used by list
199 'ul', 'ol',
200 ];
201 $listtags = [ # Tags that can appear in a list
202 'li',
203 ];
204
205 $htmlsingleallowed = array_unique( array_merge( $htmlsingle, $tabletags ) );
206 $htmlelementsStatic = array_unique( array_merge( $htmlsingle, $htmlpairsStatic, $htmlnest ) );
207
208 # Convert them all to hashtables for faster lookup
209 $vars = [ 'htmlpairsStatic', 'htmlsingle', 'htmlsingleonly', 'htmlnest', 'tabletags',
210 'htmllist', 'listtags', 'htmlsingleallowed', 'htmlelementsStatic' ];
211 foreach ( $vars as $var ) {
212 $$var = array_fill_keys( $$var, true );
213 }
214 $staticInitialised = true;
215 }
216
217 # Populate $htmlpairs and $htmlelements with the $extratags and $removetags arrays
218 $extratags = array_fill_keys( $extratags, true );
219 $removetags = array_fill_keys( $removetags, true );
220 $htmlpairs = array_merge( $extratags, $htmlpairsStatic );
221 $htmlelements = array_diff_key( array_merge( $extratags, $htmlelementsStatic ), $removetags );
222
223 $result = [
224 'htmlpairs' => $htmlpairs,
225 'htmlsingle' => $htmlsingle,
226 'htmlsingleonly' => $htmlsingleonly,
227 'htmlnest' => $htmlnest,
228 'tabletags' => $tabletags,
229 'htmllist' => $htmllist,
230 'listtags' => $listtags,
231 'htmlsingleallowed' => $htmlsingleallowed,
232 'htmlelements' => $htmlelements,
233 ];
234 if ( $isCommonCase ) {
235 $commonCase = $result;
236 }
237 return $result;
238 }
239
240 /**
241 * Cleans up HTML, removes dangerous tags and attributes, and
242 * removes HTML comments; BEWARE there may be unmatched HTML
243 * tags in the result.
244 *
245 * @note Callers are recommended to use `::removeSomeTags()` instead
246 * of this method. `Sanitizer::removeSomeTags()` is safer and will
247 * always return well-formed HTML; however, it is significantly
248 * slower (especially for short strings where setup costs
249 * predominate). This method is for internal use by the legacy parser
250 * where we know the result will be cleaned up in a subsequent tidy pass.
251 *
252 * @param string $text Original string; see T268353 for why untainted.
253 * @param-taint $text none
254 * @param callable|null $processCallback Callback to do any variable or
255 * parameter replacements in HTML attribute values.
256 * This argument should be considered @internal.
257 * @param-taint $processCallback exec_shell
258 * @param array|bool $args Arguments for the processing callback
259 * @param-taint $args none
260 * @param array $extratags For any extra tags to include
261 * @param-taint $extratags tainted
262 * @param array $removetags For any tags (default or extra) to exclude
263 * @param-taint $removetags none
264 * @return string
265 * @return-taint escaped
266 * @internal
267 */
268 public static function internalRemoveHtmlTags( string $text, ?callable $processCallback = null,
269 $args = [], array $extratags = [], array $removetags = []
270 ): string {
271 $tagData = self::getRecognizedTagData( $extratags, $removetags );
272 $htmlsingle = $tagData['htmlsingle'];
273 $htmlsingleonly = $tagData['htmlsingleonly'];
274 $htmlelements = $tagData['htmlelements'];
275
276 # Remove HTML comments
277 $text = self::removeHTMLcomments( $text );
278 $bits = explode( '<', $text );
279 $text = str_replace( '>', '&gt;', array_shift( $bits ) );
280
281 # this might be possible using remex tidy itself
282 foreach ( $bits as $x ) {
283 if ( preg_match( self::ELEMENT_BITS_REGEX, $x, $regs ) ) {
284 [ /* $qbar */, $slash, $t, $params, $brace, $rest ] = $regs;
285
286 $badtag = false;
287 $t = strtolower( $t );
288 if ( isset( $htmlelements[$t] ) ) {
289 if ( is_callable( $processCallback ) ) {
290 call_user_func_array( $processCallback, [ &$params, $args ] );
291 }
292
293 if ( $brace == '/>' && !( isset( $htmlsingle[$t] ) || isset( $htmlsingleonly[$t] ) ) ) {
294 // Remove the self-closing slash, to be consistent
295 // with HTML5 semantics. T134423
296 $brace = '>';
297 }
298 if ( !self::validateTag( $params, $t ) ) {
299 $badtag = true;
300 }
301
302 $newparams = self::fixTagAttributes( $params, $t );
303 if ( !$badtag ) {
304 if ( $brace === '/>' && !isset( $htmlsingleonly[$t] ) ) {
305 # Interpret self-closing tags as empty tags even when
306 # HTML 5 would interpret them as start tags. Such input
307 # is commonly seen on Wikimedia wikis with this intention.
308 $brace = "></$t>";
309 }
310
311 $rest = str_replace( '>', '&gt;', $rest );
312 $text .= "<$slash$t$newparams$brace$rest";
313 continue;
314 }
315 }
316 }
317 $text .= '&lt;' . str_replace( '>', '&gt;', $x );
318 }
319 return $text;
320 }
321
322 /**
323 * Cleans up HTML, removes dangerous tags and attributes, and
324 * removes HTML comments; the result will always be balanced and
325 * tidy HTML.
326 * @param string $text Source string; see T268353 for why untainted
327 * @param-taint $text none
328 * @param array $options Options controlling the cleanup:
329 * string[] $options['extraTags'] Any extra tags to allow
330 * (This property taints the whole array.)
331 * string[] $options['removeTags'] Any tags (default or extra) to exclude
332 * callable(Attributes,...):Attributes $options['attrCallback'] Callback
333 * to do any variable or parameter replacements in HTML attribute
334 * values before further cleanup; should be considered @internal
335 * and not for external use.
336 * array $options['attrCallbackArgs'] Additional arguments for the
337 * attribute callback
338 * @param-taint $options tainted
339 * @return string The cleaned up HTML
340 * @return-taint escaped
341 * @since 1.38
342 */
343 public static function removeSomeTags(
344 string $text, array $options = []
345 ): string {
346 $extraTags = $options['extraTags'] ?? [];
347 $removeTags = $options['removeTags'] ?? [];
348 // These options are @internal:
349 $attrCallback = $options['attrCallback'] ?? null;
350 $attrCallbackArgs = $options['attrCallbackArgs'] ?? [];
351
352 // This disallows HTML5-style "missing trailing semicolon" attributes
353 // In wikitext "clean&copy" does *not* contain an entity.
354 $text = self::normalizeCharReferences( $text );
355
356 $tagData = self::getRecognizedTagData( $extraTags, $removeTags );
357 // Use RemexHtml to tokenize $text and remove the barred tags
358 $formatter = new RemexCompatFormatter;
359 $serializer = new RemexSerializer( $formatter );
360 $treeBuilder = new RemexTreeBuilder( $serializer, [
361 'ignoreErrors' => true,
362 'ignoreNulls' => true,
363 ] );
364 $dispatcher = new RemexDispatcher( $treeBuilder );
365 $tokenHandler = $dispatcher;
366 $remover = new RemexRemoveTagHandler(
367 $tokenHandler, $text, $tagData,
368 $attrCallback, $attrCallbackArgs
369 );
370 $tokenizer = new RemexTokenizer( $remover, $text, [
371 'ignoreErrors' => true,
372 // don't ignore char refs, we want them to be decoded
373 'ignoreNulls' => true,
374 'skipPreprocess' => true,
375 ] );
376 $tokenizer->execute( [
377 'fragmentNamespace' => HTMLData::NS_HTML,
378 'fragmentName' => 'body',
379 ] );
380 return $serializer->getResult();
381 }
382
383 /**
384 * Remove '<!--', '-->', and everything between.
385 * To avoid leaving blank lines, when a comment is both preceded
386 * and followed by a newline (ignoring spaces), trim leading and
387 * trailing spaces and one of the newlines.
388 */
389 public static function removeHTMLcomments( string $text ): string {
390 // phpcs:ignore Generic.CodeAnalysis.AssignmentInCondition.FoundInWhileCondition
391 while ( ( $start = strpos( $text, '<!--' ) ) !== false ) {
392 $end = strpos( $text, '-->', $start + 4 );
393 if ( $end === false ) {
394 # Unterminated comment; bail out
395 break;
396 }
397
398 $end += 3;
399
400 # Trim space and newline if the comment is both
401 # preceded and followed by a newline
402 $spaceStart = max( $start - 1, 0 );
403 $spaceLen = $end - $spaceStart;
404 while ( substr( $text, $spaceStart, 1 ) === ' ' && $spaceStart > 0 ) {
405 $spaceStart--;
406 $spaceLen++;
407 }
408 while ( substr( $text, $spaceStart + $spaceLen, 1 ) === ' ' ) {
409 $spaceLen++;
410 }
411 if ( substr( $text, $spaceStart, 1 ) === "\n"
412 && substr( $text, $spaceStart + $spaceLen, 1 ) === "\n" ) {
413 # Remove the comment, leading and trailing
414 # spaces, and leave only one newline.
415 $text = substr_replace( $text, "\n", $spaceStart, $spaceLen + 1 );
416 } else {
417 # Remove just the comment.
418 $text = substr_replace( $text, '', $start, $end - $start );
419 }
420 }
421 return $text;
422 }
423
424 /**
425 * Takes attribute names and values for a tag and the tag name and
426 * validates that the tag is allowed to be present.
427 * This DOES NOT validate the attributes, nor does it validate the
428 * tags themselves. This method only handles the special circumstances
429 * where we may want to allow a tag within content but ONLY when it has
430 * specific attributes set.
431 *
432 * @see RemexRemoveTagHandler::validateTag()
433 */
434 private static function validateTag( string $params, string $element ): bool {
435 $params = self::decodeTagAttributes( $params );
436
437 if ( $element == 'meta' || $element == 'link' ) {
438 if ( !isset( $params['itemprop'] ) ) {
439 // <meta> and <link> must have an itemprop="" otherwise they are not valid or safe in content
440 return false;
441 }
442 if ( $element == 'meta' && !isset( $params['content'] ) ) {
443 // <meta> must have a content="" for the itemprop
444 return false;
445 }
446 if ( $element == 'link' && !isset( $params['href'] ) ) {
447 // <link> must have an associated href=""
448 return false;
449 }
450 }
451
452 return true;
453 }
454
455 /**
456 * Take an array of attribute names and values and normalize or discard
457 * illegal values for the given element type.
458 *
459 * - Discards attributes not allowed for the given element
460 * - Unsafe style attributes are discarded
461 * - Invalid id attributes are re-encoded
462 *
463 * @todo Check for legal values where the DTD limits things.
464 * @todo Check for unique id attribute :P
465 */
466 public static function validateTagAttributes( array $attribs, string $element ): array {
467 return self::validateAttributes( $attribs,
468 self::attributesAllowedInternal( $element ) );
469 }
470
471 /**
472 * Take an array of attribute names and values and normalize or discard
473 * illegal values.
474 *
475 * - Discards attributes not on the given list
476 * - Unsafe style attributes are discarded
477 * - Invalid id attributes are re-encoded
478 *
479 * @param array $attribs
480 * @param array $allowed List of allowed attribute names,
481 * as an associative array where keys give valid attribute names
482 * (since 1.34). Before 1.35, passing a sequential array of
483 * valid attribute names was permitted but that is now deprecated.
484 * @return array
485 *
486 * @todo Check for legal values where the DTD limits things.
487 * @todo Check for unique id attribute :P
488 */
489 public static function validateAttributes( array $attribs, array $allowed ): array {
490 if ( isset( $allowed[0] ) ) {
491 // Calling this function with a sequential array is
492 // deprecated. For now just convert it.
493 wfDeprecated( __METHOD__ . ' with sequential array', '1.35' );
494 $allowed = array_fill_keys( $allowed, true );
495 }
496 $validProtocols = MediaWikiServices::getInstance()->getUrlUtils()->validProtocols();
497 $hrefExp = '/^(' . $validProtocols . ')[^\s]+$/';
498
499 $out = [];
500 foreach ( $attribs as $attribute => $value ) {
501 # Allow XML namespace declaration to allow RDFa
502 if ( preg_match( self::XMLNS_ATTRIBUTE_PATTERN, $attribute ) ) {
503 if ( !preg_match( self::EVIL_URI_PATTERN, $value ) ) {
504 $out[$attribute] = $value;
505 }
506
507 continue;
508 }
509
510 # Allow any attribute beginning with "data-"
511 # However:
512 # * Disallow data attributes used by MediaWiki code
513 # * Ensure that the attribute is not namespaced by banning
514 # colons.
515 # * Ensure attribute name will be accepted by the HTML
516 # parser; see
517 # https://github.com/whatwg/dom/issues/849#issuecomment-1007541209
518 # * Underscore and double-wide underscore (U+FF3F) is disallowed
519 # here (but not in Parsoid): T407131
520 if ( (
521 !preg_match( '|^data-[^:= \t\r\n/>\0__]*$|i', $attribute ) &&
522 !array_key_exists( $attribute, $allowed )
523 ) || self::isReservedDataAttribute( $attribute ) ) {
524 continue;
525 }
526
527 # Strip javascript "expression" from stylesheets.
528 # https://msdn.microsoft.com/en-us/library/ms537634.aspx
529 if ( $attribute == 'style' ) {
530 $value = self::checkCss( $value );
531 }
532
533 # Escape HTML id attributes
534 if ( $attribute === 'id' ) {
535 $value = self::escapeIdForAttribute( $value, self::ID_PRIMARY );
536 if ( $value === false || $value === '' ) {
537 continue;
538 }
539 }
540
541 # Escape HTML id reference lists
542 if ( $attribute === 'aria-describedby'
543 || $attribute === 'aria-flowto'
544 || $attribute === 'aria-labelledby'
545 || $attribute === 'aria-owns'
546 ) {
547 $value = self::escapeIdReferenceListInternal( $value );
548 }
549
550 // RDFa and microdata properties allow URLs, URIs and/or CURIs.
551 if ( $attribute === 'rel' || $attribute === 'rev'
552 # RDFa
553 || $attribute === 'about' || $attribute === 'property'
554 || $attribute === 'resource' || $attribute === 'datatype'
555 || $attribute === 'typeof'
556 # HTML5 microdata
557 || $attribute === 'itemid' || $attribute === 'itemprop'
558 || $attribute === 'itemref' || $attribute === 'itemscope'
559 || $attribute === 'itemtype'
560 ) {
561 // Paranoia. Allow "simple" values but suppress javascript
562 if ( preg_match( self::EVIL_URI_PATTERN, $value ) ) {
563 continue;
564 }
565 }
566
567 # NOTE: even though elements using href/src are not allowed directly, supply
568 # validation code that can be used by tag hook handlers, etc
569 if ( $attribute === 'href' || $attribute === 'src' || $attribute === 'poster' ) {
570 if ( !preg_match( $hrefExp, $value ) ) {
571 continue; // drop any href or src attributes not using an allowed protocol.
572 // NOTE: this also drops all relative URLs
573 }
574 }
575
576 if ( $attribute === 'tabindex' && $value !== '0' ) {
577 // Only allow tabindex of 0, which is useful for accessibility.
578 continue;
579 }
580
581 // If this attribute was previously set, override it.
582 // Output should only have one attribute of each name.
583 $out[$attribute] = $value;
584 }
585
586 # itemtype, itemid, itemref don't make sense without itemscope
587 if ( !array_key_exists( 'itemscope', $out ) ) {
588 unset( $out['itemtype'] );
589 unset( $out['itemid'] );
590 unset( $out['itemref'] );
591 }
592 # TODO: Strip itemprop if we aren't descendants of an itemscope or pointed to by an itemref.
593
594 return $out;
595 }
596
597 /**
598 * Given an attribute name, checks whether it is a reserved data attribute
599 * (such as data-mw-foo) which is unavailable to user-generated HTML so MediaWiki
600 * core and extension code can safely use it to communicate with frontend code.
601 * @param string $attr Attribute name.
602 * @return bool
603 */
604 public static function isReservedDataAttribute( string $attr ): bool {
605 // data-ooui is reserved for ooui.
606 // data-mw and data-parsoid are reserved for parsoid.
607 // data-mw-<name here> is reserved for extensions (or core) if
608 // they need to communicate some data to the client and want to be
609 // sure that it isn't coming from an untrusted user.
610 // We ignore the possibility of namespaces since user-generated HTML
611 // can't use them anymore.
612 return (bool)preg_match( '/^data-(ooui|mw|parsoid)/i', $attr );
613 }
614
615 /**
616 * Merge two sets of HTML attributes. Conflicting items in the second set
617 * will override those in the first, except for 'class' attributes which
618 * will be combined (if they're both strings).
619 *
620 * @todo implement merging for other attributes such as style
621 */
622 public static function mergeAttributes( array $a, array $b ): array {
623 $out = array_merge( $a, $b );
624 if ( isset( $a['class'] ) && isset( $b['class'] )
625 && is_string( $a['class'] ) && is_string( $b['class'] )
626 && $a['class'] !== $b['class']
627 ) {
628 $classes = preg_split( '/\s+/', "{$a['class']} {$b['class']}",
629 -1, PREG_SPLIT_NO_EMPTY );
630 $out['class'] = implode( ' ', array_unique( $classes ) );
631 }
632 return $out;
633 }
634
635 /**
636 * Normalize CSS into a format we can easily search for hostile input
637 * - decode character references
638 * - decode escape sequences
639 * - remove comments, unless the entire value is one single comment
640 * @param string $value the css string
641 * @return string normalized css
642 */
643 public static function normalizeCss( string $value ): string {
644 // Decode character references like &#123;
645 $value = self::decodeCharReferences( $value );
646
647 // Decode escape sequences and line continuation
648 // See the grammar in the CSS 2 spec, appendix D.
649 // This has to be done AFTER decoding character references.
650 // This means it isn't possible for this function to return
651 // unsanitized escape sequences. It is possible to manufacture
652 // input that contains character references that decode to
653 // escape sequences that decode to character references, but
654 // it's OK for the return value to contain character references
655 // because the caller is supposed to escape those anyway.
656 static $decodeRegex;
657 if ( !$decodeRegex ) {
658 $space = '[\\x20\\t\\r\\n\\f]';
659 $nl = '(?:\\n|\\r\\n|\\r|\\f)';
660 $backslash = '\\\\';
661 $decodeRegex = "/ $backslash
662 (?:
663 ($nl) | # 1. Line continuation
664 ([0-9A-Fa-f]{1,6})$space? | # 2. character number
665 (.) | # 3. backslash cancelling special meaning
666 () | # 4. backslash at end of string
667 )/xu";
668 }
669 $value = preg_replace_callback( $decodeRegex,
670 [ __CLASS__, 'cssDecodeCallback' ], $value );
671
672 // Let the value through if it's nothing but a single comment, to
673 // allow other functions which may reject it to pass some error
674 // message through.
675 if ( !preg_match( '! ^ \s* /\* [^*\\/]* \*/ \s* $ !x', $value ) ) {
676 // Remove any comments; IE gets token splitting wrong
677 // This must be done AFTER decoding character references and
678 // escape sequences, because those steps can introduce comments
679 // This step cannot introduce character references or escape
680 // sequences, because it replaces comments with spaces rather
681 // than removing them completely.
682 $value = StringUtils::delimiterReplace( '/*', '*/', ' ', $value );
683
684 // Remove anything after a comment-start token, to guard against
685 // incorrect client implementations.
686 $commentPos = strpos( $value, '/*' );
687 if ( $commentPos !== false ) {
688 $value = substr( $value, 0, $commentPos );
689 }
690 }
691
692 return $value;
693 }
694
695 /**
696 * Pick apart some CSS and check it for forbidden or unsafe structures.
697 * Returns a sanitized string. This sanitized string will have
698 * character references and escape sequences decoded and comments
699 * stripped (unless it is itself one valid comment, in which case the value
700 * will be passed through). If the input is just too evil, only a comment
701 * complaining about evilness will be returned.
702 *
703 * Currently URL references, 'expression', 'tps' are forbidden.
704 *
705 * NOTE: Despite the fact that character references are decoded, the
706 * returned string may contain character references given certain
707 * clever input strings. These character references must
708 * be escaped before the return value is embedded in HTML.
709 *
710 * @warning This method is intended to sanitize style attributes on
711 * html tags only. It is not safe to use on full CSS files.
712 * @param string $value
713 * @return string
714 */
715 public static function checkCss( $value ) {
716 $value = self::normalizeCss( $value );
717
718 // Reject problematic keywords and control characters
719 if ( preg_match( '/[\000-\010\013\016-\037\177]/', $value ) ||
720 strpos( $value, \UtfNormal\Constants::UTF8_REPLACEMENT ) !== false ) {
721 return '/* invalid control char */';
722 } elseif ( preg_match(
723 '! expression
724 | accelerator\s*:
725 | -o-link\s*:
726 | -o-link-source\s*:
727 | -o-replace\s*:
728 | url\s*\(
729 | src\s*\(
730 | image\s*\(
731 | image-set\s*\(
732 | attr\s*\([^)]+[\s,]+url
733 !ix', $value ) ) {
734 return '/* insecure input */';
735 }
736 return $value;
737 }
738
739 private static function cssDecodeCallback( array $matches ): string {
740 if ( $matches[1] !== '' ) {
741 // Line continuation
742 return '';
743 } elseif ( $matches[2] !== '' ) {
744 # hexdec could return a float if the match is too long, but the
745 # regexp in question limits the string length to 6.
746 $char = \UtfNormal\Utils::codepointToUtf8( hexdec( $matches[2] ) );
747 } elseif ( $matches[3] !== '' ) {
748 $char = $matches[3];
749 } else {
750 $char = '\\';
751 }
752 if ( $char == "\n" || $char == '"' || $char == "'" || $char == '\\' ) {
753 // These characters need to be escaped in strings
754 // Clean up the escape sequence to avoid parsing errors by clients
755 return '\\' . dechex( ord( $char ) ) . ' ';
756 } else {
757 // Decode unnecessary escape
758 return $char;
759 }
760 }
761
762 /**
763 * Take a tag soup fragment listing an HTML element's attributes
764 * and normalize it to well-formed XML, discarding unwanted attributes.
765 * Output is safe for further wikitext processing, with escaping of
766 * values that could trigger problems.
767 *
768 * - Normalizes attribute names to lowercase
769 * - Discards attributes not allowed for the given element
770 * - Turns broken or invalid entities into plaintext
771 * - Double-quotes all attribute values
772 * - Attributes without values are given the name as attribute
773 * - Double attributes are discarded
774 * - Unsafe style attributes are discarded
775 * - Prepends space if there are attributes.
776 * - (Optionally) Sorts attributes by name.
777 *
778 * @param string $text
779 * @param string $element
780 * @param bool $sorted Whether to sort the attributes (default: false)
781 * @return string
782 */
783 public static function fixTagAttributes( string $text, string $element, bool $sorted = false ): string {
784 if ( trim( $text ) == '' ) {
785 return '';
786 }
787
788 $decoded = self::decodeTagAttributes( $text );
789 $stripped = self::validateTagAttributes( $decoded, $element );
790
791 if ( $sorted ) {
792 ksort( $stripped );
793 }
794
795 return self::safeEncodeTagAttributes( $stripped );
796 }
797
798 /**
799 * Encode an attribute value for HTML output.
800 * @param string $text
801 * @param-taint $text escapes_html
802 * @return string HTML-encoded text fragment
803 * @return-taint escaped
804 */
805 public static function encodeAttribute( string $text ): string {
806 $encValue = htmlspecialchars( $text, ENT_QUOTES );
807
808 // Whitespace is normalized during attribute decoding,
809 // so if we've been passed non-spaces we must encode them
810 // ahead of time or they won't be preserved.
811 $encValue = strtr( $encValue, [
812 "\n" => '&#10;',
813 "\r" => '&#13;',
814 "\t" => '&#9;',
815 ] );
816
817 return $encValue;
818 }
819
820 /**
821 * Armor French spaces with a replacement character
822 *
823 * @since 1.32
824 * @param string $text Text to armor
825 * @param string $space Space character for the French spaces, defaults to '&#160;'
826 * @return string Armored text
827 */
828 public static function armorFrenchSpaces( string $text, string $space = '&#160;' ): string {
829 // Replace $ with \$ and \ with \\
830 $space = preg_replace( '#(?<!\\\\)(\\$|\\\\)#', '\\\\$1', $space );
831 $fixtags = [
832 # French spaces, last one Guillemet-left
833 # only if it isn't followed by a word character.
834 '/ (?=[?:;!%»›](?!\w))/u' => "$space",
835 # French spaces, Guillemet-right
836 '/([«‹]) /u' => "\\1$space",
837 ];
838 return preg_replace( array_keys( $fixtags ), array_values( $fixtags ), $text );
839 }
840
841 /**
842 * Encode an attribute value for HTML tags, with extra armoring
843 * against further wiki processing.
844 * @param string $text
845 * @param-taint $text escapes_html
846 * @return string HTML-encoded text fragment
847 * @return-taint escaped
848 */
849 public static function safeEncodeAttribute( string $text ): string {
850 $encValue = self::encodeAttribute( $text );
851
852 # Templates and links may be expanded in later parsing,
853 # creating invalid or dangerous output. Suppress this.
854 $encValue = strtr( $encValue, [
855 // '<', '>', and '"' should never happen, as they indicate that we've received invalid input which should
856 // have been escaped.
857 '<' => '&lt;',
858 '>' => '&gt;',
859 '"' => '&quot;',
860 '{' => '&#123;',
861 '}' => '&#125;', // prevent unpaired language conversion syntax
862 '[' => '&#91;',
863 ']' => '&#93;',
864 "''" => '&#39;&#39;',
865 'ISBN' => '&#73;SBN',
866 'RFC' => '&#82;FC',
867 'PMID' => '&#80;MID',
868 '|' => '&#124;',
869 '_' => '&#95;',
870 '_' => '&#xFF3F;', // Japanese magic words
871 ] );
872
873 # Stupid hack
874 $validProtocols = MediaWikiServices::getInstance()->getUrlUtils()->validProtocols();
875 $encValue = preg_replace_callback(
876 '/((?i)' . $validProtocols . ')/',
877 static function ( $matches ) {
878 return str_replace( ':', '&#58;', $matches[1] );
879 },
880 $encValue );
881 return $encValue;
882 }
883
884 /**
885 * Given a section name or other user-generated or otherwise unsafe string, escapes it to be
886 * a valid HTML id attribute.
887 *
888 * WARNING: The output of this function is not guaranteed to be HTML safe, so be sure to use
889 * proper escaping.
890 *
891 * @param string $id String to escape
892 * @param int $mode One of ID_* constants, specifying whether the primary or fallback encoding
893 * should be used.
894 * @return string|false Escaped ID or false if fallback encoding is requested but it's not
895 * configured.
896 *
897 * @since 1.30
898 */
899 public static function escapeIdForAttribute( string $id, int $mode = self::ID_PRIMARY ) {
900 global $wgFragmentMode;
901
902 if ( !isset( $wgFragmentMode[$mode] ) ) {
903 if ( $mode === self::ID_PRIMARY ) {
904 throw new UnexpectedValueException( '$wgFragmentMode is configured with no primary mode' );
905 }
906 return false;
907 }
908
909 $internalMode = $wgFragmentMode[$mode];
910
911 return self::escapeIdInternal( $id, $internalMode );
912 }
913
914 /**
915 * Given a section name or other user-generated or otherwise unsafe string, escapes it to be
916 * a valid URL fragment.
917 *
918 * WARNING: The output of this function is not guaranteed to be HTML safe, so be sure to use
919 * proper escaping.
920 *
921 * @param string $id String to escape
922 * @return string Escaped ID
923 *
924 * @since 1.30
925 */
926 public static function escapeIdForLink( string $id ): string {
927 global $wgFragmentMode;
928
929 if ( !isset( $wgFragmentMode[self::ID_PRIMARY] ) ) {
930 throw new UnexpectedValueException( '$wgFragmentMode is configured with no primary mode' );
931 }
932
933 $mode = $wgFragmentMode[self::ID_PRIMARY];
934
935 $id = self::escapeIdInternalUrl( $id, $mode );
936
937 return $id;
938 }
939
940 /**
941 * Given a section name or other user-generated or otherwise unsafe string, escapes it to be
942 * a valid URL fragment for external interwikis.
943 *
944 * @param string $id String to escape
945 * @return string Escaped ID
946 *
947 * @since 1.30
948 */
949 public static function escapeIdForExternalInterwiki( string $id ): string {
950 global $wgExternalInterwikiFragmentMode;
951
952 $id = self::escapeIdInternalUrl( $id, $wgExternalInterwikiFragmentMode );
953
954 return $id;
955 }
956
957 /**
958 * Do percent encoding of percent signs for href (but not id) attributes
959 *
960 * @since 1.35
961 * @see https://phabricator.wikimedia.org/T238385
962 * @param string $id String to escape
963 * @param string $mode One of modes from $wgFragmentMode
964 * @return string
965 */
966 private static function escapeIdInternalUrl( string $id, string $mode ): string {
967 $id = self::escapeIdInternal( $id, $mode );
968 if ( $mode === 'html5' ) {
969 $id = preg_replace( '/%([a-fA-F0-9]{2})/', '%25$1', $id );
970 }
971 return $id;
972 }
973
974 /**
975 * Helper for escapeIdFor*() functions. Performs most of the actual escaping.
976 *
977 * @param string $id String to escape
978 * @param string $mode One of modes from $wgFragmentMode
979 * @return string
980 */
981 private static function escapeIdInternal( string $id, string $mode ): string {
982 // Truncate overly-long IDs. This isn't an HTML limit, it's just
983 // griefer protection. [T251506]
984 $id = mb_substr( $id, 0, 1024 );
985
986 switch ( $mode ) {
987 case 'html5':
988 // html5 spec says ids must not have any of the following:
989 // U+0009 TAB, U+000A LF, U+000C FF, U+000D CR, or U+0020 SPACE
990 // In practice, in wikitext, only tab, LF, CR (and SPACE) are
991 // possible using either Lua or html entities.
992 $id = str_replace( [ "\t", "\n", "\f", "\r", " " ], '_', $id );
993 break;
994 case 'legacy':
995 // This corresponds to 'noninitial' mode of the former escapeId()
996 static $replace = [
997 '%3A' => ':',
998 '%' => '.'
999 ];
1000
1001 $id = urlencode( str_replace( ' ', '_', $id ) );
1002 $id = strtr( $id, $replace );
1003 break;
1004 default:
1005 throw new InvalidArgumentException( "Invalid mode '$mode' passed to '" . __METHOD__ );
1006 }
1007
1008 return $id;
1009 }
1010
1011 /**
1012 * Given a string containing a space delimited list of ids, escape each id
1013 * to match ids escaped by the escapeIdForAttribute() function.
1014 *
1015 * @param string $referenceString Space delimited list of ids
1016 * @return string
1017 */
1018 private static function escapeIdReferenceListInternal( string $referenceString ): string {
1019 # Explode the space delimited list string into an array of tokens
1020 $references = preg_split( '/\s+/', "{$referenceString}", -1, PREG_SPLIT_NO_EMPTY );
1021
1022 # Escape each token as an id
1023 foreach ( $references as &$ref ) {
1024 $ref = self::escapeIdForAttribute( $ref );
1025 }
1026
1027 # Merge the array back to a space delimited list string
1028 # If the array is empty, the result will be an empty string ('')
1029 $referenceString = implode( ' ', $references );
1030
1031 return $referenceString;
1032 }
1033
1034 /**
1035 * Given a value, escape it so that it can be used as a CSS class and
1036 * return it.
1037 *
1038 * @todo For extra validity, input should be validated UTF-8.
1039 *
1040 * @see https://www.w3.org/TR/CSS21/syndata.html Valid characters/format
1041 */
1042 public static function escapeClass( string $class ): string {
1043 // Convert ugly stuff to underscores and kill underscores in ugly places
1044 return rtrim( preg_replace(
1045 [ '/(^[0-9\\-])|[\\x00-\\x20!"#$%&\'()*+,.\\/:;<=>?@[\\]^`{|}~]|\\xC2\\xA0/', '/_+/' ],
1046 '_',
1047 $class ), '_' );
1048 }
1049
1050 public static function escapeCombiningChar( string $html ): string {
1051 return strtr( $html, [
1052 "\u{0338}" => '&#x338;', # T387130
1053 ] );
1054 }
1055
1056 /**
1057 * Given HTML input, escape with htmlspecialchars but un-escape entities.
1058 * This allows (generally harmless) entities like &#160; to survive.
1059 *
1060 * @param string $html HTML to escape
1061 * @param-taint $html escapes_htmlnoent
1062 * @return string Escaped input
1063 * @return-taint escaped
1064 */
1065 public static function escapeHtmlAllowEntities( string $html ): string {
1066 $html = self::decodeCharReferences( $html );
1067 # It seems wise to escape ' as well as ", as a matter of course. Can't
1068 # hurt. Use ENT_SUBSTITUTE so that incorrectly truncated multibyte characters
1069 # don't cause the entire string to disappear.
1070 $html = htmlspecialchars( $html, ENT_QUOTES | ENT_SUBSTITUTE );
1071 return self::escapeCombiningChar( $html );
1072 }
1073
1074 /**
1075 * Return an associative array of attribute names and values from
1076 * a partial tag string. Attribute names are forced to lowercase,
1077 * character references are decoded to UTF-8 text.
1078 */
1079 public static function decodeTagAttributes( string $text ): array {
1080 if ( trim( $text ) == '' ) {
1081 return [];
1082 }
1083
1084 $pairs = [];
1085 if ( !preg_match_all(
1086 self::getAttribsRegex(),
1087 $text,
1088 $pairs,
1089 PREG_SET_ORDER ) ) {
1090 return [];
1091 }
1092
1093 $attribs = [];
1094 foreach ( $pairs as $set ) {
1095 $attribute = strtolower( $set[1] );
1096
1097 // Filter attribute names with unacceptable characters
1098 if ( !preg_match( self::getAttribNameRegex(), $attribute ) ) {
1099 continue;
1100 }
1101
1102 $value = self::getTagAttributeCallback( $set );
1103
1104 // Normalize whitespace
1105 $value = preg_replace( '/[\t\r\n ]+/', ' ', $value );
1106 $value = trim( $value );
1107
1108 // Decode character references
1109 $attribs[$attribute] = self::decodeCharReferences( $value );
1110 }
1111 return $attribs;
1112 }
1113
1114 /**
1115 * Build a partial tag string from an associative array of attribute
1116 * names and values as returned by decodeTagAttributes.
1117 */
1118 public static function safeEncodeTagAttributes( array $assoc_array ): string {
1119 $attribs = [];
1120 foreach ( $assoc_array as $attribute => $value ) {
1121 $encAttribute = htmlspecialchars( $attribute, ENT_COMPAT );
1122 $encValue = self::safeEncodeAttribute( $value );
1123
1124 $attribs[] = "$encAttribute=\"$encValue\"";
1125 }
1126 return count( $attribs ) ? ' ' . implode( ' ', $attribs ) : '';
1127 }
1128
1129 /**
1130 * Pick the appropriate attribute value from a match set from the
1131 * attribs regex matches.
1132 */
1133 private static function getTagAttributeCallback( array $set ): string {
1134 if ( isset( $set[5] ) ) {
1135 # No quotes.
1136 return $set[5];
1137 } elseif ( isset( $set[4] ) ) {
1138 # Single-quoted
1139 return $set[4];
1140 } elseif ( isset( $set[3] ) ) {
1141 # Double-quoted
1142 return $set[3];
1143 } elseif ( !isset( $set[2] ) ) {
1144 # In XHTML, attributes must have a value so return an empty string.
1145 # See "Empty attribute syntax",
1146 # https://www.w3.org/TR/html5/syntax.html#syntax-attribute-name
1147 return "";
1148 } else {
1149 throw new LogicException( "Tag conditions not met. This should never happen and is a bug." );
1150 }
1151 }
1152
1153 private static function normalizeWhitespace( string $text ): string {
1154 $normalized = preg_replace( '/[ \r\n\t]+/', ' ', $text );
1155 if ( $normalized === null ) {
1156 wfLogWarning( __METHOD__ . ': Failed to normalize whitespace: ' . preg_last_error() );
1157 return '';
1158 }
1159 return trim( $normalized );
1160 }
1161
1162 /**
1163 * Normalizes whitespace in a section name, such as might be returned
1164 * by Parser::stripSectionName(), for use in the id's that are used for
1165 * section links.
1166 */
1167 public static function normalizeSectionNameWhitespace( string $section ): string {
1168 $normalized = preg_replace( '/[ _]+/', ' ', $section );
1169 if ( $normalized === null ) {
1170 wfLogWarning( __METHOD__ . ': Failed to normalize whitespace: ' . preg_last_error() );
1171 return '';
1172 }
1173 return trim( $normalized );
1174 }
1175
1176 /**
1177 * Ensure that any entities and character references are legal
1178 * for XML and XHTML specifically. Any stray bits will be
1179 * &amp;-escaped to result in a valid text fragment.
1180 *
1181 * a. named char refs can only be &lt; &gt; &amp; &quot;, others are
1182 * numericized (this way we're well-formed even without a DTD)
1183 * b. any numeric char refs must be legal chars, not invalid or forbidden
1184 * c. use lower cased "&#x", not "&#X"
1185 * d. fix or reject non-valid attributes
1186 *
1187 * @internal
1188 */
1189 public static function normalizeCharReferences( string $text ): string {
1190 return preg_replace_callback(
1191 self::CHAR_REFS_REGEX,
1192 [ self::class, 'normalizeCharReferencesCallback' ],
1193 $text, -1, $count, PREG_UNMATCHED_AS_NULL
1194 );
1195 }
1196
1197 private static function normalizeCharReferencesCallback( array $matches ): string {
1198 $ret = null;
1199 if ( isset( $matches[1] ) ) {
1200 $ret = self::normalizeEntity( $matches[1] );
1201 } elseif ( isset( $matches[2] ) ) {
1202 $ret = self::decCharReference( $matches[2] );
1203 } elseif ( isset( $matches[3] ) ) {
1204 $ret = self::hexCharReference( $matches[3] );
1205 }
1206 if ( $ret === null ) {
1207 return htmlspecialchars( $matches[0], ENT_COMPAT );
1208 } else {
1209 return $ret;
1210 }
1211 }
1212
1213 /**
1214 * If the named entity is defined in HTML5
1215 * return the equivalent numeric entity reference (except for the core &lt;
1216 * &gt; &amp; &quot;). If the entity is a MediaWiki-specific alias, returns
1217 * the HTML equivalent. Otherwise, returns HTML-escaped text of
1218 * pseudo-entity source (eg &amp;foo;)
1219 *
1220 * @param string $name Semicolon-terminated name
1221 * @return string
1222 */
1223 private static function normalizeEntity( string $name ): string {
1224 if ( isset( self::MW_ENTITY_ALIASES[$name] ) ) {
1225 // Non-standard MediaWiki-specific entities
1226 return '&' . self::MW_ENTITY_ALIASES[$name];
1227 } elseif ( in_array( $name, [ 'lt;', 'gt;', 'amp;', 'quot;' ], true ) ) {
1228 // Keep these in word form
1229 return "&$name";
1230 } elseif ( isset( HTMLData::$namedEntityTranslations[$name] ) ) {
1231 // Beware: some entities expand to more than 1 codepoint
1232 return preg_replace_callback( '/./Ssu', static function ( $m ) {
1233 return '&#' . \UtfNormal\Utils::utf8ToCodepoint( $m[0] ) . ';';
1234 }, HTMLData::$namedEntityTranslations[$name] );
1235 } else {
1236 return "&amp;$name";
1237 }
1238 }
1239
1240 private static function decCharReference( string $codepoint ): ?string {
1241 # intval() will (safely) saturate at the maximum signed integer
1242 # value if $codepoint is too many digits
1243 $point = intval( $codepoint );
1244 if ( self::validateCodepoint( $point ) ) {
1245 return "&#$point;";
1246 } else {
1247 return null;
1248 }
1249 }
1250
1251 private static function hexCharReference( string $codepoint ): ?string {
1252 $point = hexdec( $codepoint );
1253 // hexdec() might return a float if the string is too long
1254 if ( is_int( $point ) && self::validateCodepoint( $point ) ) {
1255 return sprintf( '&#x%x;', $point );
1256 } else {
1257 return null;
1258 }
1259 }
1260
1261 /**
1262 * Returns true if a given Unicode codepoint is a valid character in
1263 * both HTML5 and XML.
1264 */
1265 private static function validateCodepoint( int $codepoint ): bool {
1266 # U+000C is valid in HTML5 but not allowed in XML.
1267 # U+000D is valid in XML but not allowed in HTML5.
1268 # U+007F - U+009F are disallowed in HTML5 (control characters).
1269 return $codepoint == 0x09
1270 || $codepoint == 0x0a
1271 || ( $codepoint >= 0x20 && $codepoint <= 0x7e )
1272 || ( $codepoint >= 0xa0 && $codepoint <= 0xd7ff )
1273 || ( $codepoint >= 0xe000 && $codepoint <= 0xfffd )
1274 || ( $codepoint >= 0x10000 && $codepoint <= 0x10ffff );
1275 }
1276
1277 /**
1278 * Decode any character references, numeric or named entities,
1279 * in the text and return a UTF-8 string.
1280 */
1281 public static function decodeCharReferences( string $text ): string {
1282 return preg_replace_callback(
1283 self::CHAR_REFS_REGEX,
1284 [ self::class, 'decodeCharReferencesCallback' ],
1285 $text, -1, $count, PREG_UNMATCHED_AS_NULL
1286 );
1287 }
1288
1289 /**
1290 * Decode any character references, numeric or named entities,
1291 * in the next and normalize the resulting string. (T16952)
1292 *
1293 * This is useful for page titles, not for text to be displayed,
1294 * MediaWiki allows HTML entities to escape normalization as a feature.
1295 *
1296 * @param string $text Already normalized, containing entities
1297 * @return string Still normalized, without entities
1298 */
1299 public static function decodeCharReferencesAndNormalize( string $text ): string {
1300 $text = preg_replace_callback(
1301 self::CHAR_REFS_REGEX,
1302 [ self::class, 'decodeCharReferencesCallback' ],
1303 $text, -1, $count, PREG_UNMATCHED_AS_NULL
1304 );
1305
1306 if ( $count ) {
1307 return MediaWikiServices::getInstance()->getContentLanguage()->normalize( $text );
1308 } else {
1309 return $text;
1310 }
1311 }
1312
1313 private static function decodeCharReferencesCallback( array $matches ): string {
1314 if ( isset( $matches[1] ) ) {
1315 return self::decodeEntity( $matches[1] );
1316 } elseif ( isset( $matches[2] ) ) {
1317 // Value is user provided string and may exceed native int bounds.
1318 // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
1319 return self::decodeChar( @intval( $matches[2] ) );
1320 } elseif ( isset( $matches[3] ) ) {
1321 $point = hexdec( $matches[3] );
1322 // hexdec() might return a float if the string is too long
1323 if ( !is_int( $point ) ) {
1324 // Invalid character reference.
1325 return \UtfNormal\Constants::UTF8_REPLACEMENT;
1326 }
1327 return self::decodeChar( $point );
1328 }
1329 # Last case should be an ampersand by itself
1330 return $matches[0];
1331 }
1332
1333 /**
1334 * Return UTF-8 string for a codepoint if that is a valid
1335 * character reference, otherwise U+FFFD REPLACEMENT CHARACTER.
1336 * @internal
1337 */
1338 private static function decodeChar( int $codepoint ): string {
1339 if ( self::validateCodepoint( $codepoint ) ) {
1340 return \UtfNormal\Utils::codepointToUtf8( $codepoint );
1341 } else {
1342 return \UtfNormal\Constants::UTF8_REPLACEMENT;
1343 }
1344 }
1345
1346 /**
1347 * If the named entity is defined in HTML5
1348 * return the UTF-8 encoding of that character. Otherwise, returns
1349 * pseudo-entity source (eg "&foo;")
1350 *
1351 * @param string $name Semicolon-terminated entity name
1352 * @return string
1353 */
1354 private static function decodeEntity( string $name ): string {
1355 // These are MediaWiki-specific entities, not in the HTML standard
1356 if ( isset( self::MW_ENTITY_ALIASES[$name] ) ) {
1357 $name = self::MW_ENTITY_ALIASES[$name];
1358 }
1359 $trans = HTMLData::$namedEntityTranslations[$name] ?? null;
1360 return $trans ?? "&$name";
1361 }
1362
1363 /**
1364 * Fetch the list of acceptable attributes for a given element name.
1365 *
1366 * @param string $element
1367 * @return array An associative array where keys are acceptable attribute
1368 * names
1369 */
1370 private static function attributesAllowedInternal( string $element ): array {
1371 $list = self::setupAttributesAllowedInternal();
1372 return $list[$element] ?? [];
1373 }
1374
1375 /**
1376 * Foreach array key (an allowed HTML element), return an array
1377 * of allowed attributes.
1378 * @return array An associative array: keys are HTML element names;
1379 * values are associative arrays where the keys are allowed attribute
1380 * names.
1381 */
1382 private static function setupAttributesAllowedInternal(): array {
1383 static $allowed;
1384
1385 if ( $allowed !== null ) {
1386 return $allowed;
1387 }
1388
1389 // For lookup efficiency flip each attributes array so the keys are
1390 // the valid attributes.
1391 $merge = static function ( $a, $b, $c = [] ) {
1392 return array_merge(
1393 $a,
1394 array_fill_keys( $b, true ),
1395 array_fill_keys( $c, true ) );
1396 };
1397 $common = $merge( [], [
1398 # HTML
1399 'id',
1400 'class',
1401 'style',
1402 'lang',
1403 'dir',
1404 'title',
1405 'tabindex',
1406
1407 # WAI-ARIA
1408 'aria-describedby',
1409 'aria-flowto',
1410 'aria-hidden',
1411 'aria-label',
1412 'aria-labelledby',
1413 'aria-level',
1414 'aria-owns',
1415 'role',
1416
1417 # RDFa
1418 # These attributes are specified in section 9 of
1419 # https://www.w3.org/TR/2008/REC-rdfa-syntax-20081014
1420 'about',
1421 'property',
1422 'resource',
1423 'datatype',
1424 'typeof',
1425
1426 # Microdata. These are specified by
1427 # https://html.spec.whatwg.org/multipage/microdata.html#the-microdata-model
1428 'itemid',
1429 'itemprop',
1430 'itemref',
1431 'itemscope',
1432 'itemtype',
1433 ] );
1434
1435 $block = $merge( $common, [ 'align' ] );
1436
1437 $tablealign = [ 'align', 'valign' ];
1438 $tablecell = [
1439 'abbr',
1440 'axis',
1441 'headers',
1442 'scope',
1443 'rowspan',
1444 'colspan',
1445 'nowrap', # deprecated
1446 'width', # deprecated
1447 'height', # deprecated
1448 'bgcolor', # deprecated
1449 ];
1450
1451 # Numbers refer to sections in HTML 4.01 standard describing the element.
1452 # See: https://www.w3.org/TR/html4/
1453 $allowed = [
1454 # 7.5.4
1455 'div' => $block,
1456 'center' => $common, # deprecated
1457 'span' => $common,
1458
1459 # 7.5.5
1460 'h1' => $block,
1461 'h2' => $block,
1462 'h3' => $block,
1463 'h4' => $block,
1464 'h5' => $block,
1465 'h6' => $block,
1466
1467 # 7.5.6
1468 # address
1469
1470 # 8.2.4
1471 'bdo' => $common,
1472
1473 # 9.2.1
1474 'em' => $common,
1475 'strong' => $common,
1476 'cite' => $common,
1477 'dfn' => $common,
1478 'code' => $common,
1479 'samp' => $common,
1480 'kbd' => $common,
1481 'var' => $common,
1482 'abbr' => $common,
1483 # acronym
1484
1485 # 9.2.2
1486 'blockquote' => $merge( $common, [ 'cite' ] ),
1487 'q' => $merge( $common, [ 'cite' ] ),
1488
1489 # 9.2.3
1490 'sub' => $common,
1491 'sup' => $common,
1492
1493 # 9.3.1
1494 'p' => $block,
1495
1496 # 9.3.2
1497 'br' => $merge( $common, [ 'clear' ] ),
1498
1499 # https://www.w3.org/TR/html5/text-level-semantics.html#the-wbr-element
1500 'wbr' => $common,
1501
1502 # 9.3.4
1503 'pre' => $merge( $common, [ 'width' ] ),
1504
1505 # 9.4
1506 'ins' => $merge( $common, [ 'cite', 'datetime' ] ),
1507 'del' => $merge( $common, [ 'cite', 'datetime' ] ),
1508
1509 # 10.2
1510 'ul' => $merge( $common, [ 'type' ] ),
1511 'ol' => $merge( $common, [ 'type', 'start', 'reversed' ] ),
1512 'li' => $merge( $common, [ 'type', 'value' ] ),
1513
1514 # 10.3
1515 'dl' => $common,
1516 'dd' => $common,
1517 'dt' => $common,
1518
1519 # 11.2.1
1520 'table' => $merge( $common,
1521 [ 'summary', 'width', 'border', 'frame',
1522 'rules', 'cellspacing', 'cellpadding',
1523 'align', 'bgcolor',
1524 ] ),
1525
1526 # 11.2.2
1527 'caption' => $block,
1528
1529 # 11.2.3
1530 'thead' => $common,
1531 'tfoot' => $common,
1532 'tbody' => $common,
1533
1534 # 11.2.4
1535 'colgroup' => $merge( $common, [ 'span' ] ),
1536 'col' => $merge( $common, [ 'span' ] ),
1537
1538 # 11.2.5
1539 'tr' => $merge( $common, [ 'bgcolor' ], $tablealign ),
1540
1541 # 11.2.6
1542 'td' => $merge( $common, $tablecell, $tablealign ),
1543 'th' => $merge( $common, $tablecell, $tablealign ),
1544
1545 # 12.2
1546 # NOTE: <a> is not allowed directly, but this list of allowed
1547 # attributes is used from the Parser object
1548 'a' => $merge( $common, [ 'href', 'rel', 'rev' ] ), # rel/rev esp. for RDFa
1549
1550 # 13.2
1551 # Not usually allowed, but may be used for extension-style hooks
1552 # such as <math> when it is rasterized
1553 'img' => $merge( $common, [ 'alt', 'src', 'width', 'height', 'srcset' ] ),
1554 # Attributes for A/V tags added in T163583 / T133673
1555 'audio' => $merge( $common, [ 'controls', 'preload', 'width', 'height' ] ),
1556 'video' => $merge( $common, [ 'poster', 'controls', 'preload', 'width', 'height' ] ),
1557 'source' => $merge( $common, [ 'type', 'src' ] ),
1558 'track' => $merge( $common, [ 'type', 'src', 'srclang', 'kind', 'label' ] ),
1559
1560 # 15.2.1
1561 'tt' => $common,
1562 'b' => $common,
1563 'i' => $common,
1564 'big' => $common,
1565 'small' => $common,
1566 'strike' => $common,
1567 's' => $common,
1568 'u' => $common,
1569
1570 # 15.2.2
1571 'font' => $merge( $common, [ 'size', 'color', 'face' ] ),
1572 # basefont
1573
1574 # 15.3
1575 'hr' => $merge( $common, [ 'width' ] ),
1576
1577 # HTML Ruby annotation text module, simple ruby only.
1578 # https://www.w3.org/TR/html5/text-level-semantics.html#the-ruby-element
1579 'ruby' => $common,
1580 # rbc
1581 'rb' => $common,
1582 'rp' => $common,
1583 'rt' => $common, # $merge( $common, [ 'rbspan' ] ),
1584 'rtc' => $common,
1585
1586 # MathML root element, where used for extensions
1587 # 'title' may not be 100% valid here; it's XHTML
1588 # https://www.w3.org/TR/REC-MathML/
1589 'math' => $merge( [], [ 'class', 'style', 'id', 'title' ] ),
1590
1591 // HTML 5 section 4.5
1592 'figure' => $common,
1593 'figcaption' => $common,
1594
1595 # HTML 5 section 4.6
1596 'bdi' => $common,
1597
1598 # HTML5 elements, defined by:
1599 # https://html.spec.whatwg.org/multipage/semantics.html#the-data-element
1600 'data' => $merge( $common, [ 'value' ] ),
1601 'time' => $merge( $common, [ 'datetime' ] ),
1602 'mark' => $common,
1603
1604 // meta and link are only permitted by internalRemoveHtmlTags when Microdata
1605 // is enabled so we don't bother adding a conditional to hide these
1606 // Also meta and link are only valid in WikiText as Microdata elements
1607 // (ie: validateTag rejects tags missing the attributes needed for Microdata)
1608 // So we don't bother including $common attributes that have no purpose.
1609 'meta' => $merge( [], [ 'itemprop', 'content' ] ),
1610 'link' => $merge( [], [ 'itemprop', 'href', 'title' ] ),
1611
1612 # HTML 5 section 4.3.5
1613 'aside' => $common,
1614 ];
1615
1616 return $allowed;
1617 }
1618
1619 /**
1620 * Take a fragment of (potentially invalid) HTML and return
1621 * a version with any tags removed, encoded as plain text.
1622 *
1623 * Warning: this return value must be further escaped for literal
1624 * inclusion in HTML output as of 1.10!
1625 *
1626 * @param string $html HTML fragment
1627 * @return string
1628 * @return-taint tainted
1629 */
1630 public static function stripAllTags( string $html ): string {
1631 // Use RemexHtml to tokenize $html and extract the text
1632 $handler = new RemexStripTagHandler;
1633 $tokenizer = new RemexTokenizer( $handler, $html, [
1634 'ignoreErrors' => true,
1635 // don't ignore char refs, we want them to be decoded
1636 'ignoreNulls' => true,
1637 'skipPreprocess' => true,
1638 ] );
1639 $tokenizer->execute();
1640 $text = $handler->getResult();
1641
1642 $text = self::normalizeWhitespace( $text );
1643 return $text;
1644 }
1645
1646 /**
1647 * Hack up a private DOCTYPE with HTML's standard entity declarations.
1648 * PHP 4 seemed to know these if you gave it an HTML doctype, but
1649 * PHP 5.1 doesn't.
1650 *
1651 * Use for passing XHTML fragments to PHP's XML parsing functions
1652 *
1653 * @deprecated since 1.36; will be made private or removed in a future
1654 * release.
1655 */
1656 public static function hackDocType(): string {
1657 $out = "<!DOCTYPE html [\n";
1658 foreach ( HTMLData::$namedEntityTranslations as $entity => $translation ) {
1659 if ( substr( $entity, -1 ) !== ';' ) {
1660 // Some HTML entities omit the trailing semicolon;
1661 // wikitext does not permit these.
1662 continue;
1663 }
1664 $name = substr( $entity, 0, -1 );
1665 $expansion = self::normalizeEntity( $entity );
1666 if ( $entity === $expansion ) {
1667 // Skip &lt; &gt; etc
1668 continue;
1669 }
1670 $out .= "<!ENTITY $name \"$expansion\">";
1671 }
1672 $out .= "]>\n";
1673 return $out;
1674 }
1675
1676 public static function cleanUrl( string $url ): string {
1677 # Normalize any HTML entities in input. They will be
1678 # re-escaped by makeExternalLink().
1679 $url = self::decodeCharReferences( $url );
1680
1681 # Escape any control characters introduced by the above step
1682 $url = preg_replace_callback( '/[\][<>"\\x00-\\x20\\x7F\|]+/',
1683 static fn ( $m ) => urlencode( $m[0] ), $url );
1684
1685 # Validate hostname portion
1686 $matches = [];
1687 if ( preg_match( '!^([^:]+:)(//[^/]+)?(.*)$!iD', $url, $matches ) ) {
1688 [ /* $whole */, $protocol, $host, $rest ] = $matches;
1689
1690 // Characters that will be ignored in IDNs.
1691 // https://datatracker.ietf.org/doc/html/rfc8264#section-9.13
1692 // https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
1693 // Strip them before further processing so deny lists and such work.
1694 $strip = "/
1695 \\s| # general whitespace
1696 \u{00AD}| # SOFT HYPHEN
1697 \u{034F}| # COMBINING GRAPHEME JOINER
1698 \u{061C}| # ARABIC LETTER MARK
1699 [\u{115F}-\u{1160}]| # HANGUL CHOSEONG FILLER..
1700 # HANGUL JUNGSEONG FILLER
1701 [\u{17B4}-\u{17B5}]| # KHMER VOWEL INHERENT AQ..
1702 # KHMER VOWEL INHERENT AA
1703 [\u{180B}-\u{180D}]| # MONGOLIAN FREE VARIATION SELECTOR ONE..
1704 # MONGOLIAN FREE VARIATION SELECTOR THREE
1705 \u{180E}| # MONGOLIAN VOWEL SEPARATOR
1706 [\u{200B}-\u{200F}]| # ZERO WIDTH SPACE..
1707 # RIGHT-TO-LEFT MARK
1708 [\u{202A}-\u{202E}]| # LEFT-TO-RIGHT EMBEDDING..
1709 # RIGHT-TO-LEFT OVERRIDE
1710 [\u{2060}-\u{2064}]| # WORD JOINER..
1711 # INVISIBLE PLUS
1712 \u{2065}| # <reserved-2065>
1713 [\u{2066}-\u{206F}]| # LEFT-TO-RIGHT ISOLATE..
1714 # NOMINAL DIGIT SHAPES
1715 \u{3164}| # HANGUL FILLER
1716 [\u{FE00}-\u{FE0F}]| # VARIATION SELECTOR-1..
1717 # VARIATION SELECTOR-16
1718 \u{FEFF}| # ZERO WIDTH NO-BREAK SPACE
1719 \u{FFA0}| # HALFWIDTH HANGUL FILLER
1720 [\u{FFF0}-\u{FFF8}]| # <reserved-FFF0>..
1721 # <reserved-FFF8>
1722 [\u{1BCA0}-\u{1BCA3}]| # SHORTHAND FORMAT LETTER OVERLAP..
1723 # SHORTHAND FORMAT UP STEP
1724 [\u{1D173}-\u{1D17A}]| # MUSICAL SYMBOL BEGIN BEAM..
1725 # MUSICAL SYMBOL END PHRASE
1726 \u{E0000}| # <reserved-E0000>
1727 \u{E0001}| # LANGUAGE TAG
1728 [\u{E0002}-\u{E001F}]| # <reserved-E0002>..
1729 # <reserved-E001F>
1730 [\u{E0020}-\u{E007F}]| # TAG SPACE..
1731 # CANCEL TAG
1732 [\u{E0080}-\u{E00FF}]| # <reserved-E0080>..
1733 # <reserved-E00FF>
1734 [\u{E0100}-\u{E01EF}]| # VARIATION SELECTOR-17..
1735 # VARIATION SELECTOR-256
1736 [\u{E01F0}-\u{E0FFF}]| # <reserved-E01F0>..
1737 # <reserved-E0FFF>
1738 /xuD";
1739
1740 $host = preg_replace( $strip, '', $host );
1741
1742 // IPv6 host names are bracketed with []. Url-decode these.
1743 if ( str_starts_with( $host, "//%5B" ) &&
1744 preg_match( '!^//%5B([0-9A-Fa-f:.]+)%5D((:\d+)?)$!', $host, $matches )
1745 ) {
1746 $host = '//[' . $matches[1] . ']' . $matches[2];
1747 }
1748
1749 // @todo FIXME: Validate hostnames here
1750
1751 return $protocol . $host . $rest;
1752 } else {
1753 return $url;
1754 }
1755 }
1756
1757 /**
1758 * Does a string look like an e-mail address?
1759 *
1760 * This validates an email address using an HTML5 specification found at:
1761 * http://www.whatwg.org/html/states-of-the-type-attribute.html#valid-e-mail-address
1762 * Which as of 2011-01-24 says:
1763 *
1764 * A valid e-mail address is a string that matches the ABNF production
1765 * 1*( atext / "." ) "@" ldh-str *( "." ldh-str ) where atext is defined
1766 * in RFC 5322 section 3.2.3, and ldh-str is defined in RFC 1034 section
1767 * 3.5.
1768 *
1769 * This function is an implementation of the specification as requested in
1770 * T24449.
1771 *
1772 * Client-side forms will use the same standard validation rules via JS or
1773 * HTML 5 validation; additional restrictions can be enforced server-side
1774 * by extensions via the 'isValidEmailAddr' hook.
1775 *
1776 * Note that this validation doesn't 100% match RFC 2822, but is believed
1777 * to be liberal enough for wide use. Some invalid addresses will still
1778 * pass validation here.
1779 *
1780 * @since 1.18
1781 *
1782 * @param string $addr E-mail address
1783 * @return bool
1784 */
1785 public static function validateEmail( string $addr ): bool {
1786 $result = null;
1787 // TODO This method should be non-static, and have a HookRunner injected
1788 $hookRunner = new HookRunner( MediaWikiServices::getInstance()->getHookContainer() );
1789 if ( !$hookRunner->onIsValidEmailAddr( $addr, $result ) ) {
1790 return $result;
1791 }
1792
1793 // Please note strings below are enclosed in brackets [], this make the
1794 // hyphen "-" a range indicator. Hence it is double backslashed below.
1795 // See T28948
1796 $rfc5322_atext = "a-z0-9!#$%&'*+\\-\/=?^_`{|}~";
1797 $rfc1034_ldh_str = "a-z0-9\\-";
1798
1799 $html5_email_regexp = "/
1800 ^ # start of string
1801 [$rfc5322_atext\\.]+ # user part which is liberal :p
1802 @ # 'apostrophe'
1803 [$rfc1034_ldh_str]+ # First domain part
1804 (\\.[$rfc1034_ldh_str]+)* # Following part prefixed with a dot
1805 $ # End of string
1806 /ix"; // case Insensitive, eXtended
1807
1808 return (bool)preg_match( $html5_email_regexp, $addr );
1809 }
1810 }
1811
1812 /** @deprecated class alias since 1.41 */
1813 class_alias( Sanitizer::class, 'Sanitizer' );