39 '/&([A-Za-z0-9\x80-\xff]+);
41 |&\#[xX]([0-9A-Fa-f]+);
358 if ( self::$attribsRegex ===
null ) {
359 $spaceChars =
'\x09\x0a\x0c\x0d\x20';
360 $space =
"[{$spaceChars}]";
361 $attrib =
"[^{$spaceChars}\/>=]";
362 $attribFirst =
"(?:{$attrib}|=)";
363 self::$attribsRegex =
364 "/({$attribFirst}{$attrib}*)
367 # The attribute value: quoted or alone
374 return self::$attribsRegex;
387 if ( self::$attribNameRegex ===
null ) {
388 $attribFirst =
"[:_\p{L}\p{N}]";
389 $attrib =
"[:_\.\-\p{L}\p{N}]";
390 self::$attribNameRegex =
"/^({$attribFirst}{$attrib}*)$/sxu";
392 return self::$attribNameRegex;
404 static $htmlpairsStatic, $htmlsingle, $htmlsingleonly, $htmlnest, $tabletags,
405 $htmllist, $listtags, $htmlsingleallowed, $htmlelementsStatic, $staticInitialised;
410 if ( !$staticInitialised || $staticInitialised != $globalContext ) {
411 $htmlpairsStatic = [ # Tags that must be closed
412 'b',
'bdi',
'del',
'i',
'ins',
'u',
'font',
'big',
'small',
'sub',
'sup',
'h1',
413 'h2',
'h3',
'h4',
'h5',
'h6',
'cite',
'code',
'em',
's',
414 'strike',
'strong',
'tt',
'var',
'div',
'center',
415 'blockquote',
'ol',
'ul',
'dl',
'table',
'caption',
'pre',
416 'ruby',
'rb',
'rp',
'rt',
'rtc',
'p',
'span',
'abbr',
'dfn',
417 'kbd',
'samp',
'data',
'time',
'mark'
420 'br',
'wbr',
'hr',
'li',
'dt',
'dd',
'meta',
'link'
423 # Elements that cannot have close tags. This is (not coincidentally)
424 # also the list of tags for which the HTML 5 parsing algorithm
425 # requires you to "acknowledge the token's self-closing flag", i.e.
426 # a self-closing tag like <br/> is not an HTML 5 parse error only
429 'br',
'wbr',
'hr',
'meta',
'link'
432 $htmlnest = [ # Tags that can be nested--??
433 'table',
'tr',
'td',
'th',
'div',
'blockquote',
'ol',
'ul',
434 'li',
'dl',
'dt',
'dd',
'font',
'big',
'small',
'sub',
'sup',
'span',
435 'var',
'kbd',
'samp',
'em',
'strong',
'q',
'ruby',
'bdo'
437 $tabletags = [ # Can only appear inside table, we will close them
440 $htmllist = [ # Tags used by list
443 $listtags = [ # Tags that can appear in a list
449 'is deprecated since MediaWiki 1.35',
'1.35',
false,
false );
450 $htmlsingle[] =
'img';
451 $htmlsingleonly[] =
'img';
454 $htmlsingleallowed = array_unique( array_merge( $htmlsingle, $tabletags ) );
455 $htmlelementsStatic = array_unique( array_merge( $htmlsingle, $htmlpairsStatic, $htmlnest ) );
457 # Convert them all to hashtables for faster lookup
458 $vars = [
'htmlpairsStatic',
'htmlsingle',
'htmlsingleonly',
'htmlnest',
'tabletags',
459 'htmllist',
'listtags',
'htmlsingleallowed',
'htmlelementsStatic' ];
460 foreach ( $vars as $var ) {
461 $$var = array_flip( $$var );
463 $staticInitialised = $globalContext;
466 # Populate $htmlpairs and $htmlelements with the $extratags and $removetags arrays
467 $extratags = array_flip( $extratags );
468 $removetags = array_flip( $removetags );
469 $htmlpairs = array_merge( $extratags, $htmlpairsStatic );
470 $htmlelements = array_diff_key( array_merge( $extratags, $htmlelementsStatic ), $removetags );
473 'htmlpairs' => $htmlpairs,
474 'htmlsingle' => $htmlsingle,
475 'htmlsingleonly' => $htmlsingleonly,
476 'htmlnest' => $htmlnest,
477 'tabletags' => $tabletags,
478 'htmllist' => $htmllist,
479 'listtags' => $listtags,
480 'htmlsingleallowed' => $htmlsingleallowed,
481 'htmlelements' => $htmlelements,
497 $args = [], $extratags = [], $removetags = []
499 $tagData = self::getRecognizedTagData( $extratags, $removetags );
500 $htmlpairs = $tagData[
'htmlpairs'];
501 $htmlsingle = $tagData[
'htmlsingle'];
502 $htmlsingleonly = $tagData[
'htmlsingleonly'];
503 $htmlnest = $tagData[
'htmlnest'];
504 $tabletags = $tagData[
'tabletags'];
505 $htmllist = $tagData[
'htmllist'];
506 $listtags = $tagData[
'listtags'];
507 $htmlsingleallowed = $tagData[
'htmlsingleallowed'];
508 $htmlelements = $tagData[
'htmlelements'];
510 # Remove HTML comments
511 $text = self::removeHTMLcomments( $text );
512 $bits = explode(
'<', $text );
513 $text = str_replace(
'>',
'>', array_shift( $bits ) );
515 # this might be possible using remex tidy itself
516 foreach ( $bits as $x ) {
517 if ( preg_match( self::ELEMENT_BITS_REGEX, $x, $regs ) ) {
518 list( , $slash,
$t, $params, $brace, $rest ) = $regs;
521 $t = strtolower(
$t );
522 if ( isset( $htmlelements[
$t] ) ) {
523 if ( is_callable( $processCallback ) ) {
524 call_user_func_array( $processCallback, [ &$params,
$args ] );
527 if ( $brace ==
'/>' && !( isset( $htmlsingle[
$t] ) || isset( $htmlsingleonly[
$t] ) ) ) {
532 if ( !self::validateTag( $params,
$t ) ) {
536 $newparams = self::fixTagAttributes( $params,
$t );
538 if ( $brace ===
'/>' && !isset( $htmlsingleonly[
$t] ) ) {
539 # Interpret self-closing tags as empty tags even when
540 # HTML 5 would interpret them as start tags. Such input
541 # is commonly seen on Wikimedia wikis with this intention.
545 $rest = str_replace(
'>',
'>', $rest );
546 $text .=
"<$slash$t$newparams$brace$rest";
551 $text .=
'<' . str_replace(
'>',
'>', $x );
566 while ( ( $start = strpos( $text,
'<!--' ) ) !==
false ) {
567 $end = strpos( $text,
'-->', $start + 4 );
568 if ( $end ===
false ) {
569 # Unterminated comment; bail out
575 # Trim space and newline if the comment is both
576 # preceded and followed by a newline
577 $spaceStart = max( $start - 1, 0 );
578 $spaceLen = $end - $spaceStart;
579 while ( substr( $text, $spaceStart, 1 ) ===
' ' && $spaceStart > 0 ) {
583 while ( substr( $text, $spaceStart + $spaceLen, 1 ) ===
' ' ) {
586 if ( substr( $text, $spaceStart, 1 ) ===
"\n"
587 && substr( $text, $spaceStart + $spaceLen, 1 ) ===
"\n" ) {
588 # Remove the comment, leading and trailing
589 # spaces, and leave only one newline.
590 $text = substr_replace( $text,
"\n", $spaceStart, $spaceLen + 1 );
592 # Remove just the comment.
593 $text = substr_replace( $text,
'', $start, $end - $start );
612 $params = self::decodeTagAttributes( $params );
614 if ( $element ==
'meta' || $element ==
'link' ) {
615 if ( !isset( $params[
'itemprop'] ) ) {
619 if ( $element ==
'meta' && !isset( $params[
'content'] ) ) {
623 if ( $element ==
'link' && !isset( $params[
'href'] ) ) {
648 return self::validateAttributes( $attribs,
649 self::attributesAllowedInternal( $element ) );
671 if ( isset( $allowed[0] ) ) {
674 wfDeprecated( __METHOD__ .
' with sequential array',
'1.35' );
675 $allowed = array_flip( $allowed );
680 foreach ( $attribs as $attribute => $value ) {
681 # Allow XML namespace declaration to allow RDFa
682 if ( preg_match( self::XMLNS_ATTRIBUTE_PATTERN, $attribute ) ) {
683 if ( !preg_match( self::EVIL_URI_PATTERN, $value ) ) {
684 $out[$attribute] = $value;
690 # Allow any attribute beginning with "data-"
692 # * Disallow data attributes used by MediaWiki code
693 # * Ensure that the attribute is not namespaced by banning
696 !preg_match(
'/^data-[^:]*$/i', $attribute ) &&
697 !array_key_exists( $attribute, $allowed )
698 ) || self::isReservedDataAttribute( $attribute ) ) {
702 # Strip javascript "expression" from stylesheets.
704 if ( $attribute ==
'style' ) {
705 $value = self::checkCss( $value );
708 # Escape HTML id attributes
709 if ( $attribute ===
'id' ) {
710 $value = self::escapeIdForAttribute( $value, self::ID_PRIMARY );
713 # Escape HTML id reference lists
714 if ( $attribute ===
'aria-describedby'
715 || $attribute ===
'aria-flowto'
716 || $attribute ===
'aria-labelledby'
717 || $attribute ===
'aria-owns'
719 $value = self::escapeIdReferenceList( $value );
724 if ( $attribute ===
'rel' || $attribute ===
'rev'
726 || $attribute ===
'about' || $attribute ===
'property'
727 || $attribute ===
'resource' || $attribute ===
'datatype'
728 || $attribute ===
'typeof'
730 || $attribute ===
'itemid' || $attribute ===
'itemprop'
731 || $attribute ===
'itemref' || $attribute ===
'itemscope'
732 || $attribute ===
'itemtype'
735 if ( preg_match( self::EVIL_URI_PATTERN, $value ) ) {
740 # NOTE: even though elements using href/src are not allowed directly, supply
741 # validation code that can be used by tag hook handlers, etc
742 if ( $attribute ===
'href' || $attribute ===
'src' || $attribute ===
'poster' ) {
743 if ( !preg_match( $hrefExp, $value ) ) {
749 if ( $attribute ===
'tabindex' && $value !==
'0' ) {
756 $out[$attribute] = $value;
759 # itemtype, itemid, itemref don't make sense without itemscope
760 if ( !array_key_exists(
'itemscope', $out ) ) {
761 unset( $out[
'itemtype'] );
762 unset( $out[
'itemid'] );
763 unset( $out[
'itemref'] );
765 # TODO: Strip itemprop if we aren't descendants of an itemscope or pointed to by an itemref.
785 return (
bool)preg_match(
'/^data-(ooui|mw|parsoid)/i', $attr );
799 $out = array_merge( $a, $b );
800 if ( isset( $a[
'class'] ) && isset( $b[
'class'] )
801 && is_string( $a[
'class'] ) && is_string( $b[
'class'] )
802 && $a[
'class'] !== $b[
'class']
804 $classes = preg_split(
'/\s+/',
"{$a['class']} {$b['class']}",
805 -1, PREG_SPLIT_NO_EMPTY );
806 $out[
'class'] = implode(
' ', array_unique( $classes ) );
821 $value = self::decodeCharReferences( $value );
833 if ( !$decodeRegex ) {
834 $space =
'[\\x20\\t\\r\\n\\f]';
835 $nl =
'(?:\\n|\\r\\n|\\r|\\f)';
837 $decodeRegex =
"/ $backslash
839 ($nl) | # 1. Line continuation
840 ([0-9A-Fa-f]{1,6})$space? | # 2. character number
841 (.) | # 3. backslash cancelling special meaning
842 () | # 4. backslash at end of string
845 $value = preg_replace_callback( $decodeRegex,
846 [ __CLASS__,
'cssDecodeCallback' ], $value );
851 if ( !preg_match(
'! ^ \s* /\* [^*\\/]* \*/ \s* $ !x', $value ) ) {
862 $commentPos = strpos( $value,
'/*' );
863 if ( $commentPos !==
false ) {
864 $value = substr( $value, 0, $commentPos );
890 $value = self::normalizeCss( $value );
893 if ( preg_match(
'/[\000-\010\013\016-\037\177]/', $value ) ||
894 strpos( $value, UtfNormal\Constants::UTF8_REPLACEMENT ) !==
false ) {
895 return '/* invalid control char */';
896 } elseif ( preg_match(
906 | attr\s*\([^)]+[\s,]+url
909 return '/* insecure input */';
923 $char = UtfNormal\Utils::codepointToUtf8( hexdec(
$matches[2] ) );
929 if ( $char ==
"\n" || $char ==
'"' || $char ==
"'" || $char ==
'\\' ) {
932 return '\\' . dechex( ord( $char ) ) .
' ';
961 if ( trim( $text ) ==
'' ) {
965 $decoded = self::decodeTagAttributes( $text );
966 $stripped = self::validateTagAttributes( $decoded, $element );
972 return self::safeEncodeTagAttributes( $stripped );
981 $encValue = htmlspecialchars( $text, ENT_QUOTES );
986 $encValue = strtr( $encValue, [
1007 # French spaces, last one Guillemet-left
1008 # only if there is something before the space
1009 # and a non-word character after the punctuation.
1010 '/(?<=\S) (?=[?:;!%»›](?!\w))/u' =>
"$space",
1011 # French spaces, Guillemet-right
1012 '/([«‹]) /u' =>
"\\1$space",
1014 return preg_replace( array_keys( $fixtags ), array_values( $fixtags ), $text );
1024 $encValue = self::encodeAttribute( $text );
1026 # Templates and links may be expanded in later parsing,
1027 # creating invalid or dangerous output. Suppress this.
1028 $encValue = strtr( $encValue, [
1036 "''" =>
'''',
1037 'ISBN' =>
'ISBN',
1039 'PMID' =>
'PMID',
1044 # Armor against French spaces detection (T5158)
1045 $encValue = self::armorFrenchSpaces( $encValue,
' ' );
1048 $encValue = preg_replace_callback(
1051 return str_replace(
':',
':',
$matches[1] );
1085 public static function escapeId( $id, $options = [] ) {
1087 $options = (array)$options;
1095 $id = urlencode( strtr( $id,
' ',
'_' ) );
1096 $id = strtr( $id, $replace );
1098 if ( !preg_match(
'/^[a-zA-Z]/', $id ) && !in_array(
'noninitial', $options ) ) {
1124 if ( $mode === self::ID_PRIMARY ) {
1125 throw new UnexpectedValueException(
'$wgFragmentMode is configured with no primary mode' );
1132 return self::escapeIdInternal( $id, $internalMode );
1151 throw new UnexpectedValueException(
'$wgFragmentMode is configured with no primary mode' );
1156 $id = self::escapeIdInternalUrl( $id, $mode );
1188 $id = self::escapeIdInternal( $id, $mode );
1189 if ( $mode ===
'html5' ) {
1190 $id = preg_replace(
'/%([a-fA-F0-9]{2})/',
'%25$1', $id );
1205 $id = mb_substr( $id, 0, 1024 );
1213 $id = str_replace( [
"\t",
"\n",
"\f",
"\r",
" " ],
'_', $id );
1222 $id = urlencode( str_replace(
' ',
'_', $id ) );
1223 $id = strtr( $id, $replace );
1226 throw new InvalidArgumentException(
"Invalid mode '$mode' passed to '" . __METHOD__ );
1242 # Explode the space delimited list string into an array of tokens
1243 $references = preg_split(
'/\s+/',
"{$referenceString}", -1, PREG_SPLIT_NO_EMPTY );
1245 # Escape each token as an id
1246 foreach ( $references as &$ref ) {
1247 $ref = self::escapeIdForAttribute( $ref );
1250 # Merge the array back to a space delimited list string
1251 # If the array is empty, the result will be an empty string ('')
1252 $referenceString = implode(
' ', $references );
1254 return $referenceString;
1270 return rtrim( preg_replace(
1271 [
'/(^[0-9\\-])|[\\x00-\\x20!"#$%&\'()*+,.\\/:;<=>?@[\\]^`{|}~]|\\xC2\\xA0/',
'/_+/' ],
1284 $html = self::decodeCharReferences( $html );
1285 # It seems wise to escape ' as well as ", as a matter of course. Can't
1286 # hurt. Use ENT_SUBSTITUTE so that incorrectly truncated multibyte characters
1287 # don't cause the entire string to disappear.
1288 $html = htmlspecialchars( $html, ENT_QUOTES | ENT_SUBSTITUTE );
1300 public static function decodeTagAttributes( $text ) {
1301 if ( trim( $text ) == '' ) {
1306 if ( !preg_match_all(
1307 self::getAttribsRegex(),
1310 PREG_SET_ORDER ) ) {
1315 foreach ( $pairs as $set ) {
1316 $attribute = strtolower( $set[1] );
1318 // Filter attribute names with unacceptable characters
1319 if ( !preg_match( self::getAttribNameRegex(), $attribute ) ) {
1323 $value = self::getTagAttributeCallback( $set );
1325 // Normalize whitespace
1326 $value = preg_replace( '/[\t\r\n ]+/', ' ', $value );
1327 $value = trim( $value );
1329 // Decode character references
1330 $attribs[$attribute] = self::decodeCharReferences( $value );
1342 public static function safeEncodeTagAttributes( $assoc_array ) {
1344 foreach ( $assoc_array as $attribute => $value ) {
1345 $encAttribute = htmlspecialchars( $attribute );
1346 $encValue = self::safeEncodeAttribute( $value );
1348 $attribs[] = "$encAttribute=\"$encValue\"";
1350 return count( $attribs ) ?
' ' . implode(
' ', $attribs ) :
'';
1362 if ( isset( $set[5] ) ) {
1365 } elseif ( isset( $set[4] ) ) {
1368 } elseif ( isset( $set[3] ) ) {
1371 } elseif ( !isset( $set[2] ) ) {
1372 # In XHTML, attributes must have a value so return an empty string.
1373 # See "Empty attribute syntax",
1377 throw new MWException(
"Tag conditions not met. This should never happen and is a bug." );
1386 return trim( preg_replace(
1387 '/(?:\r\n|[\x20\x0d\x0a\x09])+/',
1401 return trim( preg_replace(
'/[ _]+/',
' ', $section ) );
1420 return preg_replace_callback(
1421 self::CHAR_REFS_REGEX,
1422 [ self::class,
'normalizeCharReferencesCallback' ],
1433 $ret = self::normalizeEntity(
$matches[1] );
1435 $ret = self::decCharReference(
$matches[2] );
1437 $ret = self::hexCharReference(
$matches[3] );
1439 if ( $ret ===
null ) {
1440 return htmlspecialchars(
$matches[0] );
1457 if ( isset( self::HTML_ENTITY_ALIASES[$name] ) ) {
1458 return '&' . self::HTML_ENTITY_ALIASES[$name] .
';';
1459 } elseif ( in_array( $name, [
'lt',
'gt',
'amp',
'quot' ] ) ) {
1461 } elseif ( isset( self::HTML_ENTITIES[$name] ) ) {
1462 return '&#' . self::HTML_ENTITIES[$name] .
';';
1464 return "&$name;";
1473 $point = intval( $codepoint );
1474 if ( self::validateCodepoint( $point ) ) {
1475 return sprintf(
'&#%d;', $point );
1486 $point = hexdec( $codepoint );
1487 if ( self::validateCodepoint( $point ) ) {
1488 return sprintf(
'&#x%x;', $point );
1501 # U+000C is valid in HTML5 but not allowed in XML.
1502 # U+000D is valid in XML but not allowed in HTML5.
1503 # U+007F - U+009F are disallowed in HTML5 (control characters).
1504 return $codepoint == 0x09
1505 || $codepoint == 0x0a
1506 || ( $codepoint >= 0x20 && $codepoint <= 0x7e )
1507 || ( $codepoint >= 0xa0 && $codepoint <= 0xd7ff )
1508 || ( $codepoint >= 0xe000 && $codepoint <= 0xfffd )
1509 || ( $codepoint >= 0x10000 && $codepoint <= 0x10ffff );
1520 return preg_replace_callback(
1521 self::CHAR_REFS_REGEX,
1522 [ self::class,
'decodeCharReferencesCallback' ],
1537 $text = preg_replace_callback(
1538 self::CHAR_REFS_REGEX,
1539 [ self::class,
'decodeCharReferencesCallback' ],
1546 return MediaWikiServices::getInstance()->getContentLanguage()->normalize( $text );
1558 return self::decodeEntity(
$matches[1] );
1560 return self::decodeChar( intval(
$matches[2] ) );
1562 return self::decodeChar( hexdec(
$matches[3] ) );
1564 # Last case should be an ampersand by itself
1576 if ( self::validateCodepoint( $codepoint ) ) {
1577 return UtfNormal\Utils::codepointToUtf8( $codepoint );
1579 return UtfNormal\Constants::UTF8_REPLACEMENT;
1592 if ( isset( self::HTML_ENTITY_ALIASES[$name] ) ) {
1593 $name = self::HTML_ENTITY_ALIASES[$name];
1595 if ( isset( self::HTML_ENTITIES[$name] ) ) {
1596 return UtfNormal\Utils::codepointToUtf8( self::HTML_ENTITIES[$name] );
1610 $list = self::setupAttributesAllowedInternal();
1611 return $list[$element] ?? [];
1624 if ( $allowed !==
null ) {
1630 $merge =
function ( $a, $b, $c = [] ) {
1631 return array_merge( $a, array_flip( $b ), array_flip( $c ) );
1633 $common = $merge( [], [
1653 # These attributes are specified in section 9 of
1661 # Microdata. These are specified by
1670 $block = $merge( $common, [
'align' ] );
1672 $tablealign = [
'align',
'valign' ];
1680 'nowrap', # deprecated
1681 'width', # deprecated
1682 'height', # deprecated
1683 'bgcolor', # deprecated
1686 # Numbers refer to sections in HTML 4.01 standard describing the element.
1691 'center' => $common, # deprecated
1710 'strong' => $common,
1721 'blockquote' => $merge( $common, [
'cite' ] ),
1722 'q' => $merge( $common, [
'cite' ] ),
1732 'br' => $merge( $common, [
'clear' ] ),
1738 'pre' => $merge( $common, [
'width' ] ),
1741 'ins' => $merge( $common, [
'cite',
'datetime' ] ),
1742 'del' => $merge( $common, [
'cite',
'datetime' ] ),
1745 'ul' => $merge( $common, [
'type' ] ),
1746 'ol' => $merge( $common, [
'type',
'start',
'reversed' ] ),
1747 'li' => $merge( $common, [
'type',
'value' ] ),
1755 'table' => $merge( $common,
1756 [
'summary',
'width',
'border',
'frame',
1757 'rules',
'cellspacing',
'cellpadding',
1762 'caption' => $block,
1770 'colgroup' => $merge( $common, [
'span' ] ),
1771 'col' => $merge( $common, [
'span' ] ),
1774 'tr' => $merge( $common, [
'bgcolor' ], $tablealign ),
1777 'td' => $merge( $common, $tablecell, $tablealign ),
1778 'th' => $merge( $common, $tablecell, $tablealign ),
1781 # NOTE: <a> is not allowed directly, but this list of allowed
1782 # attributes is used from the Parser object
1783 'a' => $merge( $common, [
'href',
'rel',
'rev' ] ), # rel/rev esp.
for RDFa
1786 # Not usually allowed, but may be used for extension-style hooks
1787 # such as <math> when it is rasterized, or if $wgAllowImageTag is
1789 'img' => $merge( $common, [
'alt',
'src',
'width',
'height',
'srcset' ] ),
1790 # Attributes for A/V tags added in T163583 / T133673
1791 'audio' => $merge( $common, [
'controls',
'preload',
'width',
'height' ] ),
1792 'video' => $merge( $common, [
'poster',
'controls',
'preload',
'width',
'height' ] ),
1793 'source' => $merge( $common, [
'type',
'src' ] ),
1794 'track' => $merge( $common, [
'type',
'src',
'srclang',
'kind',
'label' ] ),
1802 'strike' => $common,
1807 'font' => $merge( $common, [
'size',
'color',
'face' ] ),
1811 'hr' => $merge( $common, [
'width' ] ),
1813 # HTML Ruby annotation text module, simple ruby only.
1819 'rt' => $common, # $merge( $common, [
'rbspan' ] ),
1822 # MathML root element, where used for extensions
1823 # 'title' may not be 100% valid here; it's XHTML
1825 'math' => $merge( [], [
'class',
'style',
'id',
'title' ] ),
1828 'figure' => $common,
1829 'figure-inline' => $common, # T118520
1830 'figcaption' => $common,
1832 # HTML 5 section 4.6
1835 # HTML5 elements, defined by:
1837 'data' => $merge( $common, [
'value' ] ),
1838 'time' => $merge( $common, [
'datetime' ] ),
1846 'meta' => $merge( [], [
'itemprop',
'content' ] ),
1847 'link' => $merge( [], [
'itemprop',
'href',
'title' ] ),
1867 $tokenizer =
new RemexHtml\Tokenizer\Tokenizer( $handler, $html, [
1868 'ignoreErrors' =>
true,
1870 'ignoreNulls' =>
true,
1871 'skipPreprocess' =>
true,
1873 $tokenizer->execute();
1874 $text = $handler->getResult();
1876 $text = self::normalizeWhitespace( $text );
1890 $out =
"<!DOCTYPE html [\n";
1891 foreach ( self::HTML_ENTITIES as $entity => $codepoint ) {
1892 $out .=
"<!ENTITY $entity \"&#$codepoint;\">";
1903 # Normalize any HTML entities in input. They will be
1904 # re-escaped by makeExternalLink().
1905 $url = self::decodeCharReferences( $url );
1907 # Escape any control characters introduced by the above step
1908 $url = preg_replace_callback(
'/[\][<>"\\x00-\\x20\\x7F\|]/',
1909 [ __CLASS__,
'cleanUrlCallback' ], $url );
1911 # Validate hostname portion
1913 if ( preg_match(
'!^([^:]+:)(//[^/]+)?(.*)$!iD', $url,
$matches ) ) {
1914 list( , $protocol, $host, $rest ) =
$matches;
1920 \\s| # general whitespace
1921 \xc2\xad| # 00ad SOFT HYPHEN
1922 \xe1\xa0\x86| # 1806 MONGOLIAN TODO SOFT HYPHEN
1923 \xe2\x80\x8b| # 200b ZERO WIDTH SPACE
1924 \xe2\x81\xa0| # 2060 WORD JOINER
1925 \xef\xbb\xbf| # feff ZERO WIDTH NO-BREAK SPACE
1926 \xcd\x8f| # 034f COMBINING GRAPHEME JOINER
1927 \xe1\xa0\x8b| # 180b MONGOLIAN FREE VARIATION SELECTOR ONE
1928 \xe1\xa0\x8c| # 180c MONGOLIAN FREE VARIATION SELECTOR TWO
1929 \xe1\xa0\x8d| # 180d MONGOLIAN FREE VARIATION SELECTOR THREE
1930 \xe2\x80\x8c| # 200c ZERO WIDTH NON-JOINER
1931 \xe2\x80\x8d| # 200d ZERO WIDTH JOINER
1932 [\xef\xb8\x80-\xef\xb8\x8f] # fe00-fe0f VARIATION SELECTOR-1-16
1935 $host = preg_replace( $strip,
'', $host );
1938 if ( substr_compare(
"//%5B", $host, 0, 5 ) === 0 &&
1939 preg_match(
'!^//%5B([0-9A-Fa-f:.]+)%5D((:\d+)?)$!', $host,
$matches )
1946 return $protocol . $host . $rest;
1990 if ( !Hooks::runner()->onIsValidEmailAddr( $addr, $result ) ) {
1997 $rfc5322_atext =
"a-z0-9!#$%&'*+\\-\/=?^_`{|}~";
1998 $rfc1034_ldh_str =
"a-z0-9\\-";
2000 $html5_email_regexp =
"/
2002 [$rfc5322_atext\\.]+ # user part which is liberal :p
2004 [$rfc1034_ldh_str]+ # First domain part
2005 (\\.[$rfc1034_ldh_str]+)* # Following part prefixed with a dot
2009 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...
wfDeprecatedMsg( $msg, $version=false, $component=false, $callerOffset=2)
Log a deprecation warning with arbitrary message text.
wfUrlProtocols( $includeProtocolRelative=true)
Returns a regular expression of url protocols.
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Logs 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,...
const CHAR_REFS_REGEX
Regular expression to match various types of character references in Sanitizer::normalizeCharReferenc...
const HTML_ENTITY_ALIASES
Character entity aliases accepted by MediaWiki.
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 escapeIdInternalUrl( $id, $mode)
Do percent encoding of percent signs for href (but not id) attributes.
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 validateAttributes( $attribs, $allowed)
Take an array of attribute names and values and normalize or discard illegal values.
static armorFrenchSpaces( $text, $space=' ')
Armor French spaces with a replacement character.
static setupAttributesAllowedInternal()
Foreach array key (an allowed HTML element), return an array of allowed attributes.
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 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
Pattern matching evil uris like javascript: WARNING: DO NOT use this in any place that actually requi...
static normalizeSectionNameWhitespace( $section)
Normalizes whitespace in a section name, such as might be returned by Parser::stripSectionName(),...
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 removeHTMLtags( $text, $processCallback=null, $args=[], $extratags=[], $removetags=[])
Cleans up HTML, removes dangerous tags and attributes, and removes HTML comments.
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 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 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...
const HTML_ENTITIES
List of all named character entities defined in HTML 4.01 https://www.w3.org/TR/html4/sgml/entities....
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 attributesAllowedInternal( $element)
Fetch the list of acceptable attributes for a given element name.
static decodeCharReferencesAndNormalize( $text)
Decode any character references, numeric or named entities, in the next and normalize the resulting s...
static escapeId( $id, $options=[])
Given a value, escape it so that it can be used in an id attribute and return it.
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.