39 '/&([A-Za-z0-9\x80-\xff]+);
41 |&\#[xX]([0-9A-Fa-f]+);
357 if ( self::$attribsRegex ===
null ) {
358 $spaceChars =
'\x09\x0a\x0c\x0d\x20';
359 $space =
"[{$spaceChars}]";
360 $attrib =
"[^{$spaceChars}\/>=]";
361 $attribFirst =
"(?:{$attrib}|=)";
362 self::$attribsRegex =
363 "/({$attribFirst}{$attrib}*)
366 # The attribute value: quoted or alone
373 return self::$attribsRegex;
386 if ( self::$attribNameRegex ===
null ) {
387 $attribFirst =
"[:_\p{L}\p{N}]";
388 $attrib =
"[:_\.\-\p{L}\p{N}]";
389 self::$attribNameRegex =
"/^({$attribFirst}{$attrib}*)$/sxu";
391 return self::$attribNameRegex;
403 static $htmlpairsStatic, $htmlsingle, $htmlsingleonly, $htmlnest, $tabletags,
404 $htmllist, $listtags, $htmlsingleallowed, $htmlelementsStatic, $staticInitialised;
409 if ( !$staticInitialised || $staticInitialised != $globalContext ) {
410 $htmlpairsStatic = [ # Tags that must be closed
411 'b',
'bdi',
'del',
'i',
'ins',
'u',
'font',
'big',
'small',
'sub',
'sup',
'h1',
412 'h2',
'h3',
'h4',
'h5',
'h6',
'cite',
'code',
'em',
's',
413 'strike',
'strong',
'tt',
'var',
'div',
'center',
414 'blockquote',
'ol',
'ul',
'dl',
'table',
'caption',
'pre',
415 'ruby',
'rb',
'rp',
'rt',
'rtc',
'p',
'span',
'abbr',
'dfn',
416 'kbd',
'samp',
'data',
'time',
'mark'
419 'br',
'wbr',
'hr',
'li',
'dt',
'dd',
'meta',
'link'
422 # Elements that cannot have close tags. This is (not coincidentally)
423 # also the list of tags for which the HTML 5 parsing algorithm
424 # requires you to "acknowledge the token's self-closing flag", i.e.
425 # a self-closing tag like <br/> is not an HTML 5 parse error only
428 'br',
'wbr',
'hr',
'meta',
'link'
431 $htmlnest = [ # Tags that can be nested--??
432 'table',
'tr',
'td',
'th',
'div',
'blockquote',
'ol',
'ul',
433 'li',
'dl',
'dt',
'dd',
'font',
'big',
'small',
'sub',
'sup',
'span',
434 'var',
'kbd',
'samp',
'em',
'strong',
'q',
'ruby',
'bdo'
436 $tabletags = [ # Can only appear inside table, we will close them
439 $htmllist = [ # Tags used by list
442 $listtags = [ # Tags that can appear in a list
447 $htmlsingle[] =
'img';
448 $htmlsingleonly[] =
'img';
451 $htmlsingleallowed = array_unique( array_merge( $htmlsingle, $tabletags ) );
452 $htmlelementsStatic = array_unique( array_merge( $htmlsingle, $htmlpairsStatic, $htmlnest ) );
454 # Convert them all to hashtables for faster lookup
455 $vars = [
'htmlpairsStatic',
'htmlsingle',
'htmlsingleonly',
'htmlnest',
'tabletags',
456 'htmllist',
'listtags',
'htmlsingleallowed',
'htmlelementsStatic' ];
457 foreach ( $vars as $var ) {
458 $$var = array_flip( $$var );
460 $staticInitialised = $globalContext;
463 # Populate $htmlpairs and $htmlelements with the $extratags and $removetags arrays
464 $extratags = array_flip( $extratags );
465 $removetags = array_flip( $removetags );
466 $htmlpairs = array_merge( $extratags, $htmlpairsStatic );
467 $htmlelements = array_diff_key( array_merge( $extratags, $htmlelementsStatic ), $removetags );
470 'htmlpairs' => $htmlpairs,
471 'htmlsingle' => $htmlsingle,
472 'htmlsingleonly' => $htmlsingleonly,
473 'htmlnest' => $htmlnest,
474 'tabletags' => $tabletags,
475 'htmllist' => $htmllist,
476 'listtags' => $listtags,
477 'htmlsingleallowed' => $htmlsingleallowed,
478 'htmlelements' => $htmlelements,
498 $args = [], $extratags = [], $removetags = [], $warnCallback =
null
500 $tagData = self::getRecognizedTagData( $extratags, $removetags );
501 $htmlpairs = $tagData[
'htmlpairs'];
502 $htmlsingle = $tagData[
'htmlsingle'];
503 $htmlsingleonly = $tagData[
'htmlsingleonly'];
504 $htmlnest = $tagData[
'htmlnest'];
505 $tabletags = $tagData[
'tabletags'];
506 $htmllist = $tagData[
'htmllist'];
507 $listtags = $tagData[
'listtags'];
508 $htmlsingleallowed = $tagData[
'htmlsingleallowed'];
509 $htmlelements = $tagData[
'htmlelements'];
511 # Remove HTML comments
512 $text = self::removeHTMLcomments( $text );
513 $bits = explode(
'<', $text );
514 $text = str_replace(
'>',
'>', array_shift( $bits ) );
517 $tagstack = $tablestack = [];
518 foreach ( $bits as $x ) {
520 # $slash: Does the current element start with a '/'?
521 # $t: Current element name
522 # $params: String between element name and >
523 # $brace: Ending '>' or '/>'
524 # $rest: Everything until the next element of $bits
525 if ( preg_match( self::ELEMENT_BITS_REGEX, $x, $regs ) ) {
526 list( , $slash,
$t, $params, $brace, $rest ) = $regs;
528 $slash =
$t = $params = $brace = $rest =
null;
532 $t = strtolower(
$t );
533 if ( isset( $htmlelements[
$t] ) ) {
535 if ( $slash && isset( $htmlsingleonly[
$t] ) ) {
537 } elseif ( $slash ) {
538 # Closing a tag... is it the one we just opened?
539 Wikimedia\suppressWarnings();
540 $ot = array_pop( $tagstack );
541 Wikimedia\restoreWarnings();
544 if ( isset( $htmlsingleallowed[$ot] ) ) {
545 # Pop all elements with an optional close tag
546 # and see if we find a match below them
548 array_push( $optstack, $ot );
549 Wikimedia\suppressWarnings();
550 $ot = array_pop( $tagstack );
551 Wikimedia\restoreWarnings();
552 while ( $ot !=
$t && isset( $htmlsingleallowed[$ot] ) ) {
553 array_push( $optstack, $ot );
554 Wikimedia\suppressWarnings();
555 $ot = array_pop( $tagstack );
556 Wikimedia\restoreWarnings();
559 # No match. Push the optional elements back again
561 Wikimedia\suppressWarnings();
562 $ot = array_pop( $optstack );
563 Wikimedia\restoreWarnings();
565 array_push( $tagstack, $ot );
566 Wikimedia\suppressWarnings();
567 $ot = array_pop( $optstack );
568 Wikimedia\restoreWarnings();
572 Wikimedia\suppressWarnings();
573 array_push( $tagstack, $ot );
574 Wikimedia\restoreWarnings();
576 # <li> can be nested in <ul> or <ol>, skip those cases:
577 if ( !isset( $htmllist[$ot] ) || !isset( $listtags[
$t] ) ) {
581 } elseif (
$t ==
'table' ) {
582 $tagstack = array_pop( $tablestack );
586 # Keep track for later
587 if ( isset( $tabletags[
$t] ) && !in_array(
'table', $tagstack ) ) {
589 } elseif ( in_array(
$t, $tagstack ) && !isset( $htmlnest[
$t] ) ) {
591 # Is it a self closed htmlpair ? (T7487)
592 } elseif ( $brace ==
'/>' && isset( $htmlpairs[
$t] ) ) {
598 if ( is_callable( $warnCallback ) ) {
599 call_user_func_array( $warnCallback, [
'deprecated-self-close-category' ] );
602 } elseif ( isset( $htmlsingleonly[
$t] ) ) {
603 # Hack to force empty tag for unclosable elements
605 } elseif ( isset( $htmlsingle[
$t] ) ) {
606 # Hack to not close $htmlsingle tags
608 # Still need to push this optionally-closed tag to
609 # the tag stack so that we can match end tags
610 # instead of marking them as bad.
611 array_push( $tagstack,
$t );
612 } elseif ( isset( $tabletags[
$t] ) && in_array(
$t, $tagstack ) ) {
616 if (
$t ==
'table' ) {
617 array_push( $tablestack, $tagstack );
620 array_push( $tagstack,
$t );
623 # Replace any variables or template parameters with
625 if ( is_callable( $processCallback ) ) {
626 call_user_func_array( $processCallback, [ &$params,
$args ] );
629 if ( !self::validateTag( $params,
$t ) ) {
633 # Strip non-approved attributes from the tag
634 $newparams = self::fixTagAttributes( $params,
$t );
637 $rest = str_replace(
'>',
'>', $rest );
638 $close = ( $brace ==
'/>' && !$slash ) ?
' /' :
'';
639 $text .=
"<$slash$t$newparams$close>$rest";
643 $text .=
'<' . str_replace(
'>',
'>', $x );
645 # Close off any remaining tags
646 while ( is_array( $tagstack ) && (
$t = array_pop( $tagstack ) ) ) {
648 if (
$t ==
'table' ) {
649 $tagstack = array_pop( $tablestack );
653 # this might be possible using tidy itself
654 foreach ( $bits as $x ) {
655 if ( preg_match( self::ELEMENT_BITS_REGEX, $x, $regs ) ) {
656 list( , $slash,
$t, $params, $brace, $rest ) = $regs;
659 $t = strtolower(
$t );
660 if ( isset( $htmlelements[
$t] ) ) {
661 if ( is_callable( $processCallback ) ) {
662 call_user_func_array( $processCallback, [ &$params,
$args ] );
665 if ( $brace ==
'/>' && !( isset( $htmlsingle[
$t] ) || isset( $htmlsingleonly[
$t] ) ) ) {
671 if ( is_callable( $warnCallback ) ) {
672 call_user_func_array( $warnCallback, [
'deprecated-self-close-category' ] );
675 if ( !self::validateTag( $params,
$t ) ) {
679 $newparams = self::fixTagAttributes( $params,
$t );
681 if ( $brace ===
'/>' && !isset( $htmlsingleonly[
$t] ) ) {
682 # Interpret self-closing tags as empty tags even when
683 # HTML 5 would interpret them as start tags. Such input
684 # is commonly seen on Wikimedia wikis with this intention.
688 $rest = str_replace(
'>',
'>', $rest );
689 $text .=
"<$slash$t$newparams$brace$rest";
694 $text .=
'<' . str_replace(
'>',
'>', $x );
710 while ( ( $start = strpos( $text,
'<!--' ) ) !==
false ) {
711 $end = strpos( $text,
'-->', $start + 4 );
712 if ( $end ===
false ) {
713 # Unterminated comment; bail out
719 # Trim space and newline if the comment is both
720 # preceded and followed by a newline
721 $spaceStart = max( $start - 1, 0 );
722 $spaceLen = $end - $spaceStart;
723 while ( substr( $text, $spaceStart, 1 ) ===
' ' && $spaceStart > 0 ) {
727 while ( substr( $text, $spaceStart + $spaceLen, 1 ) ===
' ' ) {
730 if ( substr( $text, $spaceStart, 1 ) ===
"\n"
731 && substr( $text, $spaceStart + $spaceLen, 1 ) ===
"\n" ) {
732 # Remove the comment, leading and trailing
733 # spaces, and leave only one newline.
734 $text = substr_replace( $text,
"\n", $spaceStart, $spaceLen + 1 );
736 # Remove just the comment.
737 $text = substr_replace( $text,
'', $start, $end - $start );
756 $params = self::decodeTagAttributes( $params );
758 if ( $element ==
'meta' || $element ==
'link' ) {
759 if ( !isset( $params[
'itemprop'] ) ) {
763 if ( $element ==
'meta' && !isset( $params[
'content'] ) ) {
767 if ( $element ==
'link' && !isset( $params[
'href'] ) ) {
792 return self::validateAttributes( $attribs,
793 self::attributeWhitelistInternal( $element ) );
814 if ( isset( $whitelist[0] ) ) {
818 $whitelist = array_flip( $whitelist );
823 foreach ( $attribs as $attribute => $value ) {
824 # Allow XML namespace declaration to allow RDFa
825 if ( preg_match( self::XMLNS_ATTRIBUTE_PATTERN, $attribute ) ) {
826 if ( !preg_match( self::EVIL_URI_PATTERN, $value ) ) {
827 $out[$attribute] = $value;
833 # Allow any attribute beginning with "data-"
835 # * Disallow data attributes used by MediaWiki code
836 # * Ensure that the attribute is not namespaced by banning
839 !preg_match(
'/^data-[^:]*$/i', $attribute ) &&
840 !array_key_exists( $attribute, $whitelist )
841 ) || self::isReservedDataAttribute( $attribute ) ) {
845 # Strip javascript "expression" from stylesheets.
847 if ( $attribute ==
'style' ) {
848 $value = self::checkCss( $value );
851 # Escape HTML id attributes
852 if ( $attribute ===
'id' ) {
853 $value = self::escapeIdForAttribute( $value, self::ID_PRIMARY );
856 # Escape HTML id reference lists
857 if ( $attribute ===
'aria-describedby'
858 || $attribute ===
'aria-flowto'
859 || $attribute ===
'aria-labelledby'
860 || $attribute ===
'aria-owns'
862 $value = self::escapeIdReferenceList( $value );
867 if ( $attribute ===
'rel' || $attribute ===
'rev'
869 || $attribute ===
'about' || $attribute ===
'property'
870 || $attribute ===
'resource' || $attribute ===
'datatype'
871 || $attribute ===
'typeof'
873 || $attribute ===
'itemid' || $attribute ===
'itemprop'
874 || $attribute ===
'itemref' || $attribute ===
'itemscope'
875 || $attribute ===
'itemtype'
878 if ( preg_match( self::EVIL_URI_PATTERN, $value ) ) {
883 # NOTE: even though elements using href/src are not allowed directly, supply
884 # validation code that can be used by tag hook handlers, etc
885 if ( $attribute ===
'href' || $attribute ===
'src' || $attribute ===
'poster' ) {
886 if ( !preg_match( $hrefExp, $value ) ) {
894 $out[$attribute] = $value;
897 # itemtype, itemid, itemref don't make sense without itemscope
898 if ( !array_key_exists(
'itemscope', $out ) ) {
899 unset( $out[
'itemtype'] );
900 unset( $out[
'itemid'] );
901 unset( $out[
'itemref'] );
903 # TODO: Strip itemprop if we aren't descendants of an itemscope or pointed to by an itemref.
923 return (
bool)preg_match(
'/^data-(ooui|mw|parsoid)/i', $attr );
937 $out = array_merge( $a, $b );
938 if ( isset( $a[
'class'] ) && isset( $b[
'class'] )
939 && is_string( $a[
'class'] ) && is_string( $b[
'class'] )
940 && $a[
'class'] !== $b[
'class']
942 $classes = preg_split(
'/\s+/',
"{$a['class']} {$b['class']}",
943 -1, PREG_SPLIT_NO_EMPTY );
944 $out[
'class'] = implode(
' ', array_unique( $classes ) );
960 $value = self::decodeCharReferences( $value );
972 if ( !$decodeRegex ) {
973 $space =
'[\\x20\\t\\r\\n\\f]';
974 $nl =
'(?:\\n|\\r\\n|\\r|\\f)';
976 $decodeRegex =
"/ $backslash
978 ($nl) | # 1. Line continuation
979 ([0-9A-Fa-f]{1,6})$space? | # 2. character number
980 (.) | # 3. backslash cancelling special meaning
981 () | # 4. backslash at end of string
984 $value = preg_replace_callback( $decodeRegex,
985 [ __CLASS__,
'cssDecodeCallback' ], $value );
988 $value = preg_replace_callback(
991 $cp = UtfNormal\Utils::utf8ToCodepoint(
$matches[0] );
992 if ( $cp ===
false ) {
995 return chr( $cp - 65248 );
1002 $value = str_replace(
1003 [
'ʀ',
'ɴ',
'ⁿ',
'ʟ',
'ɪ',
'⁽',
'₍' ],
1004 [
'r',
'n',
'n',
'l',
'i',
'(',
'(' ],
1011 if ( !preg_match(
'! ^ \s* /\* [^*\\/]* \*/ \s* $ !x', $value ) ) {
1022 $commentPos = strpos( $value,
'/*' );
1023 if ( $commentPos !==
false ) {
1024 $value = substr( $value, 0, $commentPos );
1030 $value = preg_replace(
1032 \xE3\x80\xB1 | # U+3031
1033 \xE3\x82\x9D | # U+309D
1034 \xE3\x83\xBC | # U+30FC
1035 \xE3\x83\xBD | # U+30FD
1036 \xEF\xB9\xBC | # U+FE7C
1037 \xEF\xB9\xBD | # U+FE7D
1038 \xEF\xBD\xB0 # U+FF70
1066 $value = self::normalizeCss( $value );
1069 if ( preg_match(
'/[\000-\010\013\016-\037\177]/', $value ) ||
1070 strpos( $value, UtfNormal\Constants::UTF8_REPLACEMENT ) !==
false ) {
1071 return '/* invalid control char */';
1072 } elseif ( preg_match(
1077 | -o-link-source\s*:
1082 | attr\s*\([^)]+[\s,]+url
1085 return '/* insecure input */';
1099 $char = UtfNormal\Utils::codepointToUtf8( hexdec(
$matches[2] ) );
1105 if ( $char ==
"\n" || $char ==
'"' || $char ==
"'" || $char ==
'\\' ) {
1108 return '\\' . dechex( ord( $char ) ) .
' ';
1137 if ( trim( $text ) ==
'' ) {
1141 $decoded = self::decodeTagAttributes( $text );
1142 $stripped = self::validateTagAttributes( $decoded, $element );
1148 return self::safeEncodeTagAttributes( $stripped );
1157 $encValue = htmlspecialchars( $text, ENT_QUOTES );
1162 $encValue = strtr( $encValue, [
1183 # French spaces, last one Guillemet-left
1184 # only if there is something before the space
1185 # and a non-word character after the punctuation.
1186 '/(\S) (?=[?:;!%»›](?!\w))/u' =>
"\\1$space",
1187 # French spaces, Guillemet-right
1188 '/([«‹]) /u' =>
"\\1$space",
1190 return preg_replace( array_keys( $fixtags ), array_values( $fixtags ), $text );
1200 $encValue = self::encodeAttribute( $text );
1202 # Templates and links may be expanded in later parsing,
1203 # creating invalid or dangerous output. Suppress this.
1204 $encValue = strtr( $encValue, [
1212 "''" =>
'''',
1213 'ISBN' =>
'ISBN',
1215 'PMID' =>
'PMID',
1220 # Armor against French spaces detection (T5158)
1221 $encValue = self::armorFrenchSpaces( $encValue,
' ' );
1224 $encValue = preg_replace_callback(
1227 return str_replace(
':',
':',
$matches[1] );
1262 $options = (array)$options;
1270 $id = urlencode( strtr( $id,
' ',
'_' ) );
1271 $id = strtr( $id, $replace );
1273 if ( !preg_match(
'/^[a-zA-Z]/', $id ) && !in_array(
'noninitial', $options ) ) {
1299 if ( $mode === self::ID_PRIMARY ) {
1300 throw new UnexpectedValueException(
'$wgFragmentMode is configured with no primary mode' );
1307 return self::escapeIdInternal( $id, $internalMode );
1326 throw new UnexpectedValueException(
'$wgFragmentMode is configured with no primary mode' );
1331 $id = self::escapeIdInternal( $id, $mode );
1363 $id = mb_substr( $id, 0, 1024 );
1367 $id = str_replace(
' ',
'_', $id );
1376 $id = urlencode( str_replace(
' ',
'_', $id ) );
1377 $id = strtr( $id, $replace );
1380 throw new InvalidArgumentException(
"Invalid mode '$mode' passed to '" . __METHOD__ );
1396 # Explode the space delimited list string into an array of tokens
1397 $references = preg_split(
'/\s+/',
"{$referenceString}", -1, PREG_SPLIT_NO_EMPTY );
1399 # Escape each token as an id
1400 foreach ( $references as &$ref ) {
1401 $ref = self::escapeIdForAttribute( $ref );
1404 # Merge the array back to a space delimited list string
1405 # If the array is empty, the result will be an empty string ('')
1406 $referenceString = implode(
' ', $references );
1408 return $referenceString;
1424 return rtrim( preg_replace(
1425 [
'/(^[0-9\\-])|[\\x00-\\x20!"#$%&\'()*+,.\\/:;<=>?@[\\]^`{|}~]|\\xC2\\xA0/',
'/_+/' ],
1438 $html = self::decodeCharReferences( $html );
1439 # It seems wise to escape ' as well as ", as a matter of course. Can't
1440 # hurt. Use ENT_SUBSTITUTE so that incorrectly truncated multibyte characters
1441 # don't cause the entire string to disappear.
1442 $html = htmlspecialchars( $html, ENT_QUOTES | ENT_SUBSTITUTE );
1454 public static function decodeTagAttributes( $text ) {
1455 if ( trim( $text ) == '' ) {
1460 if ( !preg_match_all(
1461 self::getAttribsRegex(),
1464 PREG_SET_ORDER ) ) {
1469 foreach ( $pairs as $set ) {
1470 $attribute = strtolower( $set[1] );
1472 // Filter attribute names with unacceptable characters
1473 if ( !preg_match( self::getAttribNameRegex(), $attribute ) ) {
1477 $value = self::getTagAttributeCallback( $set );
1479 // Normalize whitespace
1480 $value = preg_replace( '/[\t\r\n ]+/', ' ', $value );
1481 $value = trim( $value );
1483 // Decode character references
1484 $attribs[$attribute] = self::decodeCharReferences( $value );
1496 public static function safeEncodeTagAttributes( $assoc_array ) {
1498 foreach ( $assoc_array as $attribute => $value ) {
1499 $encAttribute = htmlspecialchars( $attribute );
1500 $encValue = self::safeEncodeAttribute( $value );
1502 $attribs[] = "$encAttribute=\"$encValue\"";
1504 return count( $attribs ) ?
' ' . implode(
' ', $attribs ) :
'';
1516 if ( isset( $set[5] ) ) {
1519 } elseif ( isset( $set[4] ) ) {
1522 } elseif ( isset( $set[3] ) ) {
1525 } elseif ( !isset( $set[2] ) ) {
1526 # In XHTML, attributes must have a value so return an empty string.
1527 # See "Empty attribute syntax",
1531 throw new MWException(
"Tag conditions not met. This should never happen and is a bug." );
1540 return trim( preg_replace(
1541 '/(?:\r\n|[\x20\x0d\x0a\x09])+/',
1555 return trim( preg_replace(
'/[ _]+/',
' ', $section ) );
1574 return preg_replace_callback(
1575 self::CHAR_REFS_REGEX,
1576 [ self::class,
'normalizeCharReferencesCallback' ],
1587 $ret = self::normalizeEntity(
$matches[1] );
1589 $ret = self::decCharReference(
$matches[2] );
1591 $ret = self::hexCharReference(
$matches[3] );
1593 if ( is_null( $ret ) ) {
1594 return htmlspecialchars(
$matches[0] );
1611 if ( isset( self::$htmlEntityAliases[$name] ) ) {
1612 return '&' . self::$htmlEntityAliases[$name] .
';';
1613 } elseif ( in_array( $name, [
'lt',
'gt',
'amp',
'quot' ] ) ) {
1615 } elseif ( isset( self::$htmlEntities[$name] ) ) {
1616 return '&#' . self::$htmlEntities[$name] .
';';
1618 return "&$name;";
1627 $point = intval( $codepoint );
1628 if ( self::validateCodepoint( $point ) ) {
1629 return sprintf(
'&#%d;', $point );
1640 $point = hexdec( $codepoint );
1641 if ( self::validateCodepoint( $point ) ) {
1642 return sprintf(
'&#x%x;', $point );
1655 # U+000C is valid in HTML5 but not allowed in XML.
1656 # U+000D is valid in XML but not allowed in HTML5.
1657 # U+007F - U+009F are disallowed in HTML5 (control characters).
1658 return $codepoint == 0x09
1659 || $codepoint == 0x0a
1660 || ( $codepoint >= 0x20 && $codepoint <= 0x7e )
1661 || ( $codepoint >= 0xa0 && $codepoint <= 0xd7ff )
1662 || ( $codepoint >= 0xe000 && $codepoint <= 0xfffd )
1663 || ( $codepoint >= 0x10000 && $codepoint <= 0x10ffff );
1674 return preg_replace_callback(
1675 self::CHAR_REFS_REGEX,
1676 [ self::class,
'decodeCharReferencesCallback' ],
1691 $text = preg_replace_callback(
1692 self::CHAR_REFS_REGEX,
1693 [ self::class,
'decodeCharReferencesCallback' ],
1700 return MediaWikiServices::getInstance()->getContentLanguage()->normalize( $text );
1712 return self::decodeEntity(
$matches[1] );
1714 return self::decodeChar( intval(
$matches[2] ) );
1716 return self::decodeChar( hexdec(
$matches[3] ) );
1718 # Last case should be an ampersand by itself
1730 if ( self::validateCodepoint( $codepoint ) ) {
1731 return UtfNormal\Utils::codepointToUtf8( $codepoint );
1733 return UtfNormal\Constants::UTF8_REPLACEMENT;
1746 if ( isset( self::$htmlEntityAliases[$name] ) ) {
1747 $name = self::$htmlEntityAliases[$name];
1749 if ( isset( self::$htmlEntities[$name] ) ) {
1750 return UtfNormal\Utils::codepointToUtf8( self::$htmlEntities[$name] );
1765 $list = self::setupAttributeWhitelist();
1766 return $list[$element] ?? [];
1777 $list = self::setupAttributeWhitelistInternal();
1778 return $list[$element] ?? [];
1789 $wlist = self::setupAttributeWhitelistInternal();
1792 return array_map(
function ( $v ) {
1793 return array_keys( $v );
1807 if ( $whitelist !==
null ) {
1813 $merge =
function ( $a, $b, $c = [] ) {
1814 return array_merge( $a, array_flip( $b ), array_flip( $c ) );
1816 $common = $merge( [], [
1834 # These attributes are specified in section 9 of
1842 # Microdata. These are specified by
1851 $block = $merge( $common, [
'align' ] );
1853 $tablealign = [
'align',
'valign' ];
1861 'nowrap', # deprecated
1862 'width', # deprecated
1863 'height', # deprecated
1864 'bgcolor', # deprecated
1867 # Numbers refer to sections in HTML 4.01 standard describing the element.
1872 'center' => $common, # deprecated
1891 'strong' => $common,
1902 'blockquote' => $merge( $common, [
'cite' ] ),
1903 'q' => $merge( $common, [
'cite' ] ),
1913 'br' => $merge( $common, [
'clear' ] ),
1919 'pre' => $merge( $common, [
'width' ] ),
1922 'ins' => $merge( $common, [
'cite',
'datetime' ] ),
1923 'del' => $merge( $common, [
'cite',
'datetime' ] ),
1926 'ul' => $merge( $common, [
'type' ] ),
1927 'ol' => $merge( $common, [
'type',
'start',
'reversed' ] ),
1928 'li' => $merge( $common, [
'type',
'value' ] ),
1936 'table' => $merge( $common,
1937 [
'summary',
'width',
'border',
'frame',
1938 'rules',
'cellspacing',
'cellpadding',
1943 'caption' => $block,
1951 'colgroup' => $merge( $common, [
'span' ] ),
1952 'col' => $merge( $common, [
'span' ] ),
1955 'tr' => $merge( $common, [
'bgcolor' ], $tablealign ),
1958 'td' => $merge( $common, $tablecell, $tablealign ),
1959 'th' => $merge( $common, $tablecell, $tablealign ),
1962 # NOTE: <a> is not allowed directly, but the attrib
1963 # whitelist is used from the Parser object
1964 'a' => $merge( $common, [
'href',
'rel',
'rev' ] ), # rel/rev esp.
for RDFa
1967 # Not usually allowed, but may be used for extension-style hooks
1968 # such as <math> when it is rasterized, or if $wgAllowImageTag is
1970 'img' => $merge( $common, [
'alt',
'src',
'width',
'height',
'srcset' ] ),
1971 # Attributes for A/V tags added in T163583 / T133673
1972 'audio' => $merge( $common, [
'controls',
'preload',
'width',
'height' ] ),
1973 'video' => $merge( $common, [
'poster',
'controls',
'preload',
'width',
'height' ] ),
1974 'source' => $merge( $common, [
'type',
'src' ] ),
1975 'track' => $merge( $common, [
'type',
'src',
'srclang',
'kind',
'label' ] ),
1983 'strike' => $common,
1988 'font' => $merge( $common, [
'size',
'color',
'face' ] ),
1992 'hr' => $merge( $common, [
'width' ] ),
1994 # HTML Ruby annotation text module, simple ruby only.
2000 'rt' => $common, # $merge( $common, [
'rbspan' ] ),
2003 # MathML root element, where used for extensions
2004 # 'title' may not be 100% valid here; it's XHTML
2006 'math' => $merge( [], [
'class',
'style',
'id',
'title' ] ),
2009 'figure' => $common,
2010 'figure-inline' => $common, # T118520
2011 'figcaption' => $common,
2013 # HTML 5 section 4.6
2016 # HTML5 elements, defined by:
2018 'data' => $merge( $common, [
'value' ] ),
2019 'time' => $merge( $common, [
'datetime' ] ),
2027 'meta' => $merge( [], [
'itemprop',
'content' ] ),
2028 'link' => $merge( [], [
'itemprop',
'href',
'title' ] ),
2048 $tokenizer =
new RemexHtml\Tokenizer\Tokenizer( $handler, $html, [
2049 'ignoreErrors' =>
true,
2051 'ignoreNulls' =>
true,
2052 'skipPreprocess' =>
true,
2054 $tokenizer->execute();
2055 $text = $handler->getResult();
2057 $text = self::normalizeWhitespace( $text );
2071 $out =
"<!DOCTYPE html [\n";
2072 foreach ( self::$htmlEntities as $entity => $codepoint ) {
2073 $out .=
"<!ENTITY $entity \"&#$codepoint;\">";
2084 # Normalize any HTML entities in input. They will be
2085 # re-escaped by makeExternalLink().
2086 $url = self::decodeCharReferences( $url );
2088 # Escape any control characters introduced by the above step
2089 $url = preg_replace_callback(
'/[\][<>"\\x00-\\x20\\x7F\|]/',
2090 [ __CLASS__,
'cleanUrlCallback' ], $url );
2092 # Validate hostname portion
2094 if ( preg_match(
'!^([^:]+:)(//[^/]+)?(.*)$!iD', $url,
$matches ) ) {
2095 list( , $protocol, $host, $rest ) =
$matches;
2101 \\s| # general whitespace
2102 \xc2\xad| # 00ad SOFT HYPHEN
2103 \xe1\xa0\x86| # 1806 MONGOLIAN TODO SOFT HYPHEN
2104 \xe2\x80\x8b| # 200b ZERO WIDTH SPACE
2105 \xe2\x81\xa0| # 2060 WORD JOINER
2106 \xef\xbb\xbf| # feff ZERO WIDTH NO-BREAK SPACE
2107 \xcd\x8f| # 034f COMBINING GRAPHEME JOINER
2108 \xe1\xa0\x8b| # 180b MONGOLIAN FREE VARIATION SELECTOR ONE
2109 \xe1\xa0\x8c| # 180c MONGOLIAN FREE VARIATION SELECTOR TWO
2110 \xe1\xa0\x8d| # 180d MONGOLIAN FREE VARIATION SELECTOR THREE
2111 \xe2\x80\x8c| # 200c ZERO WIDTH NON-JOINER
2112 \xe2\x80\x8d| # 200d ZERO WIDTH JOINER
2113 [\xef\xb8\x80-\xef\xb8\x8f] # fe00-fe0f VARIATION SELECTOR-1-16
2116 $host = preg_replace( $strip,
'', $host );
2119 if ( substr_compare(
"//%5B", $host, 0, 5 ) === 0 &&
2120 preg_match(
'!^//%5B([0-9A-Fa-f:.]+)%5D((:\d+)?)$!', $host,
$matches )
2127 return $protocol . $host . $rest;
2171 if ( !Hooks::run(
'isValidEmailAddr', [ $addr, &$result ] ) ) {
2178 $rfc5322_atext =
"a-z0-9!#$%&'*+\\-\/=?^_`{|}~";
2179 $rfc1034_ldh_str =
"a-z0-9\\-";
2181 $html5_email_regexp =
"/
2183 [$rfc5322_atext\\.]+ # user part which is liberal :p
2185 [$rfc1034_ldh_str]+ # First domain part
2186 (\\.[$rfc1034_ldh_str]+)* # Following part prefixed with a dot
2190 return (
bool)preg_match( $html5_email_regexp, $addr );
$wgAllowImageTag
A different approach to the above: simply allow the "<img>" tag to be used.
$wgFragmentMode
How should section IDs be encoded? This array can contain 1 or 2 elements, each of them can be one of...
$wgExternalInterwikiFragmentMode
Which ID escaping mode should be used for external interwiki links? See documentation for $wgFragment...
wfUrlProtocols( $includeProtocolRelative=true)
Returns a regular expression of url protocols.
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Throws a warning that $function is deprecated.
HTML sanitizer for MediaWiki.
static fixTagAttributes( $text, $element, $sorted=false)
Take a tag soup fragment listing an HTML element's attributes and normalize it to well-formed XML,...
static attributeWhitelistInternal( $element)
Fetch the whitelist of acceptable attributes for a given element name.
const CHAR_REFS_REGEX
Regular expression to match various types of character references in Sanitizer::normalizeCharReferenc...
static validateAttributes( $attribs, $whitelist)
Take an array of attribute names and values and normalize or discard illegal values for the given whi...
static decCharReference( $codepoint)
static isReservedDataAttribute( $attr)
Given an attribute name, checks whether it is a reserved data attribute (such as data-mw-foo) which i...
static decodeChar( $codepoint)
Return UTF-8 string for a codepoint if that is a valid character reference, otherwise U+FFFD REPLACEM...
static escapeHtmlAllowEntities( $html)
Given HTML input, escape with htmlspecialchars but un-escape entities.
static getAttribNameRegex()
Used in Sanitizer::decodeTagAttributes to filter attributes.
static checkCss( $value)
Pick apart some CSS and check it for forbidden or unsafe structures.
static decodeEntity( $name)
If the named entity is defined in the HTML 4.0/XHTML 1.0 DTD, return the UTF-8 encoding of that chara...
static normalizeEntity( $name)
If the named entity is defined in the HTML 4.0/XHTML 1.0 DTD, return the equivalent numeric entity re...
static armorFrenchSpaces( $text, $space=' ')
Armor French spaces with a replacement character.
static getRecognizedTagData( $extratags=[], $removetags=[])
Return the various lists of recognized tags.
static $attribsRegex
Lazy-initialised attributes regex, see getAttribsRegex()
static escapeIdForLink( $id)
Given a section name or other user-generated or otherwise unsafe string, escapes it to be a valid URL...
static setupAttributeWhitelistInternal()
Foreach array key (an allowed HTML element), return an array of allowed attributes.
static removeHTMLcomments( $text)
Remove '', and everything between.
static encodeAttribute( $text)
Encode an attribute value for HTML output.
static hexCharReference( $codepoint)
static validateTagAttributes( $attribs, $element)
Take an array of attribute names and values and normalize or discard illegal values for the given ele...
static escapeClass( $class)
Given a value, escape it so that it can be used as a CSS class and return it.
const EVIL_URI_PATTERN
Blacklist for evil uris like javascript: WARNING: DO NOT use this in any place that actually requires...
static normalizeSectionNameWhitespace( $section)
Normalizes whitespace in a section name, such as might be returned by Parser::stripSectionName(),...
static setupAttributeWhitelist()
Foreach array key (an allowed HTML element), return an array of allowed attributes.
static normalizeCharReferencesCallback( $matches)
static hackDocType()
Hack up a private DOCTYPE with HTML's standard entity declarations.
static cleanUrlCallback( $matches)
static normalizeCharReferences( $text)
Ensure that any entities and character references are legal for XML and XHTML specifically.
static cssDecodeCallback( $matches)
static escapeIdReferenceList( $referenceString)
Given a string containing a space delimited list of ids, escape each id to match ids escaped by the e...
static normalizeWhitespace( $text)
static removeHTMLtags( $text, $processCallback=null, $args=[], $extratags=[], $removetags=[], $warnCallback=null)
Cleans up HTML, removes dangerous tags and attributes, and removes HTML comments.
static getAttribsRegex()
Regular expression to match HTML/XML attribute pairs within a tag.
static validateCodepoint( $codepoint)
Returns true if a given Unicode codepoint is a valid character in both HTML5 and XML.
const ID_FALLBACK
Tells escapeUrlForHtml() to encode the ID using the fallback encoding, or return false if no fallback...
static $htmlEntities
List of all named character entities defined in HTML 4.01 https://www.w3.org/TR/html4/sgml/entities....
static decodeCharReferences( $text)
Decode any character references, numeric or named entities, in the text and return a UTF-8 string.
static escapeIdForAttribute( $id, $mode=self::ID_PRIMARY)
Given a section name or other user-generated or otherwise unsafe string, escapes it to be a valid HTM...
static $attribNameRegex
Lazy-initialised attribute name regex, see getAttribNameRegex()
static getTagAttributeCallback( $set)
Pick the appropriate attribute value from a match set from the attribs regex matches.
static escapeIdInternal( $id, $mode)
Helper for escapeIdFor*() functions.
static validateTag( $params, $element)
Takes attribute names and values for a tag and the tag name and validates that the tag is allowed to ...
static stripAllTags( $html)
Take a fragment of (potentially invalid) HTML and return a version with any tags removed,...
static decodeCharReferencesAndNormalize( $text)
Decode any character references, numeric or named entities, in the next and normalize the resulting s...
static $htmlEntityAliases
Character entity aliases accepted by MediaWiki.
static escapeId( $id, $options=[])
Given a value, escape it so that it can be used in an id attribute and return it.
static attributeWhitelist( $element)
Fetch the whitelist of acceptable attributes for a given element name.
static decodeCharReferencesCallback( $matches)
static mergeAttributes( $a, $b)
Merge two sets of HTML attributes.
static escapeIdForExternalInterwiki( $id)
Given a section name or other user-generated or otherwise unsafe string, escapes it to be a valid URL...
static validateEmail( $addr)
Does a string look like an e-mail address?
const ID_PRIMARY
Tells escapeUrlForHtml() to encode the ID using the wiki's primary encoding.
const ELEMENT_BITS_REGEX
Acceptable tag name charset from HTML5 parsing spec https://www.w3.org/TR/html5/syntax....
static safeEncodeAttribute( $text)
Encode an attribute value for HTML tags, with extra armoring against further wiki processing.
const XMLNS_ATTRIBUTE_PATTERN
static normalizeCss( $value)
Normalize CSS into a format we can easily search for hostile input.
static delimiterReplace( $startDelim, $endDelim, $replace, $subject, $flags='')
Perform an operation equivalent to preg_replace() with flags.