3 * HTML sanitizer for %MediaWiki.
5 * Copyright © 2002-2005 Brion Vibber <brion@pobox.com> et al
6 * https://www.mediawiki.org/
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
27 use MediaWiki\MediaWikiServices
;
30 * HTML sanitizer for MediaWiki
35 * Regular expression to match various types of character references in
36 * Sanitizer::normalizeCharReferences and Sanitizer::decodeCharReferences
38 const CHAR_REFS_REGEX
=
39 '/&([A-Za-z0-9\x80-\xff]+);
41 |&\#[xX]([0-9A-Fa-f]+);
45 * Acceptable tag name charset from HTML5 parsing spec
46 * https://www.w3.org/TR/html5/syntax.html#tag-open-state
48 const ELEMENT_BITS_REGEX
= '!^(/?)([A-Za-z][^\t\n\v />\0]*+)([^>]*?)(/?>)([^<]*)$!';
51 * Blacklist for evil uris like javascript:
52 * WARNING: DO NOT use this in any place that actually requires blacklisting
53 * for security reasons. There are NUMEROUS[1] ways to bypass blacklisting, the
54 * only way to be secure from javascript: uri based xss vectors is to whitelist
55 * things that you know are safe and deny everything else.
56 * [1]: http://ha.ckers.org/xss.html
58 const EVIL_URI_PATTERN
= '!(^|\s|\*/\s*)(javascript|vbscript)([^\w]|$)!i';
59 const XMLNS_ATTRIBUTE_PATTERN
= "/^xmlns:[:A-Z_a-z-.0-9]+$/";
62 * Tells escapeUrlForHtml() to encode the ID using the wiki's primary encoding.
69 * Tells escapeUrlForHtml() to encode the ID using the fallback encoding, or return false
70 * if no fallback is configured.
74 const ID_FALLBACK
= 1;
77 * List of all named character entities defined in HTML 4.01
78 * https://www.w3.org/TR/html4/sgml/entities.html
79 * As well as ' which is only defined starting in XHTML1.
81 private static $htmlEntities = [
97 'apos' => 39, // New in XHTML & HTML 5; avoid in output for compatibility with IE.
338 * Character entity aliases accepted by MediaWiki
340 private static $htmlEntityAliases = [
346 * Lazy-initialised attributes regex, see getAttribsRegex()
348 private static $attribsRegex;
351 * Regular expression to match HTML/XML attribute pairs within a tag.
352 * Allows some... latitude. Based on,
353 * https://www.w3.org/TR/html5/syntax.html#before-attribute-value-state
354 * Used in Sanitizer::fixTagAttributes and Sanitizer::decodeTagAttributes
357 static function getAttribsRegex() {
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;
377 * Return the various lists of recognized tags
378 * @param array $extratags For any extra tags to include
379 * @param array $removetags For any tags (default or extra) to exclude
382 public static function getRecognizedTagData( $extratags = [], $removetags = [] ) {
383 global $wgAllowImageTag;
385 static $htmlpairsStatic, $htmlsingle, $htmlsingleonly, $htmlnest, $tabletags,
386 $htmllist, $listtags, $htmlsingleallowed, $htmlelementsStatic, $staticInitialised;
388 // Base our staticInitialised variable off of the global config state so that if the globals
389 // are changed (like in the screwed up test system) we will re-initialise the settings.
390 $globalContext = $wgAllowImageTag;
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
421 $htmllist = [ # Tags used by list
424 $listtags = [ # Tags that can appear in a list
428 if ( $wgAllowImageTag ) {
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' ];
439 foreach ( $vars as $var ) {
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,
465 * Cleans up HTML, removes dangerous tags and attributes, and
466 * removes HTML comments
467 * @param string $text
468 * @param callable|null $processCallback Callback to do any variable or parameter
469 * replacements in HTML attribute values
470 * @param array|bool $args Arguments for the processing callback
471 * @param array $extratags For any extra tags to include
472 * @param array $removetags For any tags (default or extra) to exclude
473 * @param callable|null $warnCallback (Deprecated) Callback allowing the
474 * addition of a tracking category when bad input is encountered.
475 * DO NOT ADD NEW PARAMETERS AFTER $warnCallback, since it will be
479 public static function removeHTMLtags( $text, $processCallback = null,
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 ) );
497 if ( !MWTidy
::isEnabled() ) {
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 ) ) {
507 list( /* $qbar */, $slash, $t, $params, $brace, $rest ) = $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] ) ) {
576 // Eventually we'll just remove the self-closing
577 // slash, in order to be consistent with HTML5
580 // For now, let's just warn authors to clean up.
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 ) ) {
596 // New table tag but forgot to close the previous one
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 ) ) {
639 list( /* $qbar */, $slash, $t, $params, $brace, $rest ) = $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] ) ) ) {
649 // Eventually we'll just remove the self-closing
650 // slash, in order to be consistent with HTML5
653 // For now, let's just warn authors to clean up.
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 );
684 * Remove '<!--', '-->', and everything between.
685 * To avoid leaving blank lines, when a comment is both preceded
686 * and followed by a newline (ignoring spaces), trim leading and
687 * trailing spaces and one of the newlines.
689 * @param string $text
692 public static function removeHTMLcomments( $text ) {
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 );
727 * Takes attribute names and values for a tag and the tag name and
728 * validates that the tag is allowed to be present.
729 * This DOES NOT validate the attributes, nor does it validate the
730 * tags themselves. This method only handles the special circumstances
731 * where we may want to allow a tag within content but ONLY when it has
732 * specific attributes set.
734 * @param string $params
735 * @param string $element
738 static function validateTag( $params, $element ) {
739 $params = self
::decodeTagAttributes( $params );
741 if ( $element == 'meta' ||
$element == 'link' ) {
742 if ( !isset( $params['itemprop'] ) ) {
743 // <meta> and <link> must have an itemprop="" otherwise they are not valid or safe in content
746 if ( $element == 'meta' && !isset( $params['content'] ) ) {
747 // <meta> must have a content="" for the itemprop
750 if ( $element == 'link' && !isset( $params['href'] ) ) {
751 // <link> must have an associated href=""
760 * Take an array of attribute names and values and normalize or discard
761 * illegal values for the given element type.
763 * - Discards attributes not on a whitelist for the given element
764 * - Unsafe style attributes are discarded
765 * - Invalid id attributes are re-encoded
767 * @param array $attribs
768 * @param string $element
771 * @todo Check for legal values where the DTD limits things.
772 * @todo Check for unique id attribute :P
774 static function validateTagAttributes( $attribs, $element ) {
775 return self
::validateAttributes( $attribs,
776 self
::attributeWhitelist( $element ) );
780 * Take an array of attribute names and values and normalize or discard
781 * illegal values for the given whitelist.
783 * - Discards attributes not on the given whitelist
784 * - Unsafe style attributes are discarded
785 * - Invalid id attributes are re-encoded
787 * @param array $attribs
788 * @param array $whitelist List of allowed attribute names
791 * @todo Check for legal values where the DTD limits things.
792 * @todo Check for unique id attribute :P
794 static function validateAttributes( $attribs, $whitelist ) {
795 $whitelist = array_flip( $whitelist );
796 $hrefExp = '/^(' . wfUrlProtocols() . ')[^\s]+$/';
799 foreach ( $attribs as $attribute => $value ) {
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 ) ) {
803 $out[$attribute] = $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.
822 # https://msdn.microsoft.com/en-us/library/ms537634.aspx
823 if ( $attribute == 'style' ) {
824 $value = self
::checkCss( $value );
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'
838 $value = self
::escapeIdReferenceList( $value );
841 // RDFa and microdata properties allow URLs, URIs and/or CURIs.
842 // Check them for sanity.
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'
853 // Paranoia. Allow "simple" values but suppress javascript
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 ) ) {
863 continue; // drop any href or src attributes not using an allowed protocol.
864 // NOTE: this also drops all relative URLs
868 // If this attribute was previously set, override it.
869 // Output should only have one attribute of each name.
870 $out[$attribute] = $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.
885 * Given an attribute name, checks whether it is a reserved data attribute
886 * (such as data-mw-foo) which is unavailable to user-generated HTML so MediaWiki
887 * core and extension code can safely use it to communicate with frontend code.
888 * @param string $attr Attribute name.
891 public static function isReservedDataAttribute( $attr ) {
892 // data-ooui is reserved for ooui.
893 // data-mw and data-parsoid are reserved for parsoid.
894 // data-mw-<name here> is reserved for extensions (or core) if
895 // they need to communicate some data to the client and want to be
896 // sure that it isn't coming from an untrusted user.
897 // We ignore the possibility of namespaces since user-generated HTML
898 // can't use them anymore.
899 return (bool)preg_match( '/^data-(ooui|mw|parsoid)/i', $attr );
903 * Merge two sets of HTML attributes. Conflicting items in the second set
904 * will override those in the first, except for 'class' attributes which
905 * will be combined (if they're both strings).
907 * @todo implement merging for other attributes such as style
912 static function mergeAttributes( $a, $b ) {
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 ) );
926 * Normalize CSS into a format we can easily search for hostile input
927 * - decode character references
928 * - decode escape sequences
929 * - convert characters that IE6 interprets into ascii
930 * - remove comments, unless the entire value is one single comment
931 * @param string $value the css string
932 * @return string normalized css
934 public static function normalizeCss( $value ) {
935 // Decode character references like {
936 $value = self
::decodeCharReferences( $value );
938 // Decode escape sequences and line continuation
939 // See the grammar in the CSS 2 spec, appendix D.
940 // This has to be done AFTER decoding character references.
941 // This means it isn't possible for this function to return
942 // unsanitized escape sequences. It is possible to manufacture
943 // input that contains character references that decode to
944 // escape sequences that decode to character references, but
945 // it's OK for the return value to contain character references
946 // because the caller is supposed to escape those anyway.
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 );
963 // Normalize Halfwidth and Fullwidth Unicode block that IE6 might treat as ascii
964 $value = preg_replace_callback(
965 '/[!-[]-z]/u', // U+FF01 to U+FF5A, excluding U+FF3C (T60088)
966 function ( $matches ) {
967 $cp = UtfNormal\Utils
::utf8ToCodepoint( $matches[0] );
968 if ( $cp === false ) {
971 return chr( $cp - 65248 ); // ASCII range \x21-\x7A
976 // Convert more characters IE6 might treat as ascii
977 // U+0280, U+0274, U+207F, U+029F, U+026A, U+207D, U+208D
978 $value = str_replace(
979 [ 'ʀ', 'ɴ', 'ⁿ', 'ʟ', 'ɪ', '⁽', '₍' ],
980 [ 'r', 'n', 'n', 'l', 'i', '(', '(' ],
984 // Let the value through if it's nothing but a single comment, to
985 // allow other functions which may reject it to pass some error
987 if ( !preg_match( '! ^ \s* /\* [^*\\/]* \*/ \s* $ !x', $value ) ) {
988 // Remove any comments; IE gets token splitting wrong
989 // This must be done AFTER decoding character references and
990 // escape sequences, because those steps can introduce comments
991 // This step cannot introduce character references or escape
992 // sequences, because it replaces comments with spaces rather
993 // than removing them completely.
994 $value = StringUtils
::delimiterReplace( '/*', '*/', ' ', $value );
996 // Remove anything after a comment-start token, to guard against
997 // incorrect client implementations.
998 $commentPos = strpos( $value, '/*' );
999 if ( $commentPos !== false ) {
1000 $value = substr( $value, 0, $commentPos );
1004 // S followed by repeat, iteration, or prolonged sound marks,
1005 // which IE will treat as "ss"
1006 $value = preg_replace(
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
1024 * Pick apart some CSS and check it for forbidden or unsafe structures.
1025 * Returns a sanitized string. This sanitized string will have
1026 * character references and escape sequences decoded and comments
1027 * stripped (unless it is itself one valid comment, in which case the value
1028 * will be passed through). If the input is just too evil, only a comment
1029 * complaining about evilness will be returned.
1031 * Currently URL references, 'expression', 'tps' are forbidden.
1033 * NOTE: Despite the fact that character references are decoded, the
1034 * returned string may contain character references given certain
1035 * clever input strings. These character references must
1036 * be escaped before the return value is embedded in HTML.
1038 * @param string $value
1041 static function checkCss( $value ) {
1042 $value = self
::normalizeCss( $value );
1044 // Reject problematic keywords and control characters
1045 if ( preg_match( '/[\000-\010\013\016-\037\177]/', $value ) ||
1046 strpos( $value, UtfNormal\Constants
::UTF8_REPLACEMENT
) !== false ) {
1047 return '/* invalid control char */';
1048 } elseif ( preg_match(
1053 | -o-link-source\s*:
1058 | attr\s*\([^)]+[\s,]+url
1060 return '/* insecure input */';
1066 * @param array $matches
1069 static function cssDecodeCallback( $matches ) {
1070 if ( $matches[1] !== '' ) {
1071 // Line continuation
1073 } elseif ( $matches[2] !== '' ) {
1074 $char = UtfNormal\Utils
::codepointToUtf8( hexdec( $matches[2] ) );
1075 } elseif ( $matches[3] !== '' ) {
1076 $char = $matches[3];
1080 if ( $char == "\n" ||
$char == '"' ||
$char == "'" ||
$char == '\\' ) {
1081 // These characters need to be escaped in strings
1082 // Clean up the escape sequence to avoid parsing errors by clients
1083 return '\\' . dechex( ord( $char ) ) . ' ';
1085 // Decode unnecessary escape
1091 * Take a tag soup fragment listing an HTML element's attributes
1092 * and normalize it to well-formed XML, discarding unwanted attributes.
1093 * Output is safe for further wikitext processing, with escaping of
1094 * values that could trigger problems.
1096 * - Normalizes attribute names to lowercase
1097 * - Discards attributes not on a whitelist for the given element
1098 * - Turns broken or invalid entities into plaintext
1099 * - Double-quotes all attribute values
1100 * - Attributes without values are given the name as attribute
1101 * - Double attributes are discarded
1102 * - Unsafe style attributes are discarded
1103 * - Prepends space if there are attributes.
1104 * - (Optionally) Sorts attributes by name.
1106 * @param string $text
1107 * @param string $element
1108 * @param bool $sorted Whether to sort the attributes (default: false)
1111 static function fixTagAttributes( $text, $element, $sorted = false ) {
1112 if ( trim( $text ) == '' ) {
1116 $decoded = self
::decodeTagAttributes( $text );
1117 $stripped = self
::validateTagAttributes( $decoded, $element );
1123 return self
::safeEncodeTagAttributes( $stripped );
1127 * Encode an attribute value for HTML output.
1128 * @param string $text
1129 * @return string HTML-encoded text fragment
1131 static function encodeAttribute( $text ) {
1132 $encValue = htmlspecialchars( $text, ENT_QUOTES
);
1134 // Whitespace is normalized during attribute decoding,
1135 // so if we've been passed non-spaces we must encode them
1136 // ahead of time or they won't be preserved.
1137 $encValue = strtr( $encValue, [
1147 * Armor French spaces with a replacement character
1150 * @param string $text Text to armor
1151 * @param string $space Space character for the French spaces, defaults to ' '
1152 * @return string Armored text
1154 public static function armorFrenchSpaces( $text, $space = ' ' ) {
1155 // Replace $ with \$ and \ with \\
1156 $space = preg_replace( '#(?<!\\\\)(\\$|\\\\)#', '\\\\$1', $space );
1158 # French spaces, last one Guillemet-left
1159 # only if there is something before the space
1160 # and a non-word character after the punctuation.
1161 '/(\S) (?=[?:;!%»›](?!\w))/u' => "\\1$space",
1162 # French spaces, Guillemet-right
1163 '/([«‹]) /u' => "\\1$space",
1165 return preg_replace( array_keys( $fixtags ), array_values( $fixtags ), $text );
1169 * Encode an attribute value for HTML tags, with extra armoring
1170 * against further wiki processing.
1171 * @param string $text
1172 * @return string HTML-encoded text fragment
1174 static function safeEncodeAttribute( $text ) {
1175 $encValue = self
::encodeAttribute( $text );
1177 # Templates and links may be expanded in later parsing,
1178 # creating invalid or dangerous output. Suppress this.
1179 $encValue = strtr( $encValue, [
1180 '<' => '<', // This should never happen,
1181 '>' => '>', // we've received invalid input
1182 '"' => '"', // which should have been escaped.
1184 '}' => '}', // prevent unpaired language conversion syntax
1187 "''" => '''',
1188 'ISBN' => 'ISBN',
1190 'PMID' => 'PMID',
1195 # Armor against French spaces detection (T5158)
1196 $encValue = self
::armorFrenchSpaces( $encValue, ' ' );
1199 $encValue = preg_replace_callback(
1200 '/((?i)' . wfUrlProtocols() . ')/',
1201 function ( $matches ) {
1202 return str_replace( ':', ':', $matches[1] );
1209 * Given a value, escape it so that it can be used in an id attribute and
1210 * return it. This will use HTML5 validation, allowing anything but ASCII
1213 * To ensure we don't have to bother escaping anything, we also strip ', ".
1214 * TODO: Is this the best tactic?
1216 * We also strip # because it upsets IE, and % because it could be
1217 * ambiguous if it's part of something that looks like a percent escape
1218 * (which don't work reliably in fragments cross-browser).
1220 * @deprecated since 1.30, use one of this class' escapeIdFor*() functions
1222 * @see https://www.w3.org/TR/html401/types.html#type-name Valid characters
1223 * in the id and name attributes
1224 * @see https://www.w3.org/TR/html401/struct/links.html#h-12.2.3 Anchors with
1226 * @see https://www.w3.org/TR/html5/dom.html#the-id-attribute
1227 * HTML5 definition of id attribute
1229 * @param string $id Id to escape
1230 * @param string|array $options String or array of strings (default is array()):
1231 * 'noninitial': This is a non-initial fragment of an id, not a full id,
1232 * so don't pay attention if the first character isn't valid at the
1233 * beginning of an id.
1236 static function escapeId( $id, $options = [] ) {
1237 $options = (array)$options;
1239 // HTML4-style escaping
1245 $id = urlencode( strtr( $id, ' ', '_' ) );
1246 $id = strtr( $id, $replace );
1248 if ( !preg_match( '/^[a-zA-Z]/', $id ) && !in_array( 'noninitial', $options ) ) {
1249 // Initial character must be a letter!
1256 * Given a section name or other user-generated or otherwise unsafe string, escapes it to be
1257 * a valid HTML id attribute.
1259 * WARNING: unlike escapeId(), the output of this function is not guaranteed to be HTML safe,
1260 * be sure to use proper escaping.
1262 * @param string $id String to escape
1263 * @param int $mode One of ID_* constants, specifying whether the primary or fallback encoding
1265 * @return string|bool Escaped ID or false if fallback encoding is requested but it's not
1270 public static function escapeIdForAttribute( $id, $mode = self
::ID_PRIMARY
) {
1271 global $wgFragmentMode;
1273 if ( !isset( $wgFragmentMode[$mode] ) ) {
1274 if ( $mode === self
::ID_PRIMARY
) {
1275 throw new UnexpectedValueException( '$wgFragmentMode is configured with no primary mode' );
1280 $internalMode = $wgFragmentMode[$mode];
1282 return self
::escapeIdInternal( $id, $internalMode );
1286 * Given a section name or other user-generated or otherwise unsafe string, escapes it to be
1287 * a valid URL fragment.
1289 * WARNING: unlike escapeId(), the output of this function is not guaranteed to be HTML safe,
1290 * be sure to use proper escaping.
1292 * @param string $id String to escape
1293 * @return string Escaped ID
1297 public static function escapeIdForLink( $id ) {
1298 global $wgFragmentMode;
1300 if ( !isset( $wgFragmentMode[self
::ID_PRIMARY
] ) ) {
1301 throw new UnexpectedValueException( '$wgFragmentMode is configured with no primary mode' );
1304 $mode = $wgFragmentMode[self
::ID_PRIMARY
];
1306 $id = self
::escapeIdInternal( $id, $mode );
1312 * Given a section name or other user-generated or otherwise unsafe string, escapes it to be
1313 * a valid URL fragment for external interwikis.
1315 * @param string $id String to escape
1316 * @return string Escaped ID
1320 public static function escapeIdForExternalInterwiki( $id ) {
1321 global $wgExternalInterwikiFragmentMode;
1323 $id = self
::escapeIdInternal( $id, $wgExternalInterwikiFragmentMode );
1329 * Helper for escapeIdFor*() functions. Performs most of the actual escaping.
1331 * @param string $id String to escape
1332 * @param string $mode One of modes from $wgFragmentMode
1335 private static function escapeIdInternal( $id, $mode ) {
1338 $id = str_replace( ' ', '_', $id );
1341 // This corresponds to 'noninitial' mode of the old escapeId()
1347 $id = urlencode( str_replace( ' ', '_', $id ) );
1348 $id = strtr( $id, $replace );
1351 throw new InvalidArgumentException( "Invalid mode '$mode' passed to '" . __METHOD__
);
1358 * Given a string containing a space delimited list of ids, escape each id
1359 * to match ids escaped by the escapeId() function.
1361 * @todo remove $options completely in 1.32
1365 * @param string $referenceString Space delimited list of ids
1366 * @param string|array $options Deprecated and does nothing.
1369 static function escapeIdReferenceList( $referenceString, $options = [] ) {
1371 wfDeprecated( __METHOD__
. ' with $options', '1.31' );
1373 # Explode the space delimited list string into an array of tokens
1374 $references = preg_split( '/\s+/', "{$referenceString}", -1, PREG_SPLIT_NO_EMPTY
);
1376 # Escape each token as an id
1377 foreach ( $references as &$ref ) {
1378 $ref = self
::escapeIdForAttribute( $ref );
1381 # Merge the array back to a space delimited list string
1382 # If the array is empty, the result will be an empty string ('')
1383 $referenceString = implode( ' ', $references );
1385 return $referenceString;
1389 * Given a value, escape it so that it can be used as a CSS class and
1392 * @todo For extra validity, input should be validated UTF-8.
1394 * @see https://www.w3.org/TR/CSS21/syndata.html Valid characters/format
1396 * @param string $class
1399 static function escapeClass( $class ) {
1400 // Convert ugly stuff to underscores and kill underscores in ugly places
1401 return rtrim( preg_replace(
1402 [ '/(^[0-9\\-])|[\\x00-\\x20!"#$%&\'()*+,.\\/:;<=>?@[\\]^`{|}~]|\\xC2\\xA0/', '/_+/' ],
1408 * Given HTML input, escape with htmlspecialchars but un-escape entities.
1409 * This allows (generally harmless) entities like   to survive.
1411 * @param string $html HTML to escape
1412 * @return string Escaped input
1414 static function escapeHtmlAllowEntities( $html ) {
1415 $html = self
::decodeCharReferences( $html );
1416 # It seems wise to escape ' as well as ", as a matter of course. Can't
1417 # hurt. Use ENT_SUBSTITUTE so that incorrectly truncated multibyte characters
1418 # don't cause the entire string to disappear.
1419 $html = htmlspecialchars( $html, ENT_QUOTES | ENT_SUBSTITUTE
);
1424 * Return an associative array of attribute names and values from
1425 * a partial tag string. Attribute names are forced to lowercase,
1426 * character references are decoded to UTF-8 text.
1428 * @param string $text
1431 public static function decodeTagAttributes( $text ) {
1432 if ( trim( $text ) == '' ) {
1438 if ( !preg_match_all(
1439 self
::getAttribsRegex(),
1442 PREG_SET_ORDER
) ) {
1446 foreach ( $pairs as $set ) {
1447 $attribute = strtolower( $set[1] );
1448 $value = self
::getTagAttributeCallback( $set );
1450 // Normalize whitespace
1451 $value = preg_replace( '/[\t\r\n ]+/', ' ', $value );
1452 $value = trim( $value );
1454 // Decode character references
1455 $attribs[$attribute] = self
::decodeCharReferences( $value );
1461 * Build a partial tag string from an associative array of attribute
1462 * names and values as returned by decodeTagAttributes.
1464 * @param array $assoc_array
1467 public static function safeEncodeTagAttributes( $assoc_array ) {
1469 foreach ( $assoc_array as $attribute => $value ) {
1470 $encAttribute = htmlspecialchars( $attribute );
1471 $encValue = self
::safeEncodeAttribute( $value );
1473 $attribs[] = "$encAttribute=\"$encValue\"";
1475 return count( $attribs ) ?
' ' . implode( ' ', $attribs ) : '';
1479 * Pick the appropriate attribute value from a match set from the
1480 * attribs regex matches.
1483 * @throws MWException When tag conditions are not met.
1486 private static function getTagAttributeCallback( $set ) {
1487 if ( isset( $set[5] ) ) {
1490 } elseif ( isset( $set[4] ) ) {
1493 } elseif ( isset( $set[3] ) ) {
1496 } elseif ( !isset( $set[2] ) ) {
1497 # In XHTML, attributes must have a value so return an empty string.
1498 # See "Empty attribute syntax",
1499 # https://www.w3.org/TR/html5/syntax.html#syntax-attribute-name
1502 throw new MWException( "Tag conditions not met. This should never happen and is a bug." );
1507 * @param string $text
1510 private static function normalizeWhitespace( $text ) {
1511 return preg_replace(
1512 '/\r\n|[\x20\x0d\x0a\x09]/',
1518 * Normalizes whitespace in a section name, such as might be returned
1519 * by Parser::stripSectionName(), for use in the id's that are used for
1522 * @param string $section
1525 static function normalizeSectionNameWhitespace( $section ) {
1526 return trim( preg_replace( '/[ _]+/', ' ', $section ) );
1530 * Ensure that any entities and character references are legal
1531 * for XML and XHTML specifically. Any stray bits will be
1532 * &-escaped to result in a valid text fragment.
1534 * a. named char refs can only be < > & ", others are
1535 * numericized (this way we're well-formed even without a DTD)
1536 * b. any numeric char refs must be legal chars, not invalid or forbidden
1537 * c. use lower cased "&#x", not "&#X"
1538 * d. fix or reject non-valid attributes
1540 * @param string $text
1544 static function normalizeCharReferences( $text ) {
1545 return preg_replace_callback(
1546 self
::CHAR_REFS_REGEX
,
1547 [ self
::class, 'normalizeCharReferencesCallback' ],
1552 * @param string $matches
1555 static function normalizeCharReferencesCallback( $matches ) {
1557 if ( $matches[1] != '' ) {
1558 $ret = self
::normalizeEntity( $matches[1] );
1559 } elseif ( $matches[2] != '' ) {
1560 $ret = self
::decCharReference( $matches[2] );
1561 } elseif ( $matches[3] != '' ) {
1562 $ret = self
::hexCharReference( $matches[3] );
1564 if ( is_null( $ret ) ) {
1565 return htmlspecialchars( $matches[0] );
1572 * If the named entity is defined in the HTML 4.0/XHTML 1.0 DTD,
1573 * return the equivalent numeric entity reference (except for the core <
1574 * > & "). If the entity is a MediaWiki-specific alias, returns
1575 * the HTML equivalent. Otherwise, returns HTML-escaped text of
1576 * pseudo-entity source (eg &foo;)
1578 * @param string $name
1581 static function normalizeEntity( $name ) {
1582 if ( isset( self
::$htmlEntityAliases[$name] ) ) {
1583 return '&' . self
::$htmlEntityAliases[$name] . ';';
1584 } elseif ( in_array( $name, [ 'lt', 'gt', 'amp', 'quot' ] ) ) {
1586 } elseif ( isset( self
::$htmlEntities[$name] ) ) {
1587 return '&#' . self
::$htmlEntities[$name] . ';';
1589 return "&$name;";
1594 * @param int $codepoint
1595 * @return null|string
1597 static function decCharReference( $codepoint ) {
1598 $point = intval( $codepoint );
1599 if ( self
::validateCodepoint( $point ) ) {
1600 return sprintf( '&#%d;', $point );
1607 * @param int $codepoint
1608 * @return null|string
1610 static function hexCharReference( $codepoint ) {
1611 $point = hexdec( $codepoint );
1612 if ( self
::validateCodepoint( $point ) ) {
1613 return sprintf( '&#x%x;', $point );
1620 * Returns true if a given Unicode codepoint is a valid character in
1621 * both HTML5 and XML.
1622 * @param int $codepoint
1625 private static function validateCodepoint( $codepoint ) {
1626 # U+000C is valid in HTML5 but not allowed in XML.
1627 # U+000D is valid in XML but not allowed in HTML5.
1628 # U+007F - U+009F are disallowed in HTML5 (control characters).
1629 return $codepoint == 0x09
1630 ||
$codepoint == 0x0a
1631 ||
( $codepoint >= 0x20 && $codepoint <= 0x7e )
1632 ||
( $codepoint >= 0xa0 && $codepoint <= 0xd7ff )
1633 ||
( $codepoint >= 0xe000 && $codepoint <= 0xfffd )
1634 ||
( $codepoint >= 0x10000 && $codepoint <= 0x10ffff );
1638 * Decode any character references, numeric or named entities,
1639 * in the text and return a UTF-8 string.
1641 * @param string $text
1644 public static function decodeCharReferences( $text ) {
1645 return preg_replace_callback(
1646 self
::CHAR_REFS_REGEX
,
1647 [ self
::class, 'decodeCharReferencesCallback' ],
1652 * Decode any character references, numeric or named entities,
1653 * in the next and normalize the resulting string. (T16952)
1655 * This is useful for page titles, not for text to be displayed,
1656 * MediaWiki allows HTML entities to escape normalization as a feature.
1658 * @param string $text Already normalized, containing entities
1659 * @return string Still normalized, without entities
1661 public static function decodeCharReferencesAndNormalize( $text ) {
1662 $text = preg_replace_callback(
1663 self
::CHAR_REFS_REGEX
,
1664 [ self
::class, 'decodeCharReferencesCallback' ],
1671 return MediaWikiServices
::getInstance()->getContentLanguage()->normalize( $text );
1678 * @param string $matches
1681 static function decodeCharReferencesCallback( $matches ) {
1682 if ( $matches[1] != '' ) {
1683 return self
::decodeEntity( $matches[1] );
1684 } elseif ( $matches[2] != '' ) {
1685 return self
::decodeChar( intval( $matches[2] ) );
1686 } elseif ( $matches[3] != '' ) {
1687 return self
::decodeChar( hexdec( $matches[3] ) );
1689 # Last case should be an ampersand by itself
1694 * Return UTF-8 string for a codepoint if that is a valid
1695 * character reference, otherwise U+FFFD REPLACEMENT CHARACTER.
1696 * @param int $codepoint
1700 static function decodeChar( $codepoint ) {
1701 if ( self
::validateCodepoint( $codepoint ) ) {
1702 return UtfNormal\Utils
::codepointToUtf8( $codepoint );
1704 return UtfNormal\Constants
::UTF8_REPLACEMENT
;
1709 * If the named entity is defined in the HTML 4.0/XHTML 1.0 DTD,
1710 * return the UTF-8 encoding of that character. Otherwise, returns
1711 * pseudo-entity source (eg "&foo;")
1713 * @param string $name
1716 static function decodeEntity( $name ) {
1717 if ( isset( self
::$htmlEntityAliases[$name] ) ) {
1718 $name = self
::$htmlEntityAliases[$name];
1720 if ( isset( self
::$htmlEntities[$name] ) ) {
1721 return UtfNormal\Utils
::codepointToUtf8( self
::$htmlEntities[$name] );
1728 * Fetch the whitelist of acceptable attributes for a given element name.
1730 * @param string $element
1733 static function attributeWhitelist( $element ) {
1734 $list = self
::setupAttributeWhitelist();
1735 return $list[$element] ??
[];
1739 * Foreach array key (an allowed HTML element), return an array
1740 * of allowed attributes
1743 static function setupAttributeWhitelist() {
1746 if ( $whitelist !== null ) {
1768 # These attributes are specified in section 9 of
1769 # https://www.w3.org/TR/2008/REC-rdfa-syntax-20081014
1776 # Microdata. These are specified by
1777 # https://html.spec.whatwg.org/multipage/microdata.html#the-microdata-model
1785 $block = array_merge( $common, [ 'align' ] );
1786 $tablealign = [ 'align', 'valign' ];
1794 'nowrap', # deprecated
1795 'width', # deprecated
1796 'height', # deprecated
1797 'bgcolor', # deprecated
1800 # Numbers refer to sections in HTML 4.01 standard describing the element.
1801 # See: https://www.w3.org/TR/html4/
1805 'center' => $common, # deprecated
1824 'strong' => $common,
1835 'blockquote' => array_merge( $common, [ 'cite' ] ),
1836 'q' => array_merge( $common, [ 'cite' ] ),
1846 'br' => array_merge( $common, [ 'clear' ] ),
1848 # https://www.w3.org/TR/html5/text-level-semantics.html#the-wbr-element
1852 'pre' => array_merge( $common, [ 'width' ] ),
1855 'ins' => array_merge( $common, [ 'cite', 'datetime' ] ),
1856 'del' => array_merge( $common, [ 'cite', 'datetime' ] ),
1859 'ul' => array_merge( $common, [ 'type' ] ),
1860 'ol' => array_merge( $common, [ 'type', 'start', 'reversed' ] ),
1861 'li' => array_merge( $common, [ 'type', 'value' ] ),
1869 'table' => array_merge( $common,
1870 [ 'summary', 'width', 'border', 'frame',
1871 'rules', 'cellspacing', 'cellpadding',
1876 'caption' => $block,
1884 'colgroup' => array_merge( $common, [ 'span' ] ),
1885 'col' => array_merge( $common, [ 'span' ] ),
1888 'tr' => array_merge( $common, [ 'bgcolor' ], $tablealign ),
1891 'td' => array_merge( $common, $tablecell, $tablealign ),
1892 'th' => array_merge( $common, $tablecell, $tablealign ),
1895 # NOTE: <a> is not allowed directly, but the attrib
1896 # whitelist is used from the Parser object
1897 'a' => array_merge( $common, [ 'href', 'rel', 'rev' ] ), # rel/rev esp. for RDFa
1900 # Not usually allowed, but may be used for extension-style hooks
1901 # such as <math> when it is rasterized, or if $wgAllowImageTag is
1903 'img' => array_merge( $common, [ 'alt', 'src', 'width', 'height', 'srcset' ] ),
1905 'video' => array_merge( $common, [ 'poster', 'controls', 'preload', 'width', 'height' ] ),
1906 'source' => array_merge( $common, [ 'type', 'src' ] ),
1907 'track' => array_merge( $common, [ 'type', 'src', 'srclang', 'kind', 'label' ] ),
1915 'strike' => $common,
1920 'font' => array_merge( $common, [ 'size', 'color', 'face' ] ),
1924 'hr' => array_merge( $common, [ 'width' ] ),
1926 # HTML Ruby annotation text module, simple ruby only.
1927 # https://www.w3.org/TR/html5/text-level-semantics.html#the-ruby-element
1932 'rt' => $common, # array_merge( $common, array( 'rbspan' ) ),
1935 # MathML root element, where used for extensions
1936 # 'title' may not be 100% valid here; it's XHTML
1937 # https://www.w3.org/TR/REC-MathML/
1938 'math' => [ 'class', 'style', 'id', 'title' ],
1940 // HTML 5 section 4.5
1941 'figure' => $common,
1942 'figcaption' => $common,
1944 # HTML 5 section 4.6
1947 # HTML5 elements, defined by:
1948 # https://html.spec.whatwg.org/multipage/semantics.html#the-data-element
1949 'data' => array_merge( $common, [ 'value' ] ),
1950 'time' => array_merge( $common, [ 'datetime' ] ),
1953 // meta and link are only permitted by removeHTMLtags when Microdata
1954 // is enabled so we don't bother adding a conditional to hide these
1955 // Also meta and link are only valid in WikiText as Microdata elements
1956 // (ie: validateTag rejects tags missing the attributes needed for Microdata)
1957 // So we don't bother including $common attributes that have no purpose.
1958 'meta' => [ 'itemprop', 'content' ],
1959 'link' => [ 'itemprop', 'href', 'title' ],
1966 * Take a fragment of (potentially invalid) HTML and return
1967 * a version with any tags removed, encoded as plain text.
1969 * Warning: this return value must be further escaped for literal
1970 * inclusion in HTML output as of 1.10!
1972 * @param string $html HTML fragment
1975 static function stripAllTags( $html ) {
1976 // Use RemexHtml to tokenize $html and extract the text
1977 $handler = new RemexStripTagHandler
;
1978 $tokenizer = new RemexHtml\Tokenizer\
Tokenizer( $handler, $html, [
1979 'ignoreErrors' => true,
1980 // don't ignore char refs, we want them to be decoded
1981 'ignoreNulls' => true,
1982 'skipPreprocess' => true,
1984 $tokenizer->execute();
1985 $text = $handler->getResult();
1987 $text = self
::normalizeWhitespace( $text );
1992 * Hack up a private DOCTYPE with HTML's standard entity declarations.
1993 * PHP 4 seemed to know these if you gave it an HTML doctype, but
1996 * Use for passing XHTML fragments to PHP's XML parsing functions
2000 static function hackDocType() {
2001 $out = "<!DOCTYPE html [\n";
2002 foreach ( self
::$htmlEntities as $entity => $codepoint ) {
2003 $out .= "<!ENTITY $entity \"&#$codepoint;\">";
2010 * @param string $url
2011 * @return mixed|string
2013 static function cleanUrl( $url ) {
2014 # Normalize any HTML entities in input. They will be
2015 # re-escaped by makeExternalLink().
2016 $url = self
::decodeCharReferences( $url );
2018 # Escape any control characters introduced by the above step
2019 $url = preg_replace_callback( '/[\][<>"\\x00-\\x20\\x7F\|]/',
2020 [ __CLASS__
, 'cleanUrlCallback' ], $url );
2022 # Validate hostname portion
2024 if ( preg_match( '!^([^:]+:)(//[^/]+)?(.*)$!iD', $url, $matches ) ) {
2025 list( /* $whole */, $protocol, $host, $rest ) = $matches;
2027 // Characters that will be ignored in IDNs.
2028 // https://tools.ietf.org/html/rfc3454#section-3.1
2029 // Strip them before further processing so blacklists and such work.
2031 \\s| # general whitespace
2032 \xc2\xad| # 00ad SOFT HYPHEN
2033 \xe1\xa0\x86| # 1806 MONGOLIAN TODO SOFT HYPHEN
2034 \xe2\x80\x8b| # 200b ZERO WIDTH SPACE
2035 \xe2\x81\xa0| # 2060 WORD JOINER
2036 \xef\xbb\xbf| # feff ZERO WIDTH NO-BREAK SPACE
2037 \xcd\x8f| # 034f COMBINING GRAPHEME JOINER
2038 \xe1\xa0\x8b| # 180b MONGOLIAN FREE VARIATION SELECTOR ONE
2039 \xe1\xa0\x8c| # 180c MONGOLIAN FREE VARIATION SELECTOR TWO
2040 \xe1\xa0\x8d| # 180d MONGOLIAN FREE VARIATION SELECTOR THREE
2041 \xe2\x80\x8c| # 200c ZERO WIDTH NON-JOINER
2042 \xe2\x80\x8d| # 200d ZERO WIDTH JOINER
2043 [\xef\xb8\x80-\xef\xb8\x8f] # fe00-fe0f VARIATION SELECTOR-1-16
2046 $host = preg_replace( $strip, '', $host );
2048 // IPv6 host names are bracketed with []. Url-decode these.
2049 if ( substr_compare( "//%5B", $host, 0, 5 ) === 0 &&
2050 preg_match( '!^//%5B([0-9A-Fa-f:.]+)%5D((:\d+)?)$!', $host, $matches )
2052 $host = '//[' . $matches[1] . ']' . $matches[2];
2055 // @todo FIXME: Validate hostnames here
2057 return $protocol . $host . $rest;
2064 * @param array $matches
2067 static function cleanUrlCallback( $matches ) {
2068 return urlencode( $matches[0] );
2072 * Does a string look like an e-mail address?
2074 * This validates an email address using an HTML5 specification found at:
2075 * http://www.whatwg.org/html/states-of-the-type-attribute.html#valid-e-mail-address
2076 * Which as of 2011-01-24 says:
2078 * A valid e-mail address is a string that matches the ABNF production
2079 * 1*( atext / "." ) "@" ldh-str *( "." ldh-str ) where atext is defined
2080 * in RFC 5322 section 3.2.3, and ldh-str is defined in RFC 1034 section
2083 * This function is an implementation of the specification as requested in
2086 * Client-side forms will use the same standard validation rules via JS or
2087 * HTML 5 validation; additional restrictions can be enforced server-side
2088 * by extensions via the 'isValidEmailAddr' hook.
2090 * Note that this validation doesn't 100% match RFC 2822, but is believed
2091 * to be liberal enough for wide use. Some invalid addresses will still
2092 * pass validation here.
2096 * @param string $addr E-mail address
2099 public static function validateEmail( $addr ) {
2101 if ( !Hooks
::run( 'isValidEmailAddr', [ $addr, &$result ] ) ) {
2105 // Please note strings below are enclosed in brackets [], this make the
2106 // hyphen "-" a range indicator. Hence it is double backslashed below.
2108 $rfc5322_atext = "a-z0-9!#$%&'*+\\-\/=?^_`{|}~";
2109 $rfc1034_ldh_str = "a-z0-9\\-";
2111 $html5_email_regexp = "/
2113 [$rfc5322_atext\\.]+ # user part which is liberal :p
2115 [$rfc1034_ldh_str]+ # First domain part
2116 (\\.[$rfc1034_ldh_str]+)* # Following part prefixed with a dot
2118 /ix"; // case Insensitive, eXtended
2120 return (bool)preg_match( $html5_email_regexp, $addr );