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 $htmlsingle = array_merge( $tabletags, $htmlsingle );
371 $htmlelements = array_merge( $htmlsingle, $htmlpairs );
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 @array_push
( $tagstack, $ot );
395 # <li> can be nested in <ul> or <ol>, skip those cases:
396 if(!(in_array($ot, $htmllist) && in_array($t, $listtags) )) {
400 if ( $t == 'table' ) {
401 $tagstack = array_pop( $tablestack );
406 # Keep track for later
407 if ( in_array( $t, $tabletags ) &&
408 ! in_array( 'table', $tagstack ) ) {
410 } else if ( in_array( $t, $tagstack ) &&
411 ! in_array ( $t , $htmlnest ) ) {
413 #Â Is it a self closed htmlpair ? (bug 5487)
414 } else if( $brace == '/>' &&
415 in_array($t, $htmlpairs) ) {
417 } elseif( in_array( $t, $htmlsingleonly ) ) {
418 # Hack to force empty tag for uncloseable elements
420 } else if( in_array( $t, $htmlsingle ) ) {
421 # Hack to not close $htmlsingle tags
424 if ( $t == 'table' ) {
425 array_push( $tablestack, $tagstack );
428 array_push( $tagstack, $t );
431 # Replace any variables or template parameters with
433 if( is_callable( $processCallback ) ) {
434 call_user_func_array( $processCallback, array( &$params, $args ) );
437 # Strip non-approved attributes from the tag
438 $newparams = Sanitizer
::fixTagAttributes( $params, $t );
441 $rest = str_replace( '>', '>', $rest );
442 $close = ( $brace == '/>' ) ?
' /' : '';
443 $text .= "<$slash$t$newparams$close>$rest";
447 $text .= '<' . str_replace( '>', '>', $x);
449 # Close off any remaining tags
450 while ( is_array( $tagstack ) && ($t = array_pop( $tagstack )) ) {
452 if ( $t == 'table' ) { $tagstack = array_pop( $tablestack ); }
455 # this might be possible using tidy itself
456 foreach ( $bits as $x ) {
457 preg_match( '/^(\\/?)(\\w+)([^>]*?)(\\/{0,1}>)([^<]*)$/',
459 @list
( $qbar, $slash, $t, $params, $brace, $rest ) = $regs;
460 if ( in_array( $t = strtolower( $t ), $htmlelements ) ) {
461 if( is_callable( $processCallback ) ) {
462 call_user_func_array( $processCallback, array( &$params, $args ) );
464 $newparams = Sanitizer
::fixTagAttributes( $params, $t );
465 $rest = str_replace( '>', '>', $rest );
466 $text .= "<$slash$t$newparams$brace$rest";
468 $text .= '<' . str_replace( '>', '>', $x);
472 wfProfileOut( $fname );
477 * Remove '<!--', '-->', and everything between.
478 * To avoid leaving blank lines, when a comment is both preceded
479 * and followed by a newline (ignoring spaces), trim leading and
480 * trailing spaces and one of the newlines.
483 * @param string $text
486 function removeHTMLcomments( $text ) {
487 $fname='Parser::removeHTMLcomments';
488 wfProfileIn( $fname );
489 while (($start = strpos($text, '<!--')) !== false) {
490 $end = strpos($text, '-->', $start +
4);
491 if ($end === false) {
492 # Unterminated comment; bail out
498 # Trim space and newline if the comment is both
499 # preceded and followed by a newline
500 $spaceStart = max($start - 1, 0);
501 $spaceLen = $end - $spaceStart;
502 while (substr($text, $spaceStart, 1) === ' ' && $spaceStart > 0) {
506 while (substr($text, $spaceStart +
$spaceLen, 1) === ' ')
508 if (substr($text, $spaceStart, 1) === "\n" and substr($text, $spaceStart +
$spaceLen, 1) === "\n") {
509 # Remove the comment, leading and trailing
510 # spaces, and leave only one newline.
511 $text = substr_replace($text, "\n", $spaceStart, $spaceLen +
1);
514 # Remove just the comment.
515 $text = substr_replace($text, '', $start, $end - $start);
518 wfProfileOut( $fname );
523 * Take a tag soup fragment listing an HTML element's attributes
524 * and normalize it to well-formed XML, discarding unwanted attributes.
526 * - Normalizes attribute names to lowercase
527 * - Discards attributes not on a whitelist for the given element
528 * - Turns broken or invalid entities into plaintext
529 * - Double-quotes all attribute values
530 * - Attributes without values are given the name as attribute
531 * - Double attributes are discarded
532 * - Unsafe style attributes are discarded
533 * - Prepends space if there are attributes.
535 * @param string $text
536 * @param string $element
539 * @todo Check for legal values where the DTD limits things.
540 * @todo Check for unique id attribute :P
542 function fixTagAttributes( $text, $element ) {
543 if( trim( $text ) == '' ) {
548 # Since we quote this later, this can be anything distinguishable
549 # from the end of the attribute
559 $whitelist = array_flip( Sanitizer
::attributeWhitelist( $element ) );
561 foreach( $pairs as $set ) {
562 $attribute = strtolower( $set[1] );
563 if( !isset( $whitelist[$attribute] ) ) {
567 $raw = Sanitizer
::getTagAttributeCallback( $set );
568 $value = Sanitizer
::normalizeAttributeValue( $raw );
570 # Strip javascript "expression" from stylesheets.
571 # http://msdn.microsoft.com/workshop/author/dhtml/overview/recalc.asp
572 if( $attribute == 'style' ) {
573 $stripped = Sanitizer
::decodeCharReferences( $value );
575 // Remove any comments; IE gets token splitting wrong
576 $stripped = preg_replace( '!/\\*.*?\\*/!S', ' ', $stripped );
577 $value = htmlspecialchars( $stripped );
579 // ... and continue checks
580 $stripped = preg_replace( '!\\\\([0-9A-Fa-f]{1,6})[ \\n\\r\\t\\f]?!e',
581 'codepointToUtf8(hexdec("$1"))', $stripped );
582 $stripped = str_replace( '\\', '', $stripped );
583 if( preg_match( '/(expression|tps*:\/\/|url\\s*\().*/is',
590 if ( $attribute === 'id' )
591 $value = Sanitizer
::escapeId( $value );
593 # Templates and links may be expanded in later parsing,
594 # creating invalid or dangerous output. Suppress this.
595 $value = strtr( $value, array(
596 '<' => '<', // This should never happen,
597 '>' => '>', // we've received invalid input
598 '"' => '"', // which should have been escaped.
601 "''" => '''',
602 'ISBN' => 'ISBN',
604 'PMID' => 'PMID',
610 $value = preg_replace_callback(
611 '/(' . wfUrlProtocols() . ')/',
612 array( 'Sanitizer', 'armorLinksCallback' ),
615 // If this attribute was previously set, override it.
616 // Output should only have one attribute of each name.
617 $attribs[$attribute] = "$attribute=\"$value\"";
620 return count( $attribs ) ?
' ' . implode( ' ', $attribs ) : '';
624 * Given a value escape it so that it can be used in an id attribute and
625 * return it, this does not validate the value however (see first link)
627 * @link http://www.w3.org/TR/html401/types.html#type-name Valid characters
630 * @link http://www.w3.org/TR/html401/struct/links.html#h-12.2.3 Anchors with the id attribute
639 function escapeId( $id ) {
640 static $replace = array(
645 $id = urlencode( Sanitizer
::decodeCharReferences( strtr( $id, ' ', '_' ) ) );
647 return str_replace( array_keys( $replace ), array_values( $replace ), $id );
651 * Regex replace callback for armoring links against further processing.
652 * @param array $matches
656 function armorLinksCallback( $matches ) {
657 return str_replace( ':', ':', $matches[1] );
661 * Return an associative array of attribute names and values from
662 * a partial tag string. Attribute names are forces to lowercase,
663 * character references are decoded to UTF-8 text.
668 function decodeTagAttributes( $text ) {
671 if( trim( $text ) == '' ) {
684 foreach( $pairs as $set ) {
685 $attribute = strtolower( $set[1] );
686 $value = Sanitizer
::getTagAttributeCallback( $set );
687 $attribs[$attribute] = Sanitizer
::decodeCharReferences( $value );
693 * Pick the appropriate attribute value from a match set from the
694 * MW_ATTRIBS_REGEX matches.
700 function getTagAttributeCallback( $set ) {
701 if( isset( $set[6] ) ) {
702 # Illegal #XXXXXX color with no quotes.
704 } elseif( isset( $set[5] ) ) {
707 } elseif( isset( $set[4] ) ) {
710 } elseif( isset( $set[3] ) ) {
713 } elseif( !isset( $set[2] ) ) {
714 # In XHTML, attributes must have a value.
715 # For 'reduced' form, return explicitly the attribute name here.
718 wfDebugDieBacktrace( "Tag conditions not met. This should never happen and is a bug." );
723 * Normalize whitespace and character references in an XML source-
724 * encoded text for an attribute value.
726 * See http://www.w3.org/TR/REC-xml/#AVNormalize for background,
727 * but note that we're not returning the value, but are returning
728 * XML source fragments that will be slapped into output.
730 * @param string $text
734 function normalizeAttributeValue( $text ) {
735 return str_replace( '"', '"',
737 '/\r\n|[\x20\x0d\x0a\x09]/',
739 Sanitizer
::normalizeCharReferences( $text ) ) );
743 * Ensure that any entities and character references are legal
744 * for XML and XHTML specifically. Any stray bits will be
745 * &-escaped to result in a valid text fragment.
747 * a. any named char refs must be known in XHTML
748 * b. any numeric char refs must be legal chars, not invalid or forbidden
749 * c. use &#x, not &#X
750 * d. fix or reject non-valid attributes
752 * @param string $text
756 function normalizeCharReferences( $text ) {
757 return preg_replace_callback(
759 array( 'Sanitizer', 'normalizeCharReferencesCallback' ),
763 * @param string $matches
766 function normalizeCharReferencesCallback( $matches ) {
768 if( $matches[1] != '' ) {
769 $ret = Sanitizer
::normalizeEntity( $matches[1] );
770 } elseif( $matches[2] != '' ) {
771 $ret = Sanitizer
::decCharReference( $matches[2] );
772 } elseif( $matches[3] != '' ) {
773 $ret = Sanitizer
::hexCharReference( $matches[3] );
774 } elseif( $matches[4] != '' ) {
775 $ret = Sanitizer
::hexCharReference( $matches[4] );
777 if( is_null( $ret ) ) {
778 return htmlspecialchars( $matches[0] );
785 * If the named entity is defined in the HTML 4.0/XHTML 1.0 DTD,
786 * return the named entity reference as is. Otherwise, returns
787 * HTML-escaped text of pseudo-entity source (eg &foo;)
789 * @param string $name
792 function normalizeEntity( $name ) {
793 global $wgHtmlEntities;
794 if( isset( $wgHtmlEntities[$name] ) ) {
797 return "&$name;";
801 function decCharReference( $codepoint ) {
802 $point = intval( $codepoint );
803 if( Sanitizer
::validateCodepoint( $point ) ) {
804 return sprintf( '&#%d;', $point );
810 function hexCharReference( $codepoint ) {
811 $point = hexdec( $codepoint );
812 if( Sanitizer
::validateCodepoint( $point ) ) {
813 return sprintf( '&#x%x;', $point );
820 * Returns true if a given Unicode codepoint is a valid character in XML.
821 * @param int $codepoint
824 function validateCodepoint( $codepoint ) {
825 return ($codepoint == 0x09)
826 ||
($codepoint == 0x0a)
827 ||
($codepoint == 0x0d)
828 ||
($codepoint >= 0x20 && $codepoint <= 0xd7ff)
829 ||
($codepoint >= 0xe000 && $codepoint <= 0xfffd)
830 ||
($codepoint >= 0x10000 && $codepoint <= 0x10ffff);
834 * Decode any character references, numeric or named entities,
835 * in the text and return a UTF-8 string.
837 * @param string $text
841 function decodeCharReferences( $text ) {
842 return preg_replace_callback(
844 array( 'Sanitizer', 'decodeCharReferencesCallback' ),
849 * @param string $matches
852 function decodeCharReferencesCallback( $matches ) {
853 if( $matches[1] != '' ) {
854 return Sanitizer
::decodeEntity( $matches[1] );
855 } elseif( $matches[2] != '' ) {
856 return Sanitizer
::decodeChar( intval( $matches[2] ) );
857 } elseif( $matches[3] != '' ) {
858 return Sanitizer
::decodeChar( hexdec( $matches[3] ) );
859 } elseif( $matches[4] != '' ) {
860 return Sanitizer
::decodeChar( hexdec( $matches[4] ) );
862 # Last case should be an ampersand by itself
867 * Return UTF-8 string for a codepoint if that is a valid
868 * character reference, otherwise U+FFFD REPLACEMENT CHARACTER.
869 * @param int $codepoint
873 function decodeChar( $codepoint ) {
874 if( Sanitizer
::validateCodepoint( $codepoint ) ) {
875 return codepointToUtf8( $codepoint );
877 return UTF8_REPLACEMENT
;
882 * If the named entity is defined in the HTML 4.0/XHTML 1.0 DTD,
883 * return the UTF-8 encoding of that character. Otherwise, returns
884 * pseudo-entity source (eg &foo;)
886 * @param string $name
889 function decodeEntity( $name ) {
890 global $wgHtmlEntities;
891 if( isset( $wgHtmlEntities[$name] ) ) {
892 return codepointToUtf8( $wgHtmlEntities[$name] );
899 * Fetch the whitelist of acceptable attributes for a given
902 * @param string $element
905 function attributeWhitelist( $element ) {
907 if( !isset( $list ) ) {
908 $list = Sanitizer
::setupAttributeWhitelist();
910 return isset( $list[$element] )
918 function setupAttributeWhitelist() {
919 $common = array( 'id', 'class', 'lang', 'dir', 'title', 'style' );
920 $block = array_merge( $common, array( 'align' ) );
921 $tablealign = array( 'align', 'char', 'charoff', 'valign' );
922 $tablecell = array( 'abbr',
928 'nowrap', # deprecated
929 'width', # deprecated
930 'height', # deprecated
931 'bgcolor' # deprecated
934 # Numbers refer to sections in HTML 4.01 standard describing the element.
935 # See: http://www.w3.org/TR/html4/
939 'center' => $common, # deprecated
940 'span' => $block, # ??
969 'blockquote' => array_merge( $common, array( 'cite' ) ),
980 'br' => array( 'id', 'class', 'title', 'style', 'clear' ),
983 'pre' => array_merge( $common, array( 'width' ) ),
986 'ins' => array_merge( $common, array( 'cite', 'datetime' ) ),
987 'del' => array_merge( $common, array( 'cite', 'datetime' ) ),
990 'ul' => array_merge( $common, array( 'type' ) ),
991 'ol' => array_merge( $common, array( 'type', 'start' ) ),
992 'li' => array_merge( $common, array( 'type', 'value' ) ),
1000 'table' => array_merge( $common,
1001 array( 'summary', 'width', 'border', 'frame',
1002 'rules', 'cellspacing', 'cellpadding',
1003 'align', 'bgcolor', 'frame', 'rules',
1007 'caption' => array_merge( $common, array( 'align' ) ),
1010 'thead' => array_merge( $common, $tablealign ),
1011 'tfoot' => array_merge( $common, $tablealign ),
1012 'tbody' => array_merge( $common, $tablealign ),
1015 'colgroup' => array_merge( $common, array( 'span', 'width' ), $tablealign ),
1016 'col' => array_merge( $common, array( 'span', 'width' ), $tablealign ),
1019 'tr' => array_merge( $common, array( 'bgcolor' ), $tablealign ),
1022 'td' => array_merge( $common, $tablecell, $tablealign ),
1023 'th' => array_merge( $common, $tablecell, $tablealign ),
1031 'strike' => $common,
1036 'font' => array_merge( $common, array( 'size', 'color', 'face' ) ),
1040 'hr' => array_merge( $common, array( 'noshade', 'size', 'width' ) ),
1042 # XHTML Ruby annotation text module, simple ruby only.
1043 # http://www.w3c.org/TR/ruby/
1048 'rt' => $common, #array_merge( $common, array( 'rbspan' ) ),
1055 * Take a fragment of (potentially invalid) HTML and return
1056 * a version with any tags removed, encoded suitably for literal
1057 * inclusion in an attribute value.
1059 * @param string $text HTML fragment
1062 function stripAllTags( $text ) {
1064 $text = preg_replace( '/ < .*? > /x', '', $text );
1066 # Normalize &entities and whitespace
1067 $text = Sanitizer
::normalizeAttributeValue( $text );
1069 # Will be placed into "double-quoted" attributes,
1070 # make sure remaining bits are safe.
1071 $text = str_replace(
1072 array('<', '>', '"'),
1073 array('<', '>', '"'),
1080 * Hack up a private DOCTYPE with HTML's standard entity declarations.
1081 * PHP 4 seemed to know these if you gave it an HTML doctype, but
1084 * Use for passing XHTML fragments to PHP's XML parsing functions
1089 function hackDocType() {
1090 global $wgHtmlEntities;
1091 $out = "<!DOCTYPE html [\n";
1092 foreach( $wgHtmlEntities as $entity => $codepoint ) {
1093 $out .= "<!ENTITY $entity \"&#$codepoint;\">";