3 * XHTML sanitizer for MediaWiki
5 * Copyright (C) 2002-2005 Brion Vibber <brion@pobox.com> et al
6 * http://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 * Regular expression to match various types of character references in
29 * Sanitizer::normalizeCharReferences and Sanitizer::decodeCharReferences
31 define( 'MW_CHAR_REFS_REGEX',
39 * Regular expression to match HTML/XML attribute pairs within a tag.
40 * Allows some... latitude.
41 * Used in Sanitizer::fixTagAttributes and Sanitizer::decodeTagAttributes
43 $attrib = '[A-Za-z0-9]';
44 $space = '[\x09\x0a\x0d\x20]';
45 define( 'MW_ATTRIBS_REGEX',
46 "/(?:^|$space)($attrib+)
49 # The attribute value: quoted or alone
52 | ([a-zA-Z0-9!#$%&()*,\\-.\\/:;<>?@[\\]^_`{|}~]+)
53 | (\#[0-9a-fA-F]+) # Technically wrong, but lots of
54 # colors are specified like this.
55 # We'll be normalizing it.
57 )?(?=$space|\$)/sx" );
60 * List of all named character entities defined in HTML 4.01
61 * http://www.w3.org/TR/html4/sgml/entities.html
64 global $wgHtmlEntities;
65 $wgHtmlEntities = array(
319 /** @package MediaWiki */
322 * Cleans up HTML, removes dangerous tags and attributes, and
323 * removes HTML comments
325 * @param string $text
326 * @param callback $processCallback to do any variable or parameter replacements in HTML attribute values
327 * @param array $args for the processing callback
330 function removeHTMLtags( $text, $processCallback = null, $args = array() ) {
331 global $wgUseTidy, $wgUserHtml;
332 $fname = 'Parser::removeHTMLtags';
333 wfProfileIn( $fname );
336 $htmlpairs = array( # Tags that must be closed
337 'b', 'del', 'i', 'ins', 'u', 'font', 'big', 'small', 'sub', 'sup', 'h1',
338 'h2', 'h3', 'h4', 'h5', 'h6', 'cite', 'code', 'em', 's',
339 'strike', 'strong', 'tt', 'var', 'div', 'center',
340 'blockquote', 'ol', 'ul', 'dl', 'table', 'caption', 'pre',
341 'ruby', 'rt' , 'rb' , 'rp', 'p', 'span', 'u'
344 'br', 'hr', 'li', 'dt', 'dd'
346 $htmlsingleonly = array( # Elements that cannot have close tags
349 $htmlnest = array( # Tags that can be nested--??
350 'table', 'tr', 'td', 'th', 'div', 'blockquote', 'ol', 'ul',
351 'dl', 'font', 'big', 'small', 'sub', 'sup', 'span'
353 $tabletags = array( # Can only appear inside table
356 $htmllist = array( # Tags used by list
359 $listtags = array( # Tags that can appear in a list
364 $htmlpairs = array();
365 $htmlsingle = array();
367 $tabletags = array();
370 $htmlsingleallowed = array_merge( $htmlsingle, $tabletags );
371 $htmlelements = array_merge( $htmlsingle, $htmlpairs, $htmlnest );
373 # Remove HTML comments
374 $text = Sanitizer
::removeHTMLcomments( $text );
375 $bits = explode( '<', $text );
376 $text = array_shift( $bits );
378 $tagstack = array(); $tablestack = array();
379 foreach ( $bits as $x ) {
380 $prev = error_reporting( E_ALL
& ~
( E_NOTICE | E_WARNING
) );
381 preg_match( '/^(\\/?)(\\w+)([^>]*?)(\\/{0,1}>)([^<]*)$/',
383 list( $qbar, $slash, $t, $params, $brace, $rest ) = $regs;
384 error_reporting( $prev );
387 if ( in_array( $t = strtolower( $t ), $htmlelements ) ) {
391 if( in_array( $t, $htmlsingleonly ) ) {
393 } elseif ( ( $ot = @array_pop
( $tagstack ) ) != $t ) {
394 if ( in_array($ot, $htmlsingleallowed) ) {
395 # Pop all elements with an optional close tag
396 # and see if we find a match below them
398 array_push ($optstack, $ot);
399 while ( ( ( $ot = @array_pop
( $tagstack ) ) != $t ) &&
400 in_array($ot, $htmlsingleallowed) ) {
401 array_push ($optstack, $ot);
404 # No match. Push the optinal elements back again
406 while ( $ot = @array_pop
( $optstack ) ) {
407 array_push( $tagstack, $ot );
411 @array_push
( $tagstack, $ot );
412 # <li> can be nested in <ul> or <ol>, skip those cases:
413 if(!(in_array($ot, $htmllist) && in_array($t, $listtags) )) {
418 if ( $t == 'table' ) {
419 $tagstack = array_pop( $tablestack );
424 # Keep track for later
425 if ( in_array( $t, $tabletags ) &&
426 ! in_array( 'table', $tagstack ) ) {
428 } else if ( in_array( $t, $tagstack ) &&
429 ! in_array ( $t , $htmlnest ) ) {
431 #Â Is it a self closed htmlpair ? (bug 5487)
432 } else if( $brace == '/>' &&
433 in_array($t, $htmlpairs) ) {
435 } elseif( in_array( $t, $htmlsingleonly ) ) {
436 # Hack to force empty tag for uncloseable elements
438 } else if( in_array( $t, $htmlsingle ) ) {
439 # Hack to not close $htmlsingle tags
442 if ( $t == 'table' ) {
443 array_push( $tablestack, $tagstack );
446 array_push( $tagstack, $t );
449 # Replace any variables or template parameters with
451 if( is_callable( $processCallback ) ) {
452 call_user_func_array( $processCallback, array( &$params, $args ) );
455 # Strip non-approved attributes from the tag
456 $newparams = Sanitizer
::fixTagAttributes( $params, $t );
459 $rest = str_replace( '>', '>', $rest );
460 $close = ( $brace == '/>' ) ?
' /' : '';
461 $text .= "<$slash$t$newparams$close>$rest";
465 $text .= '<' . str_replace( '>', '>', $x);
467 # Close off any remaining tags
468 while ( is_array( $tagstack ) && ($t = array_pop( $tagstack )) ) {
470 if ( $t == 'table' ) { $tagstack = array_pop( $tablestack ); }
473 # this might be possible using tidy itself
474 foreach ( $bits as $x ) {
475 preg_match( '/^(\\/?)(\\w+)([^>]*?)(\\/{0,1}>)([^<]*)$/',
477 @list
( $qbar, $slash, $t, $params, $brace, $rest ) = $regs;
478 if ( in_array( $t = strtolower( $t ), $htmlelements ) ) {
479 if( is_callable( $processCallback ) ) {
480 call_user_func_array( $processCallback, array( &$params, $args ) );
482 $newparams = Sanitizer
::fixTagAttributes( $params, $t );
483 $rest = str_replace( '>', '>', $rest );
484 $text .= "<$slash$t$newparams$brace$rest";
486 $text .= '<' . str_replace( '>', '>', $x);
490 wfProfileOut( $fname );
495 * Remove '<!--', '-->', and everything between.
496 * To avoid leaving blank lines, when a comment is both preceded
497 * and followed by a newline (ignoring spaces), trim leading and
498 * trailing spaces and one of the newlines.
501 * @param string $text
504 function removeHTMLcomments( $text ) {
505 $fname='Parser::removeHTMLcomments';
506 wfProfileIn( $fname );
507 while (($start = strpos($text, '<!--')) !== false) {
508 $end = strpos($text, '-->', $start +
4);
509 if ($end === false) {
510 # Unterminated comment; bail out
516 # Trim space and newline if the comment is both
517 # preceded and followed by a newline
518 $spaceStart = max($start - 1, 0);
519 $spaceLen = $end - $spaceStart;
520 while (substr($text, $spaceStart, 1) === ' ' && $spaceStart > 0) {
524 while (substr($text, $spaceStart +
$spaceLen, 1) === ' ')
526 if (substr($text, $spaceStart, 1) === "\n" and substr($text, $spaceStart +
$spaceLen, 1) === "\n") {
527 # Remove the comment, leading and trailing
528 # spaces, and leave only one newline.
529 $text = substr_replace($text, "\n", $spaceStart, $spaceLen +
1);
532 # Remove just the comment.
533 $text = substr_replace($text, '', $start, $end - $start);
536 wfProfileOut( $fname );
541 * Take an array of attribute names and values and normalize or discard
542 * illegal values for the given element type.
544 * - Discards attributes not on a whitelist for the given element
545 * - Unsafe style attributes are discarded
547 * @param array $attribs
548 * @param string $element
551 * @todo Check for legal values where the DTD limits things.
552 * @todo Check for unique id attribute :P
554 function validateTagAttributes( $attribs, $element ) {
555 $whitelist = array_flip( Sanitizer
::attributeWhitelist( $element ) );
557 foreach( $attribs as $attribute => $value ) {
558 if( !isset( $whitelist[$attribute] ) ) {
561 # Strip javascript "expression" from stylesheets.
562 # http://msdn.microsoft.com/workshop/author/dhtml/overview/recalc.asp
563 if( $attribute == 'style' ) {
564 $value = Sanitizer
::checkCss( $value );
565 if( $value === false ) {
571 if ( $attribute === 'id' )
572 $value = Sanitizer
::escapeId( $value );
574 // If this attribute was previously set, override it.
575 // Output should only have one attribute of each name.
576 $out[$attribute] = $value;
582 * Pick apart some CSS and check it for forbidden or unsafe structures.
583 * Returns a sanitized string, or false if it was just too evil.
585 * Currently URL references, 'expression', 'tps' are forbidden.
587 * @param string $value
590 static function checkCss( $value ) {
591 $stripped = Sanitizer
::decodeCharReferences( $value );
593 // Remove any comments; IE gets token splitting wrong
594 $stripped = preg_replace( '!/\\*.*?\\*/!S', ' ', $stripped );
597 // ... and continue checks
598 $stripped = preg_replace( '!\\\\([0-9A-Fa-f]{1,6})[ \\n\\r\\t\\f]?!e',
599 'codepointToUtf8(hexdec("$1"))', $stripped );
600 $stripped = str_replace( '\\', '', $stripped );
601 if( preg_match( '/(expression|tps*:\/\/|url\\s*\().*/is',
611 * Take a tag soup fragment listing an HTML element's attributes
612 * and normalize it to well-formed XML, discarding unwanted attributes.
613 * Output is safe for further wikitext processing, with escaping of
614 * values that could trigger problems.
616 * - Normalizes attribute names to lowercase
617 * - Discards attributes not on a whitelist for the given element
618 * - Turns broken or invalid entities into plaintext
619 * - Double-quotes all attribute values
620 * - Attributes without values are given the name as attribute
621 * - Double attributes are discarded
622 * - Unsafe style attributes are discarded
623 * - Prepends space if there are attributes.
625 * @param string $text
626 * @param string $element
629 function fixTagAttributes( $text, $element ) {
630 if( trim( $text ) == '' ) {
634 $stripped = Sanitizer
::validateTagAttributes(
635 Sanitizer
::decodeTagAttributes( $text ), $element );
638 foreach( $stripped as $attribute => $value ) {
639 $encAttribute = htmlspecialchars( $attribute );
640 $encValue = Sanitizer
::safeEncodeAttribute( $value );
642 $attribs[] = "$encAttribute=\"$encValue\"";
644 return count( $attribs ) ?
' ' . implode( ' ', $attribs ) : '';
648 * Encode an attribute value for HTML output.
650 * @return HTML-encoded text fragment
652 function encodeAttribute( $text ) {
653 $encValue = htmlspecialchars( $text );
655 // Whitespace is normalized during attribute decoding,
656 // so if we've been passed non-spaces we must encode them
657 // ahead of time or they won't be preserved.
658 $encValue = strtr( $encValue, array(
668 * Encode an attribute value for HTML tags, with extra armoring
669 * against further wiki processing.
671 * @return HTML-encoded text fragment
673 function safeEncodeAttribute( $text ) {
674 $encValue = Sanitizer
::encodeAttribute( $text );
676 # Templates and links may be expanded in later parsing,
677 # creating invalid or dangerous output. Suppress this.
678 $encValue = strtr( $encValue, array(
679 '<' => '<', // This should never happen,
680 '>' => '>', // we've received invalid input
681 '"' => '"', // which should have been escaped.
684 "''" => '''',
685 'ISBN' => 'ISBN',
687 'PMID' => 'PMID',
693 $encValue = preg_replace_callback(
694 '/(' . wfUrlProtocols() . ')/',
695 array( 'Sanitizer', 'armorLinksCallback' ),
701 * Given a value escape it so that it can be used in an id attribute and
702 * return it, this does not validate the value however (see first link)
704 * @link http://www.w3.org/TR/html401/types.html#type-name Valid characters
707 * @link http://www.w3.org/TR/html401/struct/links.html#h-12.2.3 Anchors with the id attribute
716 function escapeId( $id ) {
717 static $replace = array(
722 $id = urlencode( Sanitizer
::decodeCharReferences( strtr( $id, ' ', '_' ) ) );
724 return str_replace( array_keys( $replace ), array_values( $replace ), $id );
728 * Regex replace callback for armoring links against further processing.
729 * @param array $matches
733 function armorLinksCallback( $matches ) {
734 return str_replace( ':', ':', $matches[1] );
738 * Return an associative array of attribute names and values from
739 * a partial tag string. Attribute names are forces to lowercase,
740 * character references are decoded to UTF-8 text.
745 function decodeTagAttributes( $text ) {
748 if( trim( $text ) == '' ) {
761 foreach( $pairs as $set ) {
762 $attribute = strtolower( $set[1] );
763 $value = Sanitizer
::getTagAttributeCallback( $set );
765 // Normalize whitespace
766 $value = preg_replace( '/[\t\r\n ]+/', ' ', $value );
767 $value = trim( $value );
769 // Decode character references
770 $attribs[$attribute] = Sanitizer
::decodeCharReferences( $value );
776 * Pick the appropriate attribute value from a match set from the
777 * MW_ATTRIBS_REGEX matches.
783 function getTagAttributeCallback( $set ) {
784 if( isset( $set[6] ) ) {
785 # Illegal #XXXXXX color with no quotes.
787 } elseif( isset( $set[5] ) ) {
790 } elseif( isset( $set[4] ) ) {
793 } elseif( isset( $set[3] ) ) {
796 } elseif( !isset( $set[2] ) ) {
797 # In XHTML, attributes must have a value.
798 # For 'reduced' form, return explicitly the attribute name here.
801 throw new MWException( "Tag conditions not met. This should never happen and is a bug." );
806 * Normalize whitespace and character references in an XML source-
807 * encoded text for an attribute value.
809 * See http://www.w3.org/TR/REC-xml/#AVNormalize for background,
810 * but note that we're not returning the value, but are returning
811 * XML source fragments that will be slapped into output.
813 * @param string $text
817 function normalizeAttributeValue( $text ) {
818 return str_replace( '"', '"',
820 '/\r\n|[\x20\x0d\x0a\x09]/',
822 Sanitizer
::normalizeCharReferences( $text ) ) );
826 * Ensure that any entities and character references are legal
827 * for XML and XHTML specifically. Any stray bits will be
828 * &-escaped to result in a valid text fragment.
830 * a. any named char refs must be known in XHTML
831 * b. any numeric char refs must be legal chars, not invalid or forbidden
832 * c. use &#x, not &#X
833 * d. fix or reject non-valid attributes
835 * @param string $text
839 function normalizeCharReferences( $text ) {
840 return preg_replace_callback(
842 array( 'Sanitizer', 'normalizeCharReferencesCallback' ),
846 * @param string $matches
849 function normalizeCharReferencesCallback( $matches ) {
851 if( $matches[1] != '' ) {
852 $ret = Sanitizer
::normalizeEntity( $matches[1] );
853 } elseif( $matches[2] != '' ) {
854 $ret = Sanitizer
::decCharReference( $matches[2] );
855 } elseif( $matches[3] != '' ) {
856 $ret = Sanitizer
::hexCharReference( $matches[3] );
857 } elseif( $matches[4] != '' ) {
858 $ret = Sanitizer
::hexCharReference( $matches[4] );
860 if( is_null( $ret ) ) {
861 return htmlspecialchars( $matches[0] );
868 * If the named entity is defined in the HTML 4.0/XHTML 1.0 DTD,
869 * return the named entity reference as is. Otherwise, returns
870 * HTML-escaped text of pseudo-entity source (eg &foo;)
872 * @param string $name
875 function normalizeEntity( $name ) {
876 global $wgHtmlEntities;
877 if( isset( $wgHtmlEntities[$name] ) ) {
880 return "&$name;";
884 function decCharReference( $codepoint ) {
885 $point = intval( $codepoint );
886 if( Sanitizer
::validateCodepoint( $point ) ) {
887 return sprintf( '&#%d;', $point );
893 function hexCharReference( $codepoint ) {
894 $point = hexdec( $codepoint );
895 if( Sanitizer
::validateCodepoint( $point ) ) {
896 return sprintf( '&#x%x;', $point );
903 * Returns true if a given Unicode codepoint is a valid character in XML.
904 * @param int $codepoint
907 function validateCodepoint( $codepoint ) {
908 return ($codepoint == 0x09)
909 ||
($codepoint == 0x0a)
910 ||
($codepoint == 0x0d)
911 ||
($codepoint >= 0x20 && $codepoint <= 0xd7ff)
912 ||
($codepoint >= 0xe000 && $codepoint <= 0xfffd)
913 ||
($codepoint >= 0x10000 && $codepoint <= 0x10ffff);
917 * Decode any character references, numeric or named entities,
918 * in the text and return a UTF-8 string.
920 * @param string $text
924 function decodeCharReferences( $text ) {
925 return preg_replace_callback(
927 array( 'Sanitizer', 'decodeCharReferencesCallback' ),
932 * @param string $matches
935 function decodeCharReferencesCallback( $matches ) {
936 if( $matches[1] != '' ) {
937 return Sanitizer
::decodeEntity( $matches[1] );
938 } elseif( $matches[2] != '' ) {
939 return Sanitizer
::decodeChar( intval( $matches[2] ) );
940 } elseif( $matches[3] != '' ) {
941 return Sanitizer
::decodeChar( hexdec( $matches[3] ) );
942 } elseif( $matches[4] != '' ) {
943 return Sanitizer
::decodeChar( hexdec( $matches[4] ) );
945 # Last case should be an ampersand by itself
950 * Return UTF-8 string for a codepoint if that is a valid
951 * character reference, otherwise U+FFFD REPLACEMENT CHARACTER.
952 * @param int $codepoint
956 function decodeChar( $codepoint ) {
957 if( Sanitizer
::validateCodepoint( $codepoint ) ) {
958 return codepointToUtf8( $codepoint );
960 return UTF8_REPLACEMENT
;
965 * If the named entity is defined in the HTML 4.0/XHTML 1.0 DTD,
966 * return the UTF-8 encoding of that character. Otherwise, returns
967 * pseudo-entity source (eg &foo;)
969 * @param string $name
972 function decodeEntity( $name ) {
973 global $wgHtmlEntities;
974 if( isset( $wgHtmlEntities[$name] ) ) {
975 return codepointToUtf8( $wgHtmlEntities[$name] );
982 * Fetch the whitelist of acceptable attributes for a given
985 * @param string $element
988 function attributeWhitelist( $element ) {
990 if( !isset( $list ) ) {
991 $list = Sanitizer
::setupAttributeWhitelist();
993 return isset( $list[$element] )
1001 function setupAttributeWhitelist() {
1002 $common = array( 'id', 'class', 'lang', 'dir', 'title', 'style' );
1003 $block = array_merge( $common, array( 'align' ) );
1004 $tablealign = array( 'align', 'char', 'charoff', 'valign' );
1005 $tablecell = array( 'abbr',
1011 'nowrap', # deprecated
1012 'width', # deprecated
1013 'height', # deprecated
1014 'bgcolor' # deprecated
1017 # Numbers refer to sections in HTML 4.01 standard describing the element.
1018 # See: http://www.w3.org/TR/html4/
1019 $whitelist = array (
1022 'center' => $common, # deprecated
1023 'span' => $block, # ??
1041 'strong' => $common,
1052 'blockquote' => array_merge( $common, array( 'cite' ) ),
1063 'br' => array( 'id', 'class', 'title', 'style', 'clear' ),
1066 'pre' => array_merge( $common, array( 'width' ) ),
1069 'ins' => array_merge( $common, array( 'cite', 'datetime' ) ),
1070 'del' => array_merge( $common, array( 'cite', 'datetime' ) ),
1073 'ul' => array_merge( $common, array( 'type' ) ),
1074 'ol' => array_merge( $common, array( 'type', 'start' ) ),
1075 'li' => array_merge( $common, array( 'type', 'value' ) ),
1083 'table' => array_merge( $common,
1084 array( 'summary', 'width', 'border', 'frame',
1085 'rules', 'cellspacing', 'cellpadding',
1086 'align', 'bgcolor', 'rules',
1090 'caption' => array_merge( $common, array( 'align' ) ),
1093 'thead' => array_merge( $common, $tablealign ),
1094 'tfoot' => array_merge( $common, $tablealign ),
1095 'tbody' => array_merge( $common, $tablealign ),
1098 'colgroup' => array_merge( $common, array( 'span', 'width' ), $tablealign ),
1099 'col' => array_merge( $common, array( 'span', 'width' ), $tablealign ),
1102 'tr' => array_merge( $common, array( 'bgcolor' ), $tablealign ),
1105 'td' => array_merge( $common, $tablecell, $tablealign ),
1106 'th' => array_merge( $common, $tablecell, $tablealign ),
1114 'strike' => $common,
1119 'font' => array_merge( $common, array( 'size', 'color', 'face' ) ),
1123 'hr' => array_merge( $common, array( 'noshade', 'size', 'width' ) ),
1125 # XHTML Ruby annotation text module, simple ruby only.
1126 # http://www.w3c.org/TR/ruby/
1131 'rt' => $common, #array_merge( $common, array( 'rbspan' ) ),
1138 * Take a fragment of (potentially invalid) HTML and return
1139 * a version with any tags removed, encoded suitably for literal
1140 * inclusion in an attribute value.
1142 * @param string $text HTML fragment
1145 function stripAllTags( $text ) {
1147 $text = preg_replace( '/ < .*? > /x', '', $text );
1149 # Normalize &entities and whitespace
1150 $text = Sanitizer
::normalizeAttributeValue( $text );
1152 # Will be placed into "double-quoted" attributes,
1153 # make sure remaining bits are safe.
1154 $text = str_replace(
1155 array('<', '>', '"'),
1156 array('<', '>', '"'),
1163 * Hack up a private DOCTYPE with HTML's standard entity declarations.
1164 * PHP 4 seemed to know these if you gave it an HTML doctype, but
1167 * Use for passing XHTML fragments to PHP's XML parsing functions
1172 function hackDocType() {
1173 global $wgHtmlEntities;
1174 $out = "<!DOCTYPE html [\n";
1175 foreach( $wgHtmlEntities as $entity => $codepoint ) {
1176 $out .= "<!ENTITY $entity \"&#$codepoint;\">";