39 '/&([A-Za-z0-9\x80-\xff]+);
41 |&\#[xX]([0-9A-Fa-f]+);
358 if ( self::$attribsRegex ===
null ) {
359 $attribFirst =
"[:_\p{L}\p{N}]";
360 $attrib =
"[:_\.\-\p{L}\p{N}]";
361 $space =
'[\x09\x0a\x0c\x0d\x20]';
362 self::$attribsRegex =
363 "/(?:^|$space)({$attribFirst}{$attrib}*)
366 # The attribute value: quoted or alone
371 )?(?=$space|\$)/sxu";
373 return self::$attribsRegex;
385 static $htmlpairsStatic, $htmlsingle, $htmlsingleonly, $htmlnest, $tabletags,
386 $htmllist, $listtags, $htmlsingleallowed, $htmlelementsStatic, $staticInitialised;
391 if ( !$staticInitialised || $staticInitialised != $globalContext ) {
392 $htmlpairsStatic = [ # Tags
that must be closed
393 'b',
'bdi',
'del',
'i',
'ins',
'u',
'font',
'big',
'small',
'sub',
'sup',
'h1',
394 'h2',
'h3',
'h4',
'h5',
'h6',
'cite',
'code',
'em',
's',
395 'strike',
'strong',
'tt',
'var',
'div',
'center',
396 'blockquote',
'ol',
'ul',
'dl',
'table',
'caption',
'pre',
397 'ruby',
'rb',
'rp',
'rt',
'rtc',
'p',
'span',
'abbr',
'dfn',
398 'kbd',
'samp',
'data',
'time',
'mark'
401 'br',
'wbr',
'hr',
'li',
'dt',
'dd',
'meta',
'link'
404 # Elements that cannot have close tags. This is (not coincidentally)
405 # also the list of tags for which the HTML 5 parsing algorithm
406 # requires you to "acknowledge the token's self-closing flag", i.e.
407 # a self-closing tag like <br/> is not an HTML 5 parse error only
410 'br',
'wbr',
'hr',
'meta',
'link'
413 $htmlnest = [ # Tags
that can be nested--??
414 'table',
'tr',
'td',
'th',
'div',
'blockquote',
'ol',
'ul',
415 'li',
'dl',
'dt',
'dd',
'font',
'big',
'small',
'sub',
'sup',
'span',
416 'var',
'kbd',
'samp',
'em',
'strong',
'q',
'ruby',
'bdo'
418 $tabletags = [ # Can only appear inside
table, we
will close
them
424 $listtags = [ # Tags
that can appear
in a
list
429 $htmlsingle[] =
'img';
430 $htmlsingleonly[] =
'img';
433 $htmlsingleallowed = array_unique( array_merge( $htmlsingle, $tabletags ) );
434 $htmlelementsStatic = array_unique( array_merge( $htmlsingle, $htmlpairsStatic, $htmlnest ) );
436 # Convert them all to hashtables for faster lookup
437 $vars = [
'htmlpairsStatic',
'htmlsingle',
'htmlsingleonly',
'htmlnest',
'tabletags',
438 'htmllist',
'listtags',
'htmlsingleallowed',
'htmlelementsStatic' ];
440 $$var = array_flip( $$var );
442 $staticInitialised = $globalContext;
445 # Populate $htmlpairs and $htmlelements with the $extratags and $removetags arrays
446 $extratags = array_flip( $extratags );
447 $removetags = array_flip( $removetags );
448 $htmlpairs = array_merge( $extratags, $htmlpairsStatic );
449 $htmlelements = array_diff_key( array_merge( $extratags, $htmlelementsStatic ), $removetags );
452 'htmlpairs' => $htmlpairs,
453 'htmlsingle' => $htmlsingle,
454 'htmlsingleonly' => $htmlsingleonly,
455 'htmlnest' => $htmlnest,
456 'tabletags' => $tabletags,
457 'htmllist' => $htmllist,
458 'listtags' => $listtags,
459 'htmlsingleallowed' => $htmlsingleallowed,
460 'htmlelements' => $htmlelements,
480 $args = [], $extratags = [], $removetags = [], $warnCallback =
null
482 $tagData = self::getRecognizedTagData( $extratags, $removetags );
483 $htmlpairs = $tagData[
'htmlpairs'];
484 $htmlsingle = $tagData[
'htmlsingle'];
485 $htmlsingleonly = $tagData[
'htmlsingleonly'];
486 $htmlnest = $tagData[
'htmlnest'];
487 $tabletags = $tagData[
'tabletags'];
488 $htmllist = $tagData[
'htmllist'];
489 $listtags = $tagData[
'listtags'];
490 $htmlsingleallowed = $tagData[
'htmlsingleallowed'];
491 $htmlelements = $tagData[
'htmlelements'];
493 # Remove HTML comments
494 $text = self::removeHTMLcomments( $text );
495 $bits = explode(
'<', $text );
496 $text = str_replace(
'>',
'>', array_shift( $bits ) );
498 $tagstack = $tablestack = [];
499 foreach ( $bits
as $x ) {
501 # $slash: Does the current element start with a '/'?
502 # $t: Current element name
503 # $params: String between element name and >
504 # $brace: Ending '>' or '/>'
505 # $rest: Everything until the next element of $bits
506 if ( preg_match( self::ELEMENT_BITS_REGEX, $x, $regs ) ) {
509 $slash =
$t =
$params = $brace = $rest =
null;
513 $t = strtolower(
$t );
514 if ( isset( $htmlelements[
$t] ) ) {
516 if ( $slash && isset( $htmlsingleonly[
$t] ) ) {
518 } elseif ( $slash ) {
519 # Closing a tag... is it the one we just opened?
520 Wikimedia\suppressWarnings();
521 $ot = array_pop( $tagstack );
522 Wikimedia\restoreWarnings();
525 if ( isset( $htmlsingleallowed[$ot] ) ) {
526 # Pop all elements with an optional close tag
527 # and see if we find a match below them
529 array_push( $optstack, $ot );
530 Wikimedia\suppressWarnings();
531 $ot = array_pop( $tagstack );
532 Wikimedia\restoreWarnings();
533 while ( $ot !=
$t && isset( $htmlsingleallowed[$ot] ) ) {
534 array_push( $optstack, $ot );
535 Wikimedia\suppressWarnings();
536 $ot = array_pop( $tagstack );
537 Wikimedia\restoreWarnings();
540 # No match. Push the optional elements back again
542 Wikimedia\suppressWarnings();
543 $ot = array_pop( $optstack );
544 Wikimedia\restoreWarnings();
546 array_push( $tagstack, $ot );
547 Wikimedia\suppressWarnings();
548 $ot = array_pop( $optstack );
549 Wikimedia\restoreWarnings();
553 Wikimedia\suppressWarnings();
554 array_push( $tagstack, $ot );
555 Wikimedia\restoreWarnings();
557 # <li> can be nested in <ul> or <ol>, skip those cases:
558 if ( !isset( $htmllist[$ot] ) || !isset( $listtags[
$t] ) ) {
563 if (
$t ==
'table' ) {
564 $tagstack = array_pop( $tablestack );
569 # Keep track for later
570 if ( isset( $tabletags[
$t] ) && !in_array(
'table', $tagstack ) ) {
572 } elseif ( in_array(
$t, $tagstack ) && !isset( $htmlnest[
$t] ) ) {
574 # Is it a self closed htmlpair ? (T7487)
575 } elseif ( $brace ==
'/>' && isset( $htmlpairs[
$t] ) ) {
581 if ( is_callable( $warnCallback ) ) {
582 call_user_func_array( $warnCallback, [
'deprecated-self-close-category' ] );
585 } elseif ( isset( $htmlsingleonly[
$t] ) ) {
586 # Hack to force empty tag for unclosable elements
588 } elseif ( isset( $htmlsingle[
$t] ) ) {
589 # Hack to not close $htmlsingle tags
591 # Still need to push this optionally-closed tag to
592 # the tag stack so that we can match end tags
593 # instead of marking them as bad.
594 array_push( $tagstack,
$t );
595 } elseif ( isset( $tabletags[
$t] ) && in_array(
$t, $tagstack ) ) {
599 if (
$t ==
'table' ) {
600 array_push( $tablestack, $tagstack );
603 array_push( $tagstack,
$t );
606 # Replace any variables or template parameters with
608 if ( is_callable( $processCallback ) ) {
609 call_user_func_array( $processCallback, [ &
$params,
$args ] );
612 if ( !self::validateTag(
$params,
$t ) ) {
616 # Strip non-approved attributes from the tag
617 $newparams = self::fixTagAttributes(
$params,
$t );
620 $rest = str_replace(
'>',
'>', $rest );
621 $close = ( $brace ==
'/>' && !$slash ) ?
' /' :
'';
622 $text .=
"<$slash$t$newparams$close>$rest";
626 $text .=
'<' . str_replace(
'>',
'>', $x );
628 # Close off any remaining tags
629 while ( is_array( $tagstack ) && (
$t = array_pop( $tagstack ) ) ) {
631 if (
$t ==
'table' ) {
632 $tagstack = array_pop( $tablestack );
636 # this might be possible using tidy itself
637 foreach ( $bits
as $x ) {
638 if ( preg_match( self::ELEMENT_BITS_REGEX, $x, $regs ) ) {
642 $t = strtolower(
$t );
643 if ( isset( $htmlelements[
$t] ) ) {
644 if ( is_callable( $processCallback ) ) {
645 call_user_func_array( $processCallback, [ &
$params,
$args ] );
648 if ( $brace ==
'/>' && !( isset( $htmlsingle[
$t] ) || isset( $htmlsingleonly[
$t] ) ) ) {
654 if ( is_callable( $warnCallback ) ) {
655 call_user_func_array( $warnCallback, [
'deprecated-self-close-category' ] );
658 if ( !self::validateTag(
$params,
$t ) ) {
662 $newparams = self::fixTagAttributes(
$params,
$t );
664 if ( $brace ===
'/>' && !isset( $htmlsingleonly[
$t] ) ) {
665 # Interpret self-closing tags as empty tags even when
666 # HTML 5 would interpret them as start tags. Such input
667 # is commonly seen on Wikimedia wikis with this intention.
671 $rest = str_replace(
'>',
'>', $rest );
672 $text .=
"<$slash$t$newparams$brace$rest";
677 $text .=
'<' . str_replace(
'>',
'>', $x );
693 while ( ( $start = strpos( $text,
'<!--' ) ) !==
false ) {
694 $end = strpos( $text,
'-->', $start + 4 );
695 if ( $end ===
false ) {
696 # Unterminated comment; bail out
702 # Trim space and newline if the comment is both
703 # preceded and followed by a newline
704 $spaceStart = max( $start - 1, 0 );
705 $spaceLen = $end - $spaceStart;
706 while ( substr( $text, $spaceStart, 1 ) ===
' ' && $spaceStart > 0 ) {
710 while ( substr( $text, $spaceStart + $spaceLen, 1 ) ===
' ' ) {
713 if ( substr( $text, $spaceStart, 1 ) ===
"\n"
714 && substr( $text, $spaceStart + $spaceLen, 1 ) ===
"\n" ) {
715 # Remove the comment, leading and trailing
716 # spaces, and leave only one newline.
717 $text = substr_replace( $text,
"\n", $spaceStart, $spaceLen + 1 );
719 # Remove just the comment.
720 $text = substr_replace( $text,
'', $start, $end - $start );
741 if ( $element ==
'meta' || $element ==
'link' ) {
742 if ( !isset(
$params[
'itemprop'] ) ) {
746 if ( $element ==
'meta' && !isset(
$params[
'content'] ) ) {
750 if ( $element ==
'link' && !isset(
$params[
'href'] ) ) {
775 return self::validateAttributes(
$attribs,
776 self::attributeWhitelist( $element ) );
795 $whitelist = array_flip( $whitelist );
800 # Allow XML namespace declaration to allow RDFa
801 if ( preg_match( self::XMLNS_ATTRIBUTE_PATTERN, $attribute ) ) {
802 if ( !preg_match( self::EVIL_URI_PATTERN,
$value ) ) {
809 # Allow any attribute beginning with "data-"
811 # * Disallow data attributes used by MediaWiki code
812 # * Ensure that the attribute is not namespaced by banning
814 if ( !preg_match(
'/^data-[^:]*$/i', $attribute )
815 && !isset( $whitelist[$attribute] )
816 || self::isReservedDataAttribute( $attribute )
821 # Strip javascript "expression" from stylesheets.
823 if ( $attribute ==
'style' ) {
827 # Escape HTML id attributes
828 if ( $attribute ===
'id' ) {
829 $value = self::escapeIdForAttribute(
$value, self::ID_PRIMARY );
832 # Escape HTML id reference lists
833 if ( $attribute ===
'aria-describedby'
834 || $attribute ===
'aria-flowto'
835 || $attribute ===
'aria-labelledby'
836 || $attribute ===
'aria-owns'
843 if ( $attribute ===
'rel' || $attribute ===
'rev'
845 || $attribute ===
'about' || $attribute ===
'property'
846 || $attribute ===
'resource' || $attribute ===
'datatype'
847 || $attribute ===
'typeof'
849 || $attribute ===
'itemid' || $attribute ===
'itemprop'
850 || $attribute ===
'itemref' || $attribute ===
'itemscope'
851 || $attribute ===
'itemtype'
854 if ( preg_match( self::EVIL_URI_PATTERN,
$value ) ) {
859 # NOTE: even though elements using href/src are not allowed directly, supply
860 # validation code that can be used by tag hook handlers, etc
861 if ( $attribute ===
'href' || $attribute ===
'src' || $attribute ===
'poster' ) {
862 if ( !preg_match( $hrefExp,
$value ) ) {
873 # itemtype, itemid, itemref don't make sense without itemscope
874 if ( !array_key_exists(
'itemscope',
$out ) ) {
875 unset(
$out[
'itemtype'] );
876 unset(
$out[
'itemid'] );
877 unset(
$out[
'itemref'] );
879 # TODO: Strip itemprop if we aren't descendants of an itemscope or pointed to by an itemref.
899 return (
bool)preg_match(
'/^data-(ooui|mw|parsoid)/i', $attr );
913 $out = array_merge( $a, $b );
914 if ( isset( $a[
'class'] ) && isset( $b[
'class'] )
915 && is_string( $a[
'class'] ) && is_string( $b[
'class'] )
916 && $a[
'class'] !== $b[
'class']
918 $classes = preg_split(
'/\s+/',
"{$a['class']} {$b['class']}",
919 -1, PREG_SPLIT_NO_EMPTY );
920 $out[
'class'] = implode(
' ', array_unique( $classes ) );
948 if ( !$decodeRegex ) {
949 $space =
'[\\x20\\t\\r\\n\\f]';
950 $nl =
'(?:\\n|\\r\\n|\\r|\\f)';
952 $decodeRegex =
"/ $backslash
954 ($nl) | # 1. Line continuation
955 ([0-9A-Fa-f]{1,6})$space? | # 2. character number
956 (.) | # 3. backslash cancelling special meaning
957 () | # 4. backslash at end of string
960 $value = preg_replace_callback( $decodeRegex,
961 [ __CLASS__,
'cssDecodeCallback' ],
$value );
964 $value = preg_replace_callback(
967 $cp = UtfNormal\Utils::utf8ToCodepoint(
$matches[0] );
968 if ( $cp ===
false ) {
971 return chr( $cp - 65248 );
979 [
'ʀ',
'ɴ',
'ⁿ',
'ʟ',
'ɪ',
'⁽',
'₍' ],
980 [
'r',
'n',
'n',
'l',
'i',
'(',
'(' ],
987 if ( !preg_match(
'! ^ \s* /\* [^*\\/]* \*/ \s* $ !x',
$value ) ) {
998 $commentPos = strpos(
$value,
'/*' );
999 if ( $commentPos !==
false ) {
1008 \xE3\x80\xB1 | # U+3031
1009 \xE3\x82\x9D | # U+309D
1010 \xE3\x83\xBC | # U+30FC
1011 \xE3\x83\xBD | # U+30FD
1012 \xEF\xB9\xBC | # U+FE7C
1013 \xEF\xB9\xBD | # U+FE7D
1014 \xEF\xBD\xB0 # U+FF70
1045 if ( preg_match(
'/[\000-\010\013\016-\037\177]/',
$value ) ||
1047 return '/* invalid control char */';
1048 } elseif ( preg_match(
1053 | -o-link-source\s*:
1058 | attr\s*\([^)]+[\s,]+url
1061 return '/* insecure input */';
1075 $char = UtfNormal\Utils::codepointToUtf8( hexdec(
$matches[2] ) );
1081 if ( $char ==
"\n" || $char ==
'"' || $char ==
"'" || $char ==
'\\' ) {
1084 return '\\' . dechex( ord( $char ) ) .
' ';
1113 if ( trim( $text ) ==
'' ) {
1117 $decoded = self::decodeTagAttributes( $text );
1118 $stripped = self::validateTagAttributes( $decoded, $element );
1124 return self::safeEncodeTagAttributes( $stripped );
1133 $encValue = htmlspecialchars( $text, ENT_QUOTES );
1138 $encValue = strtr( $encValue, [
1159 # French spaces, last one Guillemet-left
1160 # only if there is something before the space
1161 # and a non-word character after the punctuation.
1162 '/(\S) (?=[?:;!%»›](?!\w))/u' =>
"\\1$space",
1163 # French spaces, Guillemet-right
1164 '/([«‹]) /u' =>
"\\1$space",
1166 return preg_replace( array_keys( $fixtags ), array_values( $fixtags ), $text );
1176 $encValue = self::encodeAttribute( $text );
1178 # Templates and links may be expanded in later parsing,
1179 # creating invalid or dangerous output. Suppress this.
1180 $encValue = strtr( $encValue, [
1188 "''" =>
'''',
1189 'ISBN' =>
'ISBN',
1191 'PMID' =>
'PMID',
1196 # Armor against French spaces detection (T5158)
1197 $encValue = self::armorFrenchSpaces( $encValue,
' ' );
1200 $encValue = preg_replace_callback(
1203 return str_replace(
':',
':',
$matches[1] );
1246 $id = urlencode( strtr( $id,
' ',
'_' ) );
1247 $id = strtr( $id, $replace );
1249 if ( !preg_match(
'/^[a-zA-Z]/', $id ) && !in_array(
'noninitial',
$options ) ) {
1275 if ( $mode === self::ID_PRIMARY ) {
1276 throw new UnexpectedValueException(
'$wgFragmentMode is configured with no primary mode' );
1283 return self::escapeIdInternal( $id, $internalMode );
1302 throw new UnexpectedValueException(
'$wgFragmentMode is configured with no primary mode' );
1307 $id = self::escapeIdInternal( $id, $mode );
1339 $id = str_replace(
' ',
'_', $id );
1348 $id = urlencode( str_replace(
' ',
'_', $id ) );
1349 $id = strtr( $id, $replace );
1352 throw new InvalidArgumentException(
"Invalid mode '$mode' passed to '" . __METHOD__ );
1374 # Explode the space delimited list string into an array of tokens
1375 $references = preg_split(
'/\s+/',
"{$referenceString}", -1, PREG_SPLIT_NO_EMPTY );
1377 # Escape each token as an id
1378 foreach ( $references
as &$ref ) {
1379 $ref = self::escapeIdForAttribute( $ref );
1382 # Merge the array back to a space delimited list string
1383 # If the array is empty, the result will be an empty string ('')
1384 $referenceString = implode(
' ', $references );
1386 return $referenceString;
1402 return rtrim( preg_replace(
1403 [
'/(^[0-9\\-])|[\\x00-\\x20!"#$%&\'()*+,.\\/:;<=>?@[\\]^`{|}~]|\\xC2\\xA0/',
'/_+/' ],
1417 # It seems wise to escape ' as well as ", as a matter of course. Can't
1418 # hurt. Use ENT_SUBSTITUTE so that incorrectly truncated multibyte characters
1419 # don't cause the entire string to disappear.
1420 $html = htmlspecialchars( $html, ENT_QUOTES | ENT_SUBSTITUTE );
1432 public static function decodeTagAttributes( $text ) {
1433 if ( trim( $text ) == '' ) {
1439 if ( !preg_match_all(
1440 self::getAttribsRegex(),
1443 PREG_SET_ORDER ) ) {
1447 foreach ( $pairs as $set ) {
1448 $attribute = strtolower( $set[1] );
1449 $value = self::getTagAttributeCallback( $set );
1451 // Normalize whitespace
1452 $value = preg_replace( '/[\t\r\n ]+/', ' ', $value );
1453 $value = trim( $value );
1455 // Decode character references
1456 $attribs[$attribute] = self::decodeCharReferences( $value );
1468 public static function safeEncodeTagAttributes( $assoc_array ) {
1470 foreach ( $assoc_array as $attribute => $value ) {
1471 $encAttribute = htmlspecialchars( $attribute );
1472 $encValue = self::safeEncodeAttribute( $value );
1474 $attribs[] = "$encAttribute=\"$encValue\"";
1488 if ( isset( $set[5] ) ) {
1491 } elseif ( isset( $set[4] ) ) {
1494 } elseif ( isset( $set[3] ) ) {
1497 } elseif ( !isset( $set[2] ) ) {
1498 # In XHTML, attributes must have a value so return an empty string.
1499 # See "Empty attribute syntax",
1503 throw new MWException(
"Tag conditions not met. This should never happen and is a bug." );
1512 return trim( preg_replace(
1513 '/(?:\r\n|[\x20\x0d\x0a\x09])+/',
1527 return trim( preg_replace(
'/[ _]+/',
' ',
$section ) );
1546 return preg_replace_callback(
1547 self::CHAR_REFS_REGEX,
1548 [ self::class,
'normalizeCharReferencesCallback' ],
1565 if ( is_null(
$ret ) ) {
1566 return htmlspecialchars(
$matches[0] );
1583 if ( isset( self::$htmlEntityAliases[
$name] ) ) {
1584 return '&' . self::$htmlEntityAliases[
$name] .
';';
1585 } elseif ( in_array(
$name, [
'lt',
'gt',
'amp',
'quot' ] ) ) {
1587 } elseif ( isset( self::$htmlEntities[
$name] ) ) {
1588 return '&#' . self::$htmlEntities[
$name] .
';';
1590 return "&$name;";
1599 $point = intval( $codepoint );
1600 if ( self::validateCodepoint( $point ) ) {
1601 return sprintf(
'&#%d;', $point );
1612 $point = hexdec( $codepoint );
1613 if ( self::validateCodepoint( $point ) ) {
1614 return sprintf(
'&#x%x;', $point );
1627 # U+000C is valid in HTML5 but not allowed in XML.
1628 # U+000D is valid in XML but not allowed in HTML5.
1629 # U+007F - U+009F are disallowed in HTML5 (control characters).
1630 return $codepoint == 0x09
1631 || $codepoint == 0x0a
1632 || ( $codepoint >= 0x20 && $codepoint <= 0x7e )
1633 || ( $codepoint >= 0xa0 && $codepoint <= 0xd7ff )
1634 || ( $codepoint >= 0xe000 && $codepoint <= 0xfffd )
1635 || ( $codepoint >= 0x10000 && $codepoint <= 0x10ffff );
1646 return preg_replace_callback(
1647 self::CHAR_REFS_REGEX,
1648 [ self::class,
'decodeCharReferencesCallback' ],
1663 $text = preg_replace_callback(
1664 self::CHAR_REFS_REGEX,
1665 [ self::class,
'decodeCharReferencesCallback' ],
1672 return MediaWikiServices::getInstance()->getContentLanguage()->normalize( $text );
1684 return self::decodeEntity(
$matches[1] );
1686 return self::decodeChar( intval(
$matches[2] ) );
1688 return self::decodeChar( hexdec(
$matches[3] ) );
1690 # Last case should be an ampersand by itself
1702 if ( self::validateCodepoint( $codepoint ) ) {
1703 return UtfNormal\Utils::codepointToUtf8( $codepoint );
1705 return UtfNormal\Constants::UTF8_REPLACEMENT;
1718 if ( isset( self::$htmlEntityAliases[
$name] ) ) {
1721 if ( isset( self::$htmlEntities[
$name] ) ) {
1722 return UtfNormal\Utils::codepointToUtf8( self::$htmlEntities[
$name] );
1735 $list = self::setupAttributeWhitelist();
1736 return $list[$element] ?? [];
1747 if ( $whitelist !==
null ) {
1769 # These attributes are specified in section 9 of
1777 # Microdata. These are specified by
1786 $block = array_merge( $common, [
'align' ] );
1787 $tablealign = [
'align',
'valign' ];
1795 'nowrap', # deprecated
1796 'width', # deprecated
1797 'height', # deprecated
1798 'bgcolor', # deprecated
1801 # Numbers refer to sections in HTML 4.01 standard describing the element.
1806 'center' => $common, # deprecated
1825 'strong' => $common,
1836 'blockquote' => array_merge( $common, [
'cite' ] ),
1837 'q' => array_merge( $common, [
'cite' ] ),
1847 'br' => array_merge( $common, [
'clear' ] ),
1853 'pre' => array_merge( $common, [
'width' ] ),
1856 'ins' => array_merge( $common, [
'cite',
'datetime' ] ),
1857 'del' => array_merge( $common, [
'cite',
'datetime' ] ),
1860 'ul' => array_merge( $common, [
'type' ] ),
1861 'ol' => array_merge( $common, [
'type',
'start',
'reversed' ] ),
1862 'li' => array_merge( $common, [
'type',
'value' ] ),
1870 'table' => array_merge( $common,
1871 [
'summary',
'width',
'border',
'frame',
1872 'rules',
'cellspacing',
'cellpadding',
1877 'caption' => $block,
1885 'colgroup' => array_merge( $common, [
'span' ] ),
1886 'col' => array_merge( $common, [
'span' ] ),
1889 'tr' => array_merge( $common, [
'bgcolor' ], $tablealign ),
1892 'td' => array_merge( $common, $tablecell, $tablealign ),
1893 'th' => array_merge( $common, $tablecell, $tablealign ),
1896 # NOTE: <a> is not allowed directly, but the attrib
1897 # whitelist is used from the Parser object
1898 'a' => array_merge( $common, [
'href',
'rel',
'rev' ] ), # rel/rev esp.
for RDFa
1901 # Not usually allowed, but may be used for extension-style hooks
1902 # such as <math> when it is rasterized, or if $wgAllowImageTag is
1904 'img' => array_merge( $common, [
'alt',
'src',
'width',
'height',
'srcset' ] ),
1906 'video' => array_merge( $common, [
'poster',
'controls',
'preload',
'width',
'height' ] ),
1907 'source' => array_merge( $common, [
'type',
'src' ] ),
1908 'track' => array_merge( $common, [
'type',
'src',
'srclang',
'kind',
'label' ] ),
1916 'strike' => $common,
1921 'font' => array_merge( $common, [
'size',
'color',
'face' ] ),
1925 'hr' => array_merge( $common, [
'width' ] ),
1927 # HTML Ruby annotation text module, simple ruby only.
1933 'rt' => $common, # array_merge( $common,
array(
'rbspan' ) ),
1936 # MathML root element, where used for extensions
1937 # 'title' may not be 100% valid here; it's XHTML
1939 'math' => [
'class',
'style',
'id',
'title' ],
1942 'figure' => $common,
1943 'figcaption' => $common,
1945 # HTML 5 section 4.6
1948 # HTML5 elements, defined by:
1950 'data' => array_merge( $common, [
'value' ] ),
1951 'time' => array_merge( $common, [
'datetime' ] ),
1959 'meta' => [
'itemprop',
'content' ],
1960 'link' => [
'itemprop',
'href',
'title' ],
1979 $tokenizer =
new RemexHtml\Tokenizer\Tokenizer(
$handler,
$html, [
1980 'ignoreErrors' =>
true,
1982 'ignoreNulls' =>
true,
1983 'skipPreprocess' =>
true,
1985 $tokenizer->execute();
1988 $text = self::normalizeWhitespace( $text );
2002 $out =
"<!DOCTYPE html [\n";
2003 foreach ( self::$htmlEntities
as $entity => $codepoint ) {
2004 $out .=
"<!ENTITY $entity \"&#$codepoint;\">";
2015 # Normalize any HTML entities in input. They will be
2016 # re-escaped by makeExternalLink().
2017 $url = self::decodeCharReferences( $url );
2019 # Escape any control characters introduced by the above step
2020 $url = preg_replace_callback(
'/[\][<>"\\x00-\\x20\\x7F\|]/',
2021 [ __CLASS__,
'cleanUrlCallback' ], $url );
2023 # Validate hostname portion
2025 if ( preg_match(
'!^([^:]+:)(//[^/]+)?(.*)$!iD', $url,
$matches ) ) {
2032 \\s| # general whitespace
2033 \xc2\xad| # 00ad SOFT HYPHEN
2034 \xe1\xa0\x86| # 1806 MONGOLIAN TODO SOFT HYPHEN
2035 \xe2\x80\x8b| # 200b ZERO WIDTH SPACE
2036 \xe2\x81\xa0| # 2060 WORD JOINER
2037 \xef\xbb\xbf| # feff ZERO WIDTH NO-BREAK SPACE
2038 \xcd\x8f| # 034f COMBINING GRAPHEME JOINER
2039 \xe1\xa0\x8b| # 180b MONGOLIAN FREE VARIATION SELECTOR ONE
2040 \xe1\xa0\x8c| # 180c MONGOLIAN FREE VARIATION SELECTOR TWO
2041 \xe1\xa0\x8d| # 180d MONGOLIAN FREE VARIATION SELECTOR THREE
2042 \xe2\x80\x8c| # 200c ZERO WIDTH NON-JOINER
2043 \xe2\x80\x8d| # 200d ZERO WIDTH JOINER
2044 [\xef\xb8\x80-\xef\xb8\x8f] # fe00-fe0f VARIATION SELECTOR-1-16
2047 $host = preg_replace( $strip,
'', $host );
2050 if ( substr_compare(
"//%5B", $host, 0, 5 ) === 0 &&
2051 preg_match(
'!^//%5B([0-9A-Fa-f:.]+)%5D((:\d+)?)$!', $host,
$matches )
2058 return $protocol . $host . $rest;
2102 if ( !Hooks::run(
'isValidEmailAddr', [ $addr, &
$result ] ) ) {
2109 $rfc5322_atext =
"a-z0-9!#$%&'*+\\-\/=?^_`{|}~";
2110 $rfc1034_ldh_str =
"a-z0-9\\-";
2112 $html5_email_regexp =
"/
2114 [$rfc5322_atext\\.]+ # user part which is liberal :p
2116 [$rfc1034_ldh_str]+ # First domain part
2117 (\\.[$rfc1034_ldh_str]+)* # Following part prefixed with a dot
2121 return (
bool)preg_match( $html5_email_regexp, $addr );
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for and distribution as defined by Sections through of this document Licensor shall mean the copyright owner or entity authorized by the copyright owner that is granting the License Legal Entity shall mean the union of the acting entity and all other entities that control are controlled by or are under common control with that entity For the purposes of this definition control direct or to cause the direction or management of such whether by contract or including but not limited to software source documentation and configuration files Object form shall mean any form resulting from mechanical transformation or translation of a Source including but not limited to compiled object generated and conversions to other media types Work shall mean the work of whether in Source or Object made available under the as indicated by a copyright notice that is included in or attached to the whether in Source or Object that is based or other modifications as a an original work of authorship For the purposes of this Derivative Works shall not include works that remain separable or merely the Work and Derivative Works thereof Contribution shall mean any work of including the original version of the Work and any modifications or additions to that Work or Derivative Works that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner For the purposes of this submitted means any form of or written communication sent to the Licensor or its including but not limited to communication on electronic mailing source code control and issue tracking systems that are managed by
</td >< td > &</td >< td > t want your writing to be edited mercilessly and redistributed at will
$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,...
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 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 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 escapeIdReferenceList( $referenceString, $options=[])
Given a string containing a space delimited list of ids, escape each id to match ids escaped by the e...
static cssDecodeCallback( $matches)
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 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.
Unicode normalization routines for working with UTF-8 strings.
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global then executing the whole list after the page is displayed We don t do anything smart like collating updates to the same table or such because the list is almost always going to have just one item on if that
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global then executing the whole list after the page is displayed We don t do anything smart like collating updates to the same table or such because the list is almost always going to have just one item on if so it s not worth the trouble Since there is a job queue in the jobs table
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
static configuration should be added through ResourceLoaderGetConfigVars instead & $vars
this hook is for auditing only RecentChangesLinked and Watchlist Do not use this to implement individual filters if they are compatible with the ChangesListFilter and ChangesListFilterGroup structure use sub classes of those in conjunction with the ChangesListSpecialPageStructuredFilters hook This hook can be used to implement filters that do not implement that or custom behavior that is not an individual filter e g Watchlist and Watchlist you will want to construct new ChangesListBooleanFilter or ChangesListStringOptionsFilter objects When constructing them
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message. Please note the header message cannot receive/use parameters. 'ImgAuthModifyHeaders':Executed just before a file is streamed to a user via img_auth.php, allowing headers to be modified beforehand. $title:LinkTarget object & $headers:HTTP headers(name=> value, names are case insensitive). Two headers get special handling:If-Modified-Since(value must be a valid HTTP date) and Range(must be of the form "bytes=(\d*-\d*)") will be honored when streaming the file. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item. Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page. Return false to stop further processing of the tag $reader:XMLReader object & $pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUnknownUser':When a user doesn 't exist locally, this hook is called to give extensions an opportunity to auto-create it. If the auto-creation is successful, return false. $name:User name 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports. & $fullInterwikiPrefix:Interwiki prefix, may contain colons. & $pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable. Can be used to lazy-load the import sources list. & $importSources:The value of $wgImportSources. Modify as necessary. See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page. $context:IContextSource object & $pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect. & $title:Title object for the current page & $request:WebRequest & $ignoreRedirect:boolean to skip redirect check & $target:Title/string of redirect target & $article:Article object 'InternalParseBeforeLinks':during Parser 's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InternalParseBeforeSanitize':during Parser 's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings. Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not. Return true without providing an interwiki to continue interwiki search. $prefix:interwiki prefix we are looking for. & $iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user 's email has been invalidated successfully. $user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification. Callee may modify $url and $query, URL will be constructed as $url . $query & $url:URL to index.php & $query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) & $article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() & $ip:IP being check & $result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from & $allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn 't match your organization. $addr:The e-mail address entered by the user & $result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user & $result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we 're looking for a messages file for & $file:The messages file path, you can override this to change the location. 'LanguageGetMagic':DEPRECATED since 1.16! Use $magicWords in a file listed in $wgExtensionMessagesFiles instead. Use this to define synonyms of magic words depending of the language & $magicExtensions:associative array of magic words synonyms $lang:language code(string) 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces. Do not use this hook to add namespaces. Use CanonicalNamespaces for that. & $namespaces:Array of namespaces indexed by their numbers 'LanguageGetSpecialPageAliases':DEPRECATED! Use $specialPageAliases in a file listed in $wgExtensionMessagesFiles instead. Use to define aliases of special pages names depending of the language & $specialPageAliases:associative array of magic words synonyms $lang:language code(string) 'LanguageGetTranslatedLanguageNames':Provide translated language names. & $names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page 's language links. This is called in various places to allow extensions to define the effective language links for a page. $title:The page 's Title. & $links:Array with elements of the form "language:title" in the order that they will be output. & $linkFlags:Associative array mapping prefixed links to arrays of flags. Currently unused, but planned to provide support for marking individual language links in the UI, e.g. for featured articles. 'LanguageSelector':Hook to change the language selector available on a page. $out:The output page. $cssClassName:CSS class name of the language selector. 'LinkBegin':DEPRECATED since 1.28! Use HtmlPageLinkRendererBegin instead. Used when generating internal and interwiki links in Linker::link(), before processing starts. Return false to skip default processing and return $ret. See documentation for Linker::link() for details on the expected meanings of parameters. $skin:the Skin object $target:the Title that the link is pointing to & $html:the contents that the< a > tag should have(raw HTML) $result
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped & $options
null for the local wiki Added in
you don t have to do a grep find to see where the $wgReverseTitle variable is used
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses & $ret
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output $out
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return an< a > element with HTML attributes $attribs and contents $html will be returned If you return $ret will be returned and may include noclasses & $html
Allows to change the fields on the form that will be generated $name
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return an< a > element with HTML attributes $attribs and contents $html will be returned If you return $ret will be returned and may include noclasses after processing & $attribs
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output modifiable modifiable after all normalizations have been except for the $wgMaxImageArea check set to true or false to override the $wgMaxImageArea check result gives extension the possibility to transform it themselves $handler
usually copyright or history_copyright This message must be in HTML not wikitext if the section is included from a template $section
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))