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
28 * HTML sanitizer for MediaWiki
33 * Regular expression to match various types of character references in
34 * Sanitizer::normalizeCharReferences and Sanitizer::decodeCharReferences
36 const CHAR_REFS_REGEX
=
37 '/&([A-Za-z0-9\x80-\xff]+);
39 |&\#[xX]([0-9A-Fa-f]+);
43 * Acceptable tag name charset from HTML5 parsing spec
44 * http://www.w3.org/TR/html5/syntax.html#tag-open-state
46 const ELEMENT_BITS_REGEX
= '!^(/?)([A-Za-z][^\t\n\v />\0]*+)([^>]*?)(/?>)([^<]*)$!';
49 * Blacklist for evil uris like javascript:
50 * WARNING: DO NOT use this in any place that actually requires blacklisting
51 * for security reasons. There are NUMEROUS[1] ways to bypass blacklisting, the
52 * only way to be secure from javascript: uri based xss vectors is to whitelist
53 * things that you know are safe and deny everything else.
54 * [1]: http://ha.ckers.org/xss.html
56 const EVIL_URI_PATTERN
= '!(^|\s|\*/\s*)(javascript|vbscript)([^\w]|$)!i';
57 const XMLNS_ATTRIBUTE_PATTERN
= "/^xmlns:[:A-Z_a-z-.0-9]+$/";
60 * List of all named character entities defined in HTML 4.01
61 * http://www.w3.org/TR/html4/sgml/entities.html
62 * As well as ' which is only defined starting in XHTML1.
64 private static $htmlEntities = array(
80 'apos' => 39, // New in XHTML & HTML 5; avoid in output for compatibility with IE.
321 * Character entity aliases accepted by MediaWiki
323 private static $htmlEntityAliases = array(
329 * Lazy-initialised attributes regex, see getAttribsRegex()
331 private static $attribsRegex;
334 * Regular expression to match HTML/XML attribute pairs within a tag.
335 * Allows some... latitude.
336 * Used in Sanitizer::fixTagAttributes and Sanitizer::decodeTagAttributes
339 static function getAttribsRegex() {
340 if ( self
::$attribsRegex === null ) {
341 $attribFirst = '[:A-Z_a-z0-9]';
342 $attrib = '[:A-Z_a-z-.0-9]';
343 $space = '[\x09\x0a\x0d\x20]';
344 self
::$attribsRegex =
345 "/(?:^|$space)({$attribFirst}{$attrib}*)
348 # The attribute value: quoted or alone
351 | ([a-zA-Z0-9!#$%&()*,\\-.\\/:;<>?@[\\]^_`{|}~]+)
352 | (\#[0-9a-fA-F]+) # Technically wrong, but lots of
353 # colors are specified like this.
354 # We'll be normalizing it.
358 return self
::$attribsRegex;
362 * Return the various lists of recognized tags
363 * @param array $extratags For any extra tags to include
364 * @param array $removetags For any tags (default or extra) to exclude
367 public static function getRecognizedTagData( $extratags = array(), $removetags = array() ) {
368 global $wgAllowMicrodataAttributes, $wgAllowImageTag;
370 static $htmlpairsStatic, $htmlsingle, $htmlsingleonly, $htmlnest, $tabletags,
371 $htmllist, $listtags, $htmlsingleallowed, $htmlelementsStatic, $staticInitialised;
373 // Base our staticInitialised variable off of the global config state so that if the globals
374 // are changed (like in the screwed up test system) we will re-initialise the settings.
375 $globalContext = implode( '-', compact( 'wgAllowMicrodataAttributes', 'wgAllowImageTag' ) );
376 if ( !$staticInitialised ||
$staticInitialised != $globalContext ) {
377 $htmlpairsStatic = array( # Tags that must be closed
378 'b', 'bdi', 'del', 'i', 'ins', 'u', 'font', 'big', 'small', 'sub', 'sup', 'h1',
379 'h2', 'h3', 'h4', 'h5', 'h6', 'cite', 'code', 'em', 's',
380 'strike', 'strong', 'tt', 'var', 'div', 'center',
381 'blockquote', 'ol', 'ul', 'dl', 'table', 'caption', 'pre',
382 'ruby', 'rb', 'rp', 'rt', 'rtc', 'p', 'span', 'abbr', 'dfn',
383 'kbd', 'samp', 'data', 'time', 'mark'
386 'br', 'wbr', 'hr', 'li', 'dt', 'dd'
388 $htmlsingleonly = array( # Elements that cannot have close tags
391 if ( $wgAllowMicrodataAttributes ) {
392 $htmlsingle[] = $htmlsingleonly[] = 'meta';
393 $htmlsingle[] = $htmlsingleonly[] = 'link';
395 $htmlnest = array( # Tags that can be nested--??
396 'table', 'tr', 'td', 'th', 'div', 'blockquote', 'ol', 'ul',
397 'li', 'dl', 'dt', 'dd', 'font', 'big', 'small', 'sub', 'sup', 'span',
398 'var', 'kbd', 'samp', 'em', 'strong', 'q', 'ruby', 'bdo'
400 $tabletags = array( # Can only appear inside table, we will close them
403 $htmllist = array( # Tags used by list
406 $listtags = array( # Tags that can appear in a list
410 if ( $wgAllowImageTag ) {
411 $htmlsingle[] = 'img';
412 $htmlsingleonly[] = 'img';
415 $htmlsingleallowed = array_unique( array_merge( $htmlsingle, $tabletags ) );
416 $htmlelementsStatic = array_unique( array_merge( $htmlsingle, $htmlpairsStatic, $htmlnest ) );
418 # Convert them all to hashtables for faster lookup
419 $vars = array( 'htmlpairsStatic', 'htmlsingle', 'htmlsingleonly', 'htmlnest', 'tabletags',
420 'htmllist', 'listtags', 'htmlsingleallowed', 'htmlelementsStatic' );
421 foreach ( $vars as $var ) {
422 $
$var = array_flip( $
$var );
424 $staticInitialised = $globalContext;
427 # Populate $htmlpairs and $htmlelements with the $extratags and $removetags arrays
428 $extratags = array_flip( $extratags );
429 $removetags = array_flip( $removetags );
430 $htmlpairs = array_merge( $extratags, $htmlpairsStatic );
431 $htmlelements = array_diff_key( array_merge( $extratags, $htmlelementsStatic ), $removetags );
434 'htmlpairs' => $htmlpairs,
435 'htmlsingle' => $htmlsingle,
436 'htmlsingleonly' => $htmlsingleonly,
437 'htmlnest' => $htmlnest,
438 'tabletags' => $tabletags,
439 'htmllist' => $htmllist,
440 'listtags' => $listtags,
441 'htmlsingleallowed' => $htmlsingleallowed,
442 'htmlelements' => $htmlelements,
447 * Cleans up HTML, removes dangerous tags and attributes, and
448 * removes HTML comments
449 * @param string $text
450 * @param callable $processCallback Callback to do any variable or parameter
451 * replacements in HTML attribute values
452 * @param array|bool $args Arguments for the processing callback
453 * @param array $extratags For any extra tags to include
454 * @param array $removetags For any tags (default or extra) to exclude
457 public static function removeHTMLtags( $text, $processCallback = null,
458 $args = array(), $extratags = array(), $removetags = array()
462 extract( self
::getRecognizedTagData( $extratags, $removetags ) );
464 # Remove HTML comments
465 $text = Sanitizer
::removeHTMLcomments( $text );
466 $bits = explode( '<', $text );
467 $text = str_replace( '>', '>', array_shift( $bits ) );
469 $tagstack = $tablestack = array();
470 foreach ( $bits as $x ) {
472 # $slash: Does the current element start with a '/'?
473 # $t: Current element name
474 # $params: String between element name and >
475 # $brace: Ending '>' or '/>'
476 # $rest: Everything until the next element of $bits
477 if ( preg_match( self
::ELEMENT_BITS_REGEX
, $x, $regs ) ) {
478 list( /* $qbar */, $slash, $t, $params, $brace, $rest ) = $regs;
480 $slash = $t = $params = $brace = $rest = null;
484 if ( isset( $htmlelements[$t = strtolower( $t )] ) ) {
486 if ( $slash && isset( $htmlsingleonly[$t] ) ) {
488 } elseif ( $slash ) {
489 # Closing a tag... is it the one we just opened?
490 MediaWiki\
suppressWarnings();
491 $ot = array_pop( $tagstack );
492 MediaWiki\restoreWarnings
();
495 if ( isset( $htmlsingleallowed[$ot] ) ) {
496 # Pop all elements with an optional close tag
497 # and see if we find a match below them
499 array_push( $optstack, $ot );
500 MediaWiki\
suppressWarnings();
501 $ot = array_pop( $tagstack );
502 MediaWiki\restoreWarnings
();
503 while ( $ot != $t && isset( $htmlsingleallowed[$ot] ) ) {
504 array_push( $optstack, $ot );
505 MediaWiki\
suppressWarnings();
506 $ot = array_pop( $tagstack );
507 MediaWiki\restoreWarnings
();
510 # No match. Push the optional elements back again
512 MediaWiki\
suppressWarnings();
513 $ot = array_pop( $optstack );
514 MediaWiki\restoreWarnings
();
516 array_push( $tagstack, $ot );
517 MediaWiki\
suppressWarnings();
518 $ot = array_pop( $optstack );
519 MediaWiki\restoreWarnings
();
523 MediaWiki\
suppressWarnings();
524 array_push( $tagstack, $ot );
525 MediaWiki\restoreWarnings
();
527 # <li> can be nested in <ul> or <ol>, skip those cases:
528 if ( !isset( $htmllist[$ot] ) ||
!isset( $listtags[$t] ) ) {
533 if ( $t == 'table' ) {
534 $tagstack = array_pop( $tablestack );
539 # Keep track for later
540 if ( isset( $tabletags[$t] ) && !in_array( 'table', $tagstack ) ) {
542 } elseif ( in_array( $t, $tagstack ) && !isset( $htmlnest[$t] ) ) {
544 # Is it a self closed htmlpair ? (bug 5487)
545 } elseif ( $brace == '/>' && isset( $htmlpairs[$t] ) ) {
547 } elseif ( isset( $htmlsingleonly[$t] ) ) {
548 # Hack to force empty tag for unclosable elements
550 } elseif ( isset( $htmlsingle[$t] ) ) {
551 # Hack to not close $htmlsingle tags
553 # Still need to push this optionally-closed tag to
554 # the tag stack so that we can match end tags
555 # instead of marking them as bad.
556 array_push( $tagstack, $t );
557 } elseif ( isset( $tabletags[$t] ) && in_array( $t, $tagstack ) ) {
558 // New table tag but forgot to close the previous one
561 if ( $t == 'table' ) {
562 array_push( $tablestack, $tagstack );
565 array_push( $tagstack, $t );
568 # Replace any variables or template parameters with
570 if ( is_callable( $processCallback ) ) {
571 call_user_func_array( $processCallback, array( &$params, $args ) );
574 if ( !Sanitizer
::validateTag( $params, $t ) ) {
578 # Strip non-approved attributes from the tag
579 $newparams = Sanitizer
::fixTagAttributes( $params, $t );
582 $rest = str_replace( '>', '>', $rest );
583 $close = ( $brace == '/>' && !$slash ) ?
' /' : '';
584 $text .= "<$slash$t$newparams$close>$rest";
588 $text .= '<' . str_replace( '>', '>', $x );
590 # Close off any remaining tags
591 while ( is_array( $tagstack ) && ( $t = array_pop( $tagstack ) ) ) {
593 if ( $t == 'table' ) {
594 $tagstack = array_pop( $tablestack );
598 # this might be possible using tidy itself
599 foreach ( $bits as $x ) {
600 if ( preg_match( self
::ELEMENT_BITS_REGEX
, $x, $regs ) ) {
601 list( /* $qbar */, $slash, $t, $params, $brace, $rest ) = $regs;
604 if ( isset( $htmlelements[$t = strtolower( $t )] ) ) {
605 if ( is_callable( $processCallback ) ) {
606 call_user_func_array( $processCallback, array( &$params, $args ) );
609 if ( !Sanitizer
::validateTag( $params, $t ) ) {
613 $newparams = Sanitizer
::fixTagAttributes( $params, $t );
615 $rest = str_replace( '>', '>', $rest );
616 $text .= "<$slash$t$newparams$brace$rest";
621 $text .= '<' . str_replace( '>', '>', $x );
628 * Remove '<!--', '-->', and everything between.
629 * To avoid leaving blank lines, when a comment is both preceded
630 * and followed by a newline (ignoring spaces), trim leading and
631 * trailing spaces and one of the newlines.
633 * @param string $text
636 public static function removeHTMLcomments( $text ) {
637 while ( ( $start = strpos( $text, '<!--' ) ) !== false ) {
638 $end = strpos( $text, '-->', $start +
4 );
639 if ( $end === false ) {
640 # Unterminated comment; bail out
646 # Trim space and newline if the comment is both
647 # preceded and followed by a newline
648 $spaceStart = max( $start - 1, 0 );
649 $spaceLen = $end - $spaceStart;
650 while ( substr( $text, $spaceStart, 1 ) === ' ' && $spaceStart > 0 ) {
654 while ( substr( $text, $spaceStart +
$spaceLen, 1 ) === ' ' ) {
657 if ( substr( $text, $spaceStart, 1 ) === "\n"
658 && substr( $text, $spaceStart +
$spaceLen, 1 ) === "\n" ) {
659 # Remove the comment, leading and trailing
660 # spaces, and leave only one newline.
661 $text = substr_replace( $text, "\n", $spaceStart, $spaceLen +
1 );
663 # Remove just the comment.
664 $text = substr_replace( $text, '', $start, $end - $start );
671 * Takes attribute names and values for a tag and the tag name and
672 * validates that the tag is allowed to be present.
673 * This DOES NOT validate the attributes, nor does it validate the
674 * tags themselves. This method only handles the special circumstances
675 * where we may want to allow a tag within content but ONLY when it has
676 * specific attributes set.
678 * @param string $params
679 * @param string $element
682 static function validateTag( $params, $element ) {
683 $params = Sanitizer
::decodeTagAttributes( $params );
685 if ( $element == 'meta' ||
$element == 'link' ) {
686 if ( !isset( $params['itemprop'] ) ) {
687 // <meta> and <link> must have an itemprop="" otherwise they are not valid or safe in content
690 if ( $element == 'meta' && !isset( $params['content'] ) ) {
691 // <meta> must have a content="" for the itemprop
694 if ( $element == 'link' && !isset( $params['href'] ) ) {
695 // <link> must have an associated href=""
704 * Take an array of attribute names and values and normalize or discard
705 * illegal values for the given element type.
707 * - Discards attributes not on a whitelist for the given element
708 * - Unsafe style attributes are discarded
709 * - Invalid id attributes are re-encoded
711 * @param array $attribs
712 * @param string $element
715 * @todo Check for legal values where the DTD limits things.
716 * @todo Check for unique id attribute :P
718 static function validateTagAttributes( $attribs, $element ) {
719 return Sanitizer
::validateAttributes( $attribs,
720 Sanitizer
::attributeWhitelist( $element ) );
724 * Take an array of attribute names and values and normalize or discard
725 * illegal values for the given whitelist.
727 * - Discards attributes not the given whitelist
728 * - Unsafe style attributes are discarded
729 * - Invalid id attributes are re-encoded
731 * @param array $attribs
732 * @param array $whitelist List of allowed attribute names
735 * @todo Check for legal values where the DTD limits things.
736 * @todo Check for unique id attribute :P
738 static function validateAttributes( $attribs, $whitelist ) {
739 global $wgAllowRdfaAttributes, $wgAllowMicrodataAttributes;
741 $whitelist = array_flip( $whitelist );
742 $hrefExp = '/^(' . wfUrlProtocols() . ')[^\s]+$/';
745 foreach ( $attribs as $attribute => $value ) {
746 #allow XML namespace declaration if RDFa is enabled
747 if ( $wgAllowRdfaAttributes && preg_match( self
::XMLNS_ATTRIBUTE_PATTERN
, $attribute ) ) {
748 if ( !preg_match( self
::EVIL_URI_PATTERN
, $value ) ) {
749 $out[$attribute] = $value;
755 # Allow any attribute beginning with "data-"
756 if ( !preg_match( '/^data-(?!ooui)/i', $attribute ) && !isset( $whitelist[$attribute] ) ) {
760 # Strip javascript "expression" from stylesheets.
761 # http://msdn.microsoft.com/workshop/author/dhtml/overview/recalc.asp
762 if ( $attribute == 'style' ) {
763 $value = Sanitizer
::checkCss( $value );
766 if ( $attribute === 'id' ) {
767 $value = Sanitizer
::escapeId( $value, 'noninitial' );
771 # http://www.w3.org/TR/wai-aria/
772 # http://www.whatwg.org/html/elements.html#wai-aria
773 # For now we only support role="presentation" until we work out what roles should be
774 # usable by content and we ensure that our code explicitly rejects patterns that
775 # violate HTML5's ARIA restrictions.
776 if ( $attribute === 'role' && $value !== 'presentation' ) {
780 // RDFa and microdata properties allow URLs, URIs and/or CURIs.
781 // Check them for sanity.
782 if ( $attribute === 'rel' ||
$attribute === 'rev'
784 ||
$attribute === 'about' ||
$attribute === 'property'
785 ||
$attribute === 'resource' ||
$attribute === 'datatype'
786 ||
$attribute === 'typeof'
788 ||
$attribute === 'itemid' ||
$attribute === 'itemprop'
789 ||
$attribute === 'itemref' ||
$attribute === 'itemscope'
790 ||
$attribute === 'itemtype'
792 //Paranoia. Allow "simple" values but suppress javascript
793 if ( preg_match( self
::EVIL_URI_PATTERN
, $value ) ) {
798 # NOTE: even though elements using href/src are not allowed directly, supply
799 # validation code that can be used by tag hook handlers, etc
800 if ( $attribute === 'href' ||
$attribute === 'src' ) {
801 if ( !preg_match( $hrefExp, $value ) ) {
802 continue; //drop any href or src attributes not using an allowed protocol.
803 // NOTE: this also drops all relative URLs
807 // If this attribute was previously set, override it.
808 // Output should only have one attribute of each name.
809 $out[$attribute] = $value;
812 if ( $wgAllowMicrodataAttributes ) {
813 # itemtype, itemid, itemref don't make sense without itemscope
814 if ( !array_key_exists( 'itemscope', $out ) ) {
815 unset( $out['itemtype'] );
816 unset( $out['itemid'] );
817 unset( $out['itemref'] );
819 # TODO: Strip itemprop if we aren't descendants of an itemscope or pointed to by an itemref.
825 * Merge two sets of HTML attributes. Conflicting items in the second set
826 * will override those in the first, except for 'class' attributes which
827 * will be combined (if they're both strings).
829 * @todo implement merging for other attributes such as style
834 static function mergeAttributes( $a, $b ) {
835 $out = array_merge( $a, $b );
836 if ( isset( $a['class'] ) && isset( $b['class'] )
837 && is_string( $a['class'] ) && is_string( $b['class'] )
838 && $a['class'] !== $b['class']
840 $classes = preg_split( '/\s+/', "{$a['class']} {$b['class']}",
841 -1, PREG_SPLIT_NO_EMPTY
);
842 $out['class'] = implode( ' ', array_unique( $classes ) );
848 * Normalize CSS into a format we can easily search for hostile input
849 * - decode character references
850 * - decode escape sequences
851 * - convert characters that IE6 interprets into ascii
852 * - remove comments, unless the entire value is one single comment
853 * @param string $value the css string
854 * @return string normalized css
856 public static function normalizeCss( $value ) {
858 // Decode character references like {
859 $value = Sanitizer
::decodeCharReferences( $value );
861 // Decode escape sequences and line continuation
862 // See the grammar in the CSS 2 spec, appendix D.
863 // This has to be done AFTER decoding character references.
864 // This means it isn't possible for this function to return
865 // unsanitized escape sequences. It is possible to manufacture
866 // input that contains character references that decode to
867 // escape sequences that decode to character references, but
868 // it's OK for the return value to contain character references
869 // because the caller is supposed to escape those anyway.
871 if ( !$decodeRegex ) {
872 $space = '[\\x20\\t\\r\\n\\f]';
873 $nl = '(?:\\n|\\r\\n|\\r|\\f)';
875 $decodeRegex = "/ $backslash
877 ($nl) | # 1. Line continuation
878 ([0-9A-Fa-f]{1,6})$space? | # 2. character number
879 (.) | # 3. backslash cancelling special meaning
880 () | # 4. backslash at end of string
883 $value = preg_replace_callback( $decodeRegex,
884 array( __CLASS__
, 'cssDecodeCallback' ), $value );
886 // Normalize Halfwidth and Fullwidth Unicode block that IE6 might treat as ascii
887 $value = preg_replace_callback(
888 '/[!-[]-z]/u', // U+FF01 to U+FF5A, excluding U+FF3C (bug 58088)
889 function ( $matches ) {
890 $cp = UtfNormal\Utils
::utf8ToCodepoint( $matches[0] );
891 if ( $cp === false ) {
894 return chr( $cp - 65248 ); // ASCII range \x21-\x7A
899 // Convert more characters IE6 might treat as ascii
900 // U+0280, U+0274, U+207F, U+029F, U+026A, U+207D, U+208D
901 $value = str_replace(
902 array( 'ʀ', 'ɴ', 'ⁿ', 'ʟ', 'ɪ', '⁽', '₍' ),
903 array( 'r', 'n', 'n', 'l', 'i', '(', '(' ),
907 // Let the value through if it's nothing but a single comment, to
908 // allow other functions which may reject it to pass some error
910 if ( !preg_match( '! ^ \s* /\* [^*\\/]* \*/ \s* $ !x', $value ) ) {
911 // Remove any comments; IE gets token splitting wrong
912 // This must be done AFTER decoding character references and
913 // escape sequences, because those steps can introduce comments
914 // This step cannot introduce character references or escape
915 // sequences, because it replaces comments with spaces rather
916 // than removing them completely.
917 $value = StringUtils
::delimiterReplace( '/*', '*/', ' ', $value );
919 // Remove anything after a comment-start token, to guard against
920 // incorrect client implementations.
921 $commentPos = strpos( $value, '/*' );
922 if ( $commentPos !== false ) {
923 $value = substr( $value, 0, $commentPos );
927 // S followed by repeat, iteration, or prolonged sound marks,
928 // which IE will treat as "ss"
929 $value = preg_replace(
931 \xE3\x80\xB1 | # U+3031
932 \xE3\x82\x9D | # U+309D
933 \xE3\x83\xBC | # U+30FC
934 \xE3\x83\xBD | # U+30FD
935 \xEF\xB9\xBC | # U+FE7C
936 \xEF\xB9\xBD | # U+FE7D
937 \xEF\xBD\xB0 # U+FF70
948 * Pick apart some CSS and check it for forbidden or unsafe structures.
949 * Returns a sanitized string. This sanitized string will have
950 * character references and escape sequences decoded and comments
951 * stripped (unless it is itself one valid comment, in which case the value
952 * will be passed through). If the input is just too evil, only a comment
953 * complaining about evilness will be returned.
955 * Currently URL references, 'expression', 'tps' are forbidden.
957 * NOTE: Despite the fact that character references are decoded, the
958 * returned string may contain character references given certain
959 * clever input strings. These character references must
960 * be escaped before the return value is embedded in HTML.
962 * @param string $value
965 static function checkCss( $value ) {
966 $value = self
::normalizeCss( $value );
968 // Reject problematic keywords and control characters
969 if ( preg_match( '/[\000-\010\013\016-\037\177]/', $value ) ) {
970 return '/* invalid control char */';
971 } elseif ( preg_match(
982 return '/* insecure input */';
988 * @param array $matches
991 static function cssDecodeCallback( $matches ) {
992 if ( $matches[1] !== '' ) {
995 } elseif ( $matches[2] !== '' ) {
996 $char = UtfNormal\Utils
::codepointToUtf8( hexdec( $matches[2] ) );
997 } elseif ( $matches[3] !== '' ) {
1002 if ( $char == "\n" ||
$char == '"' ||
$char == "'" ||
$char == '\\' ) {
1003 // These characters need to be escaped in strings
1004 // Clean up the escape sequence to avoid parsing errors by clients
1005 return '\\' . dechex( ord( $char ) ) . ' ';
1007 // Decode unnecessary escape
1013 * Take a tag soup fragment listing an HTML element's attributes
1014 * and normalize it to well-formed XML, discarding unwanted attributes.
1015 * Output is safe for further wikitext processing, with escaping of
1016 * values that could trigger problems.
1018 * - Normalizes attribute names to lowercase
1019 * - Discards attributes not on a whitelist for the given element
1020 * - Turns broken or invalid entities into plaintext
1021 * - Double-quotes all attribute values
1022 * - Attributes without values are given the name as attribute
1023 * - Double attributes are discarded
1024 * - Unsafe style attributes are discarded
1025 * - Prepends space if there are attributes.
1027 * @param string $text
1028 * @param string $element
1031 static function fixTagAttributes( $text, $element ) {
1032 if ( trim( $text ) == '' ) {
1036 $decoded = Sanitizer
::decodeTagAttributes( $text );
1037 $stripped = Sanitizer
::validateTagAttributes( $decoded, $element );
1039 return Sanitizer
::safeEncodeTagAttributes( $stripped );
1043 * Encode an attribute value for HTML output.
1044 * @param string $text
1045 * @return string HTML-encoded text fragment
1047 static function encodeAttribute( $text ) {
1048 $encValue = htmlspecialchars( $text, ENT_QUOTES
);
1050 // Whitespace is normalized during attribute decoding,
1051 // so if we've been passed non-spaces we must encode them
1052 // ahead of time or they won't be preserved.
1053 $encValue = strtr( $encValue, array(
1063 * Encode an attribute value for HTML tags, with extra armoring
1064 * against further wiki processing.
1065 * @param string $text
1066 * @return string HTML-encoded text fragment
1068 static function safeEncodeAttribute( $text ) {
1069 $encValue = Sanitizer
::encodeAttribute( $text );
1071 # Templates and links may be expanded in later parsing,
1072 # creating invalid or dangerous output. Suppress this.
1073 $encValue = strtr( $encValue, array(
1074 '<' => '<', // This should never happen,
1075 '>' => '>', // we've received invalid input
1076 '"' => '"', // which should have been escaped.
1079 "''" => '''',
1080 'ISBN' => 'ISBN',
1082 'PMID' => 'PMID',
1088 $encValue = preg_replace_callback(
1089 '/((?i)' . wfUrlProtocols() . ')/',
1090 array( 'Sanitizer', 'armorLinksCallback' ),
1096 * Given a value, escape it so that it can be used in an id attribute and
1097 * return it. This will use HTML5 validation if $wgExperimentalHtmlIds is
1098 * true, allowing anything but ASCII whitespace. Otherwise it will use
1099 * HTML 4 rules, which means a narrow subset of ASCII, with bad characters
1100 * escaped with lots of dots.
1102 * To ensure we don't have to bother escaping anything, we also strip ', ",
1103 * & even if $wgExperimentalIds is true. TODO: Is this the best tactic?
1104 * We also strip # because it upsets IE, and % because it could be
1105 * ambiguous if it's part of something that looks like a percent escape
1106 * (which don't work reliably in fragments cross-browser).
1108 * @see http://www.w3.org/TR/html401/types.html#type-name Valid characters
1109 * in the id and name attributes
1110 * @see http://www.w3.org/TR/html401/struct/links.html#h-12.2.3 Anchors with
1112 * @see http://www.whatwg.org/html/elements.html#the-id-attribute
1113 * HTML5 definition of id attribute
1115 * @param string $id Id to escape
1116 * @param string|array $options String or array of strings (default is array()):
1117 * 'noninitial': This is a non-initial fragment of an id, not a full id,
1118 * so don't pay attention if the first character isn't valid at the
1119 * beginning of an id. Only matters if $wgExperimentalHtmlIds is
1121 * 'legacy': Behave the way the old HTML 4-based ID escaping worked even
1122 * if $wgExperimentalHtmlIds is used, so we can generate extra
1123 * anchors and links won't break.
1126 static function escapeId( $id, $options = array() ) {
1127 global $wgExperimentalHtmlIds;
1128 $options = (array)$options;
1130 $id = Sanitizer
::decodeCharReferences( $id );
1132 if ( $wgExperimentalHtmlIds && !in_array( 'legacy', $options ) ) {
1133 $id = preg_replace( '/[ \t\n\r\f_\'"&#%]+/', '_', $id );
1134 $id = trim( $id, '_' );
1136 // Must have been all whitespace to start with.
1143 // HTML4-style escaping
1144 static $replace = array(
1149 $id = urlencode( strtr( $id, ' ', '_' ) );
1150 $id = str_replace( array_keys( $replace ), array_values( $replace ), $id );
1152 if ( !preg_match( '/^[a-zA-Z]/', $id ) && !in_array( 'noninitial', $options ) ) {
1153 // Initial character must be a letter!
1160 * Given a value, escape it so that it can be used as a CSS class and
1163 * @todo For extra validity, input should be validated UTF-8.
1165 * @see http://www.w3.org/TR/CSS21/syndata.html Valid characters/format
1167 * @param string $class
1170 static function escapeClass( $class ) {
1171 // Convert ugly stuff to underscores and kill underscores in ugly places
1172 return rtrim( preg_replace(
1173 array( '/(^[0-9\\-])|[\\x00-\\x20!"#$%&\'()*+,.\\/:;<=>?@[\\]^`{|}~]|\\xC2\\xA0/', '/_+/' ),
1179 * Given HTML input, escape with htmlspecialchars but un-escape entities.
1180 * This allows (generally harmless) entities like   to survive.
1182 * @param string $html HTML to escape
1183 * @return string Escaped input
1185 static function escapeHtmlAllowEntities( $html ) {
1186 $html = Sanitizer
::decodeCharReferences( $html );
1187 # It seems wise to escape ' as well as ", as a matter of course. Can't
1189 $html = htmlspecialchars( $html, ENT_QUOTES
);
1194 * Regex replace callback for armoring links against further processing.
1195 * @param array $matches
1198 private static function armorLinksCallback( $matches ) {
1199 return str_replace( ':', ':', $matches[1] );
1203 * Return an associative array of attribute names and values from
1204 * a partial tag string. Attribute names are forces to lowercase,
1205 * character references are decoded to UTF-8 text.
1207 * @param string $text
1210 public static function decodeTagAttributes( $text ) {
1211 if ( trim( $text ) == '' ) {
1217 if ( !preg_match_all(
1218 self
::getAttribsRegex(),
1221 PREG_SET_ORDER
) ) {
1225 foreach ( $pairs as $set ) {
1226 $attribute = strtolower( $set[1] );
1227 $value = Sanitizer
::getTagAttributeCallback( $set );
1229 // Normalize whitespace
1230 $value = preg_replace( '/[\t\r\n ]+/', ' ', $value );
1231 $value = trim( $value );
1233 // Decode character references
1234 $attribs[$attribute] = Sanitizer
::decodeCharReferences( $value );
1240 * Build a partial tag string from an associative array of attribute
1241 * names and values as returned by decodeTagAttributes.
1243 * @param array $assoc_array
1246 public static function safeEncodeTagAttributes( $assoc_array ) {
1248 foreach ( $assoc_array as $attribute => $value ) {
1249 $encAttribute = htmlspecialchars( $attribute );
1250 $encValue = Sanitizer
::safeEncodeAttribute( $value );
1252 $attribs[] = "$encAttribute=\"$encValue\"";
1254 return count( $attribs ) ?
' ' . implode( ' ', $attribs ) : '';
1258 * Pick the appropriate attribute value from a match set from the
1259 * attribs regex matches.
1262 * @throws MWException When tag conditions are not met.
1265 private static function getTagAttributeCallback( $set ) {
1266 if ( isset( $set[6] ) ) {
1267 # Illegal #XXXXXX color with no quotes.
1269 } elseif ( isset( $set[5] ) ) {
1272 } elseif ( isset( $set[4] ) ) {
1275 } elseif ( isset( $set[3] ) ) {
1278 } elseif ( !isset( $set[2] ) ) {
1279 # In XHTML, attributes must have a value.
1280 # For 'reduced' form, return explicitly the attribute name here.
1283 throw new MWException( "Tag conditions not met. This should never happen and is a bug." );
1288 * @param string $text
1291 private static function normalizeWhitespace( $text ) {
1292 return preg_replace(
1293 '/\r\n|[\x20\x0d\x0a\x09]/',
1299 * Normalizes whitespace in a section name, such as might be returned
1300 * by Parser::stripSectionName(), for use in the id's that are used for
1303 * @param string $section
1306 static function normalizeSectionNameWhitespace( $section ) {
1307 return trim( preg_replace( '/[ _]+/', ' ', $section ) );
1311 * Ensure that any entities and character references are legal
1312 * for XML and XHTML specifically. Any stray bits will be
1313 * &-escaped to result in a valid text fragment.
1315 * a. named char refs can only be < > & ", others are
1316 * numericized (this way we're well-formed even without a DTD)
1317 * b. any numeric char refs must be legal chars, not invalid or forbidden
1318 * c. use lower cased "&#x", not "&#X"
1319 * d. fix or reject non-valid attributes
1321 * @param string $text
1325 static function normalizeCharReferences( $text ) {
1326 return preg_replace_callback(
1327 self
::CHAR_REFS_REGEX
,
1328 array( 'Sanitizer', 'normalizeCharReferencesCallback' ),
1333 * @param string $matches
1336 static function normalizeCharReferencesCallback( $matches ) {
1338 if ( $matches[1] != '' ) {
1339 $ret = Sanitizer
::normalizeEntity( $matches[1] );
1340 } elseif ( $matches[2] != '' ) {
1341 $ret = Sanitizer
::decCharReference( $matches[2] );
1342 } elseif ( $matches[3] != '' ) {
1343 $ret = Sanitizer
::hexCharReference( $matches[3] );
1345 if ( is_null( $ret ) ) {
1346 return htmlspecialchars( $matches[0] );
1353 * If the named entity is defined in the HTML 4.0/XHTML 1.0 DTD,
1354 * return the equivalent numeric entity reference (except for the core <
1355 * > & "). If the entity is a MediaWiki-specific alias, returns
1356 * the HTML equivalent. Otherwise, returns HTML-escaped text of
1357 * pseudo-entity source (eg &foo;)
1359 * @param string $name
1362 static function normalizeEntity( $name ) {
1363 if ( isset( self
::$htmlEntityAliases[$name] ) ) {
1364 return '&' . self
::$htmlEntityAliases[$name] . ';';
1365 } elseif ( in_array( $name, array( 'lt', 'gt', 'amp', 'quot' ) ) ) {
1367 } elseif ( isset( self
::$htmlEntities[$name] ) ) {
1368 return '&#' . self
::$htmlEntities[$name] . ';';
1370 return "&$name;";
1375 * @param int $codepoint
1376 * @return null|string
1378 static function decCharReference( $codepoint ) {
1379 $point = intval( $codepoint );
1380 if ( Sanitizer
::validateCodepoint( $point ) ) {
1381 return sprintf( '&#%d;', $point );
1388 * @param int $codepoint
1389 * @return null|string
1391 static function hexCharReference( $codepoint ) {
1392 $point = hexdec( $codepoint );
1393 if ( Sanitizer
::validateCodepoint( $point ) ) {
1394 return sprintf( '&#x%x;', $point );
1401 * Returns true if a given Unicode codepoint is a valid character in XML.
1402 * @param int $codepoint
1405 private static function validateCodepoint( $codepoint ) {
1406 return $codepoint == 0x09
1407 ||
$codepoint == 0x0a
1408 ||
$codepoint == 0x0d
1409 ||
( $codepoint >= 0x20 && $codepoint <= 0xd7ff )
1410 ||
( $codepoint >= 0xe000 && $codepoint <= 0xfffd )
1411 ||
( $codepoint >= 0x10000 && $codepoint <= 0x10ffff );
1415 * Decode any character references, numeric or named entities,
1416 * in the text and return a UTF-8 string.
1418 * @param string $text
1421 public static function decodeCharReferences( $text ) {
1422 return preg_replace_callback(
1423 self
::CHAR_REFS_REGEX
,
1424 array( 'Sanitizer', 'decodeCharReferencesCallback' ),
1429 * Decode any character references, numeric or named entities,
1430 * in the next and normalize the resulting string. (bug 14952)
1432 * This is useful for page titles, not for text to be displayed,
1433 * MediaWiki allows HTML entities to escape normalization as a feature.
1435 * @param string $text Already normalized, containing entities
1436 * @return string Still normalized, without entities
1438 public static function decodeCharReferencesAndNormalize( $text ) {
1440 $text = preg_replace_callback(
1441 self
::CHAR_REFS_REGEX
,
1442 array( 'Sanitizer', 'decodeCharReferencesCallback' ),
1443 $text, /* limit */ -1, $count );
1446 return $wgContLang->normalize( $text );
1453 * @param string $matches
1456 static function decodeCharReferencesCallback( $matches ) {
1457 if ( $matches[1] != '' ) {
1458 return Sanitizer
::decodeEntity( $matches[1] );
1459 } elseif ( $matches[2] != '' ) {
1460 return Sanitizer
::decodeChar( intval( $matches[2] ) );
1461 } elseif ( $matches[3] != '' ) {
1462 return Sanitizer
::decodeChar( hexdec( $matches[3] ) );
1464 # Last case should be an ampersand by itself
1469 * Return UTF-8 string for a codepoint if that is a valid
1470 * character reference, otherwise U+FFFD REPLACEMENT CHARACTER.
1471 * @param int $codepoint
1475 static function decodeChar( $codepoint ) {
1476 if ( Sanitizer
::validateCodepoint( $codepoint ) ) {
1477 return UtfNormal\Utils
::codepointToUtf8( $codepoint );
1479 return UtfNormal\Constants
::UTF8_REPLACEMENT
;
1484 * If the named entity is defined in the HTML 4.0/XHTML 1.0 DTD,
1485 * return the UTF-8 encoding of that character. Otherwise, returns
1486 * pseudo-entity source (eg "&foo;")
1488 * @param string $name
1491 static function decodeEntity( $name ) {
1492 if ( isset( self
::$htmlEntityAliases[$name] ) ) {
1493 $name = self
::$htmlEntityAliases[$name];
1495 if ( isset( self
::$htmlEntities[$name] ) ) {
1496 return UtfNormal\Utils
::codepointToUtf8( self
::$htmlEntities[$name] );
1503 * Fetch the whitelist of acceptable attributes for a given element name.
1505 * @param string $element
1508 static function attributeWhitelist( $element ) {
1509 $list = Sanitizer
::setupAttributeWhitelist();
1510 return isset( $list[$element] )
1516 * Foreach array key (an allowed HTML element), return an array
1517 * of allowed attributes
1520 static function setupAttributeWhitelist() {
1521 global $wgAllowRdfaAttributes, $wgAllowMicrodataAttributes;
1522 static $whitelist, $staticInitialised;
1524 $globalContext = implode( '-', compact( 'wgAllowRdfaAttributes', 'wgAllowMicrodataAttributes' ) );
1526 if ( $whitelist !== null && $staticInitialised == $globalContext ) {
1543 if ( $wgAllowRdfaAttributes ) {
1544 # RDFa attributes as specified in section 9 of
1545 # http://www.w3.org/TR/2008/REC-rdfa-syntax-20081014
1546 $common = array_merge( $common, array(
1547 'about', 'property', 'resource', 'datatype', 'typeof',
1551 if ( $wgAllowMicrodataAttributes ) {
1552 # add HTML5 microdata tags as specified by
1553 # http://www.whatwg.org/html/microdata.html#the-microdata-model
1554 $common = array_merge( $common, array(
1555 'itemid', 'itemprop', 'itemref', 'itemscope', 'itemtype'
1559 $block = array_merge( $common, array( 'align' ) );
1560 $tablealign = array( 'align', 'valign' );
1568 'nowrap', # deprecated
1569 'width', # deprecated
1570 'height', # deprecated
1571 'bgcolor', # deprecated
1574 # Numbers refer to sections in HTML 4.01 standard describing the element.
1575 # See: http://www.w3.org/TR/html4/
1579 'center' => $common, # deprecated
1598 'strong' => $common,
1609 'blockquote' => array_merge( $common, array( 'cite' ) ),
1610 'q' => array_merge( $common, array( 'cite' ) ),
1620 'br' => array_merge( $common, array( 'clear' ) ),
1622 # http://www.whatwg.org/html/text-level-semantics.html#the-wbr-element
1626 'pre' => array_merge( $common, array( 'width' ) ),
1629 'ins' => array_merge( $common, array( 'cite', 'datetime' ) ),
1630 'del' => array_merge( $common, array( 'cite', 'datetime' ) ),
1633 'ul' => array_merge( $common, array( 'type' ) ),
1634 'ol' => array_merge( $common, array( 'type', 'start' ) ),
1635 'li' => array_merge( $common, array( 'type', 'value' ) ),
1643 'table' => array_merge( $common,
1644 array( 'summary', 'width', 'border', 'frame',
1645 'rules', 'cellspacing', 'cellpadding',
1650 'caption' => $block,
1658 'colgroup' => array_merge( $common, array( 'span' ) ),
1659 'col' => array_merge( $common, array( 'span' ) ),
1662 'tr' => array_merge( $common, array( 'bgcolor' ), $tablealign ),
1665 'td' => array_merge( $common, $tablecell, $tablealign ),
1666 'th' => array_merge( $common, $tablecell, $tablealign ),
1669 # NOTE: <a> is not allowed directly, but the attrib
1670 # whitelist is used from the Parser object
1671 'a' => array_merge( $common, array( 'href', 'rel', 'rev' ) ), # rel/rev esp. for RDFa
1674 # Not usually allowed, but may be used for extension-style hooks
1675 # such as <math> when it is rasterized, or if $wgAllowImageTag is
1677 'img' => array_merge( $common, array( 'alt', 'src', 'width', 'height' ) ),
1685 'strike' => $common,
1690 'font' => array_merge( $common, array( 'size', 'color', 'face' ) ),
1694 'hr' => array_merge( $common, array( 'width' ) ),
1696 # HTML Ruby annotation text module, simple ruby only.
1697 # http://www.whatwg.org/html/text-level-semantics.html#the-ruby-element
1702 'rt' => $common, #array_merge( $common, array( 'rbspan' ) ),
1705 # MathML root element, where used for extensions
1706 # 'title' may not be 100% valid here; it's XHTML
1707 # http://www.w3.org/TR/REC-MathML/
1708 'math' => array( 'class', 'style', 'id', 'title' ),
1710 # HTML 5 section 4.6
1713 # HTML5 elements, defined by:
1714 # http://www.whatwg.org/html/
1715 'data' => array_merge( $common, array( 'value' ) ),
1716 'time' => array_merge( $common, array( 'datetime' ) ),
1719 // meta and link are only permitted by removeHTMLtags when Microdata
1720 // is enabled so we don't bother adding a conditional to hide these
1721 // Also meta and link are only valid in WikiText as Microdata elements
1722 // (ie: validateTag rejects tags missing the attributes needed for Microdata)
1723 // So we don't bother including $common attributes that have no purpose.
1724 'meta' => array( 'itemprop', 'content' ),
1725 'link' => array( 'itemprop', 'href' ),
1728 $staticInitialised = $globalContext;
1734 * Take a fragment of (potentially invalid) HTML and return
1735 * a version with any tags removed, encoded as plain text.
1737 * Warning: this return value must be further escaped for literal
1738 * inclusion in HTML output as of 1.10!
1740 * @param string $text HTML fragment
1743 static function stripAllTags( $text ) {
1745 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
1747 # Normalize &entities and whitespace
1748 $text = self
::decodeCharReferences( $text );
1749 $text = self
::normalizeWhitespace( $text );
1755 * Hack up a private DOCTYPE with HTML's standard entity declarations.
1756 * PHP 4 seemed to know these if you gave it an HTML doctype, but
1759 * Use for passing XHTML fragments to PHP's XML parsing functions
1763 static function hackDocType() {
1764 $out = "<!DOCTYPE html [\n";
1765 foreach ( self
::$htmlEntities as $entity => $codepoint ) {
1766 $out .= "<!ENTITY $entity \"&#$codepoint;\">";
1773 * @param string $url
1774 * @return mixed|string
1776 static function cleanUrl( $url ) {
1777 # Normalize any HTML entities in input. They will be
1778 # re-escaped by makeExternalLink().
1779 $url = Sanitizer
::decodeCharReferences( $url );
1781 # Escape any control characters introduced by the above step
1782 $url = preg_replace_callback( '/[\][<>"\\x00-\\x20\\x7F\|]/',
1783 array( __CLASS__
, 'cleanUrlCallback' ), $url );
1785 # Validate hostname portion
1787 if ( preg_match( '!^([^:]+:)(//[^/]+)?(.*)$!iD', $url, $matches ) ) {
1788 list( /* $whole */, $protocol, $host, $rest ) = $matches;
1790 // Characters that will be ignored in IDNs.
1791 // http://tools.ietf.org/html/3454#section-3.1
1792 // Strip them before further processing so blacklists and such work.
1794 \\s| # general whitespace
1795 \xc2\xad| # 00ad SOFT HYPHEN
1796 \xe1\xa0\x86| # 1806 MONGOLIAN TODO SOFT HYPHEN
1797 \xe2\x80\x8b| # 200b ZERO WIDTH SPACE
1798 \xe2\x81\xa0| # 2060 WORD JOINER
1799 \xef\xbb\xbf| # feff ZERO WIDTH NO-BREAK SPACE
1800 \xcd\x8f| # 034f COMBINING GRAPHEME JOINER
1801 \xe1\xa0\x8b| # 180b MONGOLIAN FREE VARIATION SELECTOR ONE
1802 \xe1\xa0\x8c| # 180c MONGOLIAN FREE VARIATION SELECTOR TWO
1803 \xe1\xa0\x8d| # 180d MONGOLIAN FREE VARIATION SELECTOR THREE
1804 \xe2\x80\x8c| # 200c ZERO WIDTH NON-JOINER
1805 \xe2\x80\x8d| # 200d ZERO WIDTH JOINER
1806 [\xef\xb8\x80-\xef\xb8\x8f] # fe00-fe0f VARIATION SELECTOR-1-16
1809 $host = preg_replace( $strip, '', $host );
1811 // @todo FIXME: Validate hostnames here
1813 return $protocol . $host . $rest;
1820 * @param array $matches
1823 static function cleanUrlCallback( $matches ) {
1824 return urlencode( $matches[0] );
1828 * Does a string look like an e-mail address?
1830 * This validates an email address using an HTML5 specification found at:
1831 * http://www.whatwg.org/html/states-of-the-type-attribute.html#valid-e-mail-address
1832 * Which as of 2011-01-24 says:
1834 * A valid e-mail address is a string that matches the ABNF production
1835 * 1*( atext / "." ) "@" ldh-str *( "." ldh-str ) where atext is defined
1836 * in RFC 5322 section 3.2.3, and ldh-str is defined in RFC 1034 section
1839 * This function is an implementation of the specification as requested in
1842 * Client-side forms will use the same standard validation rules via JS or
1843 * HTML 5 validation; additional restrictions can be enforced server-side
1844 * by extensions via the 'isValidEmailAddr' hook.
1846 * Note that this validation doesn't 100% match RFC 2822, but is believed
1847 * to be liberal enough for wide use. Some invalid addresses will still
1848 * pass validation here.
1852 * @param string $addr E-mail address
1855 public static function validateEmail( $addr ) {
1857 if ( !Hooks
::run( 'isValidEmailAddr', array( $addr, &$result ) ) ) {
1861 // Please note strings below are enclosed in brackets [], this make the
1862 // hyphen "-" a range indicator. Hence it is double backslashed below.
1864 $rfc5322_atext = "a-z0-9!#$%&'*+\\-\/=?^_`{|}~";
1865 $rfc1034_ldh_str = "a-z0-9\\-";
1867 $html5_email_regexp = "/
1869 [$rfc5322_atext\\.]+ # user part which is liberal :p
1871 [$rfc1034_ldh_str]+ # First domain part
1872 (\\.[$rfc1034_ldh_str]+)* # Following part prefixed with a dot
1874 /ix"; // case Insensitive, eXtended
1876 return (bool)preg_match( $html5_email_regexp, $addr );