38 const CHAR_REFS_REGEX =
39 '/&([A-Za-z0-9\x80-\xff]+);
41 |&\#[xX]([0-9A-Fa-f]+);
48 const ELEMENT_BITS_REGEX =
'!^(/?)([A-Za-z][^\t\n\v />\0]*+)([^>]*?)(/?>)([^<]*)$!';
58 const EVIL_URI_PATTERN =
'!(^|\s|\*/\s*)(javascript|vbscript)([^\w]|$)!i';
59 const XMLNS_ATTRIBUTE_PATTERN =
"/^xmlns:[:A-Z_a-z-.0-9]+$/";
74 const ID_FALLBACK = 1;
81 private static $htmlEntities = [
340 private static $htmlEntityAliases = [
348 private static $attribsRegex;
356 static function getAttribsRegex() {
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;
379 private static $attribNameRegex;
385 static function getAttribNameRegex() {
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;
400 public static function getRecognizedTagData( $extratags = [], $removetags = [] ) {
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,
497 public static function removeHTMLtags( $text, $processCallback =
null,
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 );
709 public static function removeHTMLcomments( $text ) {
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 );
755 static function validateTag( $params, $element ) {
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'] ) ) {
791 static function validateTagAttributes( $attribs, $element ) {
792 return self::validateAttributes( $attribs,
793 self::attributeWhitelistInternal( $element ) );
813 static function validateAttributes( $attribs, $whitelist ) {
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.
846 # https://msdn.microsoft.com/en-us/library/ms537634.aspx
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.
915 public static function isReservedDataAttribute( $attr ) {
923 return (
bool)preg_match(
'/^data-(ooui|mw|parsoid)/i', $attr );
936 static function mergeAttributes( $a, $b ) {
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 ) );
958 public static function normalizeCss( $value ) {
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
1065 static function checkCss( $value ) {
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 */';
1094 static function cssDecodeCallback(
$matches ) {
1099 $char = UtfNormal\Utils::codepointToUtf8( hexdec(
$matches[2] ) );
1105 if ( $char ==
"\n" || $char ==
'"' || $char ==
"'" || $char ==
'\\' ) {
1108 return '\\' . dechex( ord( $char ) ) .
' ';
1136 static function fixTagAttributes( $text, $element, $sorted =
false ) {
1137 if ( trim( $text ) ==
'' ) {
1141 $decoded = self::decodeTagAttributes( $text );
1142 $stripped = self::validateTagAttributes( $decoded, $element );
1148 return self::safeEncodeTagAttributes( $stripped );
1156 static function encodeAttribute( $text ) {
1157 $encValue = htmlspecialchars( $text, ENT_QUOTES );
1162 $encValue = strtr( $encValue, [
1179 public static function armorFrenchSpaces( $text, $space =
' ' ) {
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 );
1199 static function safeEncodeAttribute( $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] );
1261 static function escapeId( $id, $options = [] ) {
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 ) ) {
1295 public static function escapeIdForAttribute( $id, $mode = self::ID_PRIMARY ) {
1299 if ( $mode === self::ID_PRIMARY ) {
1300 throw new UnexpectedValueException(
'$wgFragmentMode is configured with no primary mode' );
1307 return self::escapeIdInternal( $id, $internalMode );
1322 public static function escapeIdForLink( $id ) {
1326 throw new UnexpectedValueException(
'$wgFragmentMode is configured with no primary mode' );
1331 $id = self::escapeIdInternal( $id, $mode );
1345 public static function escapeIdForExternalInterwiki( $id ) {
1360 private static function escapeIdInternal( $id, $mode ) {
1363 $id = str_replace(
' ',
'_', $id );
1372 $id = urlencode( str_replace(
' ',
'_', $id ) );
1373 $id = strtr( $id, $replace );
1376 throw new InvalidArgumentException(
"Invalid mode '$mode' passed to '" . __METHOD__ );
1391 public static function escapeIdReferenceList( $referenceString ) {
1392 # Explode the space delimited list string into an array of tokens
1393 $references = preg_split(
'/\s+/',
"{$referenceString}", -1, PREG_SPLIT_NO_EMPTY );
1395 # Escape each token as an id
1396 foreach ( $references as &$ref ) {
1397 $ref = self::escapeIdForAttribute( $ref );
1400 # Merge the array back to a space delimited list string
1401 # If the array is empty, the result will be an empty string ('')
1402 $referenceString = implode(
' ', $references );
1404 return $referenceString;
1418 static function escapeClass( $class ) {
1420 return rtrim( preg_replace(
1421 [
'/(^[0-9\\-])|[\\x00-\\x20!"#$%&\'()*+,.\\/:;<=>?@[\\]^`{|}~]|\\xC2\\xA0/',
'/_+/' ],
1433 static function escapeHtmlAllowEntities( $html ) {
1434 $html = self::decodeCharReferences( $html );
1435 # It seems wise to escape ' as well as ", as a matter of course. Can't
1436 # hurt. Use ENT_SUBSTITUTE so that incorrectly truncated multibyte characters
1437 # don't cause the entire string to disappear.
1438 $html = htmlspecialchars( $html, ENT_QUOTES | ENT_SUBSTITUTE );
1450 public static function decodeTagAttributes( $text ) {
1451 if ( trim( $text ) ==
'' ) {
1456 if ( !preg_match_all(
1457 self::getAttribsRegex(),
1460 PREG_SET_ORDER ) ) {
1465 foreach ( $pairs as $set ) {
1466 $attribute = strtolower( $set[1] );
1469 if ( !preg_match( self::getAttribNameRegex(), $attribute ) ) {
1473 $value = self::getTagAttributeCallback( $set );
1476 $value = preg_replace(
'/[\t\r\n ]+/',
' ', $value );
1477 $value = trim( $value );
1480 $attribs[$attribute] = self::decodeCharReferences( $value );
1492 public static function safeEncodeTagAttributes( $assoc_array ) {
1494 foreach ( $assoc_array as $attribute => $value ) {
1495 $encAttribute = htmlspecialchars( $attribute );
1496 $encValue = self::safeEncodeAttribute( $value );
1498 $attribs[] =
"$encAttribute=\"$encValue\"";
1500 return count( $attribs ) ?
' ' . implode(
' ', $attribs ) :
'';
1511 private static function getTagAttributeCallback( $set ) {
1512 if ( isset( $set[5] ) ) {
1515 } elseif ( isset( $set[4] ) ) {
1518 } elseif ( isset( $set[3] ) ) {
1521 } elseif ( !isset( $set[2] ) ) {
1522 # In XHTML, attributes must have a value so return an empty string.
1523 # See "Empty attribute syntax",
1524 # https://www.w3.org/TR/html5/syntax.html#syntax-attribute-name
1527 throw new MWException(
"Tag conditions not met. This should never happen and is a bug." );
1535 private static function normalizeWhitespace( $text ) {
1536 return trim( preg_replace(
1537 '/(?:\r\n|[\x20\x0d\x0a\x09])+/',
1550 static function normalizeSectionNameWhitespace( $section ) {
1551 return trim( preg_replace(
'/[ _]+/',
' ', $section ) );
1569 static function normalizeCharReferences( $text ) {
1570 return preg_replace_callback(
1571 self::CHAR_REFS_REGEX,
1572 [ self::class,
'normalizeCharReferencesCallback' ],
1580 static function normalizeCharReferencesCallback(
$matches ) {
1583 $ret = self::normalizeEntity(
$matches[1] );
1585 $ret = self::decCharReference(
$matches[2] );
1587 $ret = self::hexCharReference(
$matches[3] );
1589 if ( is_null( $ret ) ) {
1590 return htmlspecialchars(
$matches[0] );
1606 static function normalizeEntity( $name ) {
1607 if ( isset( self::$htmlEntityAliases[$name] ) ) {
1608 return '&' . self::$htmlEntityAliases[$name] .
';';
1609 } elseif ( in_array( $name, [
'lt',
'gt',
'amp',
'quot' ] ) ) {
1611 } elseif ( isset( self::$htmlEntities[$name] ) ) {
1612 return '&#' . self::$htmlEntities[$name] .
';';
1614 return "&$name;";
1622 static function decCharReference( $codepoint ) {
1623 $point = intval( $codepoint );
1624 if ( self::validateCodepoint( $point ) ) {
1625 return sprintf(
'&#%d;', $point );
1635 static function hexCharReference( $codepoint ) {
1636 $point = hexdec( $codepoint );
1637 if ( self::validateCodepoint( $point ) ) {
1638 return sprintf(
'&#x%x;', $point );
1650 private static function validateCodepoint( $codepoint ) {
1651 # U+000C is valid in HTML5 but not allowed in XML.
1652 # U+000D is valid in XML but not allowed in HTML5.
1653 # U+007F - U+009F are disallowed in HTML5 (control characters).
1654 return $codepoint == 0x09
1655 || $codepoint == 0x0a
1656 || ( $codepoint >= 0x20 && $codepoint <= 0x7e )
1657 || ( $codepoint >= 0xa0 && $codepoint <= 0xd7ff )
1658 || ( $codepoint >= 0xe000 && $codepoint <= 0xfffd )
1659 || ( $codepoint >= 0x10000 && $codepoint <= 0x10ffff );
1669 public static function decodeCharReferences( $text ) {
1670 return preg_replace_callback(
1671 self::CHAR_REFS_REGEX,
1672 [ self::class,
'decodeCharReferencesCallback' ],
1686 public static function decodeCharReferencesAndNormalize( $text ) {
1687 $text = preg_replace_callback(
1688 self::CHAR_REFS_REGEX,
1689 [ self::class,
'decodeCharReferencesCallback' ],
1696 return MediaWikiServices::getInstance()->getContentLanguage()->normalize( $text );
1706 static function decodeCharReferencesCallback(
$matches ) {
1708 return self::decodeEntity(
$matches[1] );
1710 return self::decodeChar( intval(
$matches[2] ) );
1712 return self::decodeChar( hexdec(
$matches[3] ) );
1714 # Last case should be an ampersand by itself
1725 static function decodeChar( $codepoint ) {
1726 if ( self::validateCodepoint( $codepoint ) ) {
1727 return UtfNormal\Utils::codepointToUtf8( $codepoint );
1729 return UtfNormal\Constants::UTF8_REPLACEMENT;
1741 static function decodeEntity( $name ) {
1742 if ( isset( self::$htmlEntityAliases[$name] ) ) {
1743 $name = self::$htmlEntityAliases[$name];
1745 if ( isset( self::$htmlEntities[$name] ) ) {
1746 return UtfNormal\Utils::codepointToUtf8( self::$htmlEntities[$name] );
1759 static function attributeWhitelist( $element ) {
1761 $list = self::setupAttributeWhitelist();
1762 return $list[$element] ?? [];
1772 private static function attributeWhitelistInternal( $element ) {
1773 $list = self::setupAttributeWhitelistInternal();
1774 return $list[$element] ?? [];
1783 static function setupAttributeWhitelist() {
1785 $wlist = self::setupAttributeWhitelistInternal();
1788 return array_map(
function ( $v ) {
1789 return array_keys( $v );
1800 private static function setupAttributeWhitelistInternal() {
1803 if ( $whitelist !==
null ) {
1809 $merge =
function ( $a, $b, $c = [] ) {
1810 return array_merge( $a, array_flip( $b ), array_flip( $c ) );
1812 $common = $merge( [], [
1830 # These attributes are specified in section 9 of
1838 # Microdata. These are specified by
1847 $block = $merge( $common, [
'align' ] );
1849 $tablealign = [
'align',
'valign' ];
1857 'nowrap', # deprecated
1858 'width', # deprecated
1859 'height', # deprecated
1860 'bgcolor', # deprecated
1863 # Numbers refer to sections in HTML 4.01 standard describing the element.
1864 # See: https://www.w3.org/TR/html4/
1868 'center' => $common, # deprecated
1887 'strong' => $common,
1898 'blockquote' => $merge( $common, [
'cite' ] ),
1899 'q' => $merge( $common, [
'cite' ] ),
1909 'br' => $merge( $common, [
'clear' ] ),
1911 # https://www.w3.org/TR/html5/text-level-semantics.html#the-wbr-element
1915 'pre' => $merge( $common, [
'width' ] ),
1918 'ins' => $merge( $common, [
'cite',
'datetime' ] ),
1919 'del' => $merge( $common, [
'cite',
'datetime' ] ),
1922 'ul' => $merge( $common, [
'type' ] ),
1923 'ol' => $merge( $common, [
'type',
'start',
'reversed' ] ),
1924 'li' => $merge( $common, [
'type',
'value' ] ),
1932 'table' => $merge( $common,
1933 [
'summary',
'width',
'border',
'frame',
1934 'rules',
'cellspacing',
'cellpadding',
1939 'caption' => $block,
1947 'colgroup' => $merge( $common, [
'span' ] ),
1948 'col' => $merge( $common, [
'span' ] ),
1951 'tr' => $merge( $common, [
'bgcolor' ], $tablealign ),
1954 'td' => $merge( $common, $tablecell, $tablealign ),
1955 'th' => $merge( $common, $tablecell, $tablealign ),
1958 # NOTE: <a> is not allowed directly, but the attrib
1959 # whitelist is used from the Parser object
1960 'a' => $merge( $common, [
'href',
'rel',
'rev' ] ), # rel/rev esp.
for RDFa
1963 # Not usually allowed, but may be used for extension-style hooks
1964 # such as <math> when it is rasterized, or if $wgAllowImageTag is
1966 'img' => $merge( $common, [
'alt',
'src',
'width',
'height',
'srcset' ] ),
1967 # Attributes for A/V tags added in T163583 / T133673
1968 'audio' => $merge( $common, [
'controls',
'preload',
'width',
'height' ] ),
1969 'video' => $merge( $common, [
'poster',
'controls',
'preload',
'width',
'height' ] ),
1970 'source' => $merge( $common, [
'type',
'src' ] ),
1971 'track' => $merge( $common, [
'type',
'src',
'srclang',
'kind',
'label' ] ),
1979 'strike' => $common,
1984 'font' => $merge( $common, [
'size',
'color',
'face' ] ),
1988 'hr' => $merge( $common, [
'width' ] ),
1990 # HTML Ruby annotation text module, simple ruby only.
1991 # https://www.w3.org/TR/html5/text-level-semantics.html#the-ruby-element
1996 'rt' => $common, # $merge( $common, [
'rbspan' ] ),
1999 # MathML root element, where used for extensions
2000 # 'title' may not be 100% valid here; it's XHTML
2001 # https://www.w3.org/TR/REC-MathML/
2002 'math' => $merge( [], [
'class',
'style',
'id',
'title' ] ),
2005 'figure' => $common,
2006 'figure-inline' => $common, # T118520
2007 'figcaption' => $common,
2009 # HTML 5 section 4.6
2012 # HTML5 elements, defined by:
2013 # https://html.spec.whatwg.org/multipage/semantics.html#the-data-element
2014 'data' => $merge( $common, [
'value' ] ),
2015 'time' => $merge( $common, [
'datetime' ] ),
2023 'meta' => $merge( [], [
'itemprop',
'content' ] ),
2024 'link' => $merge( [], [
'itemprop',
'href',
'title' ] ),
2041 static function stripAllTags( $html ) {
2044 $tokenizer =
new RemexHtml\Tokenizer\Tokenizer( $handler, $html, [
2045 'ignoreErrors' =>
true,
2047 'ignoreNulls' =>
true,
2048 'skipPreprocess' =>
true,
2050 $tokenizer->execute();
2051 $text = $handler->getResult();
2053 $text = self::normalizeWhitespace( $text );
2066 static function hackDocType() {
2067 $out =
"<!DOCTYPE html [\n";
2068 foreach ( self::$htmlEntities as $entity => $codepoint ) {
2069 $out .=
"<!ENTITY $entity \"&#$codepoint;\">";
2079 static function cleanUrl( $url ) {
2080 # Normalize any HTML entities in input. They will be
2081 # re-escaped by makeExternalLink().
2082 $url = self::decodeCharReferences( $url );
2084 # Escape any control characters introduced by the above step
2085 $url = preg_replace_callback(
'/[\][<>"\\x00-\\x20\\x7F\|]/',
2086 [ __CLASS__,
'cleanUrlCallback' ], $url );
2088 # Validate hostname portion
2090 if ( preg_match(
'!^([^:]+:)(//[^/]+)?(.*)$!iD', $url,
$matches ) ) {
2091 list( , $protocol, $host, $rest ) =
$matches;
2097 \\s| # general whitespace
2098 \xc2\xad| # 00ad SOFT HYPHEN
2099 \xe1\xa0\x86| # 1806 MONGOLIAN TODO SOFT HYPHEN
2100 \xe2\x80\x8b| # 200b ZERO WIDTH SPACE
2101 \xe2\x81\xa0| # 2060 WORD JOINER
2102 \xef\xbb\xbf| # feff ZERO WIDTH NO-BREAK SPACE
2103 \xcd\x8f| # 034f COMBINING GRAPHEME JOINER
2104 \xe1\xa0\x8b| # 180b MONGOLIAN FREE VARIATION SELECTOR ONE
2105 \xe1\xa0\x8c| # 180c MONGOLIAN FREE VARIATION SELECTOR TWO
2106 \xe1\xa0\x8d| # 180d MONGOLIAN FREE VARIATION SELECTOR THREE
2107 \xe2\x80\x8c| # 200c ZERO WIDTH NON-JOINER
2108 \xe2\x80\x8d| # 200d ZERO WIDTH JOINER
2109 [\xef\xb8\x80-\xef\xb8\x8f] # fe00-fe0f VARIATION SELECTOR-1-16
2112 $host = preg_replace( $strip,
'', $host );
2115 if ( substr_compare(
"//%5B", $host, 0, 5 ) === 0 &&
2116 preg_match(
'!^//%5B([0-9A-Fa-f:.]+)%5D((:\d+)?)$!', $host,
$matches )
2123 return $protocol . $host . $rest;
2133 static function cleanUrlCallback(
$matches ) {
2165 public static function validateEmail( $addr ) {
2167 if ( !
Hooks::run(
'isValidEmailAddr', [ $addr, &$result ] ) ) {
2174 $rfc5322_atext =
"a-z0-9!#$%&'*+\\-\/=?^_`{|}~";
2175 $rfc1034_ldh_str =
"a-z0-9\\-";
2177 $html5_email_regexp =
"/
2179 [$rfc5322_atext\\.]+ # user part which is liberal :p
2181 [$rfc1034_ldh_str]+ # First domain part
2182 (\\.[$rfc1034_ldh_str]+)* # Following part prefixed with a dot
2186 return (
bool)preg_match( $html5_email_regexp, $addr );