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 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, 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'
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
357 $htmlpairs = array();
358 $htmlsingle = array();
360 $tabletags = array();
363 $htmlsingle = array_merge( $tabletags, $htmlsingle );
364 $htmlelements = array_merge( $htmlsingle, $htmlpairs );
366 # Remove HTML comments
367 $text = Sanitizer
::removeHTMLcomments( $text );
369 $bits = explode( '<', $text );
370 $text = array_shift( $bits );
372 $tagstack = array(); $tablestack = array();
373 foreach ( $bits as $x ) {
374 $prev = error_reporting( E_ALL
& ~
( E_NOTICE | E_WARNING
) );
375 preg_match( '/^(\\/?)(\\w+)([^>]*?)(\\/{0,1}>)([^<]*)$/',
377 list( $qbar, $slash, $t, $params, $brace, $rest ) = $regs;
378 error_reporting( $prev );
381 if ( in_array( $t = strtolower( $t ), $htmlelements ) ) {
385 if( in_array( $t, $htmlsingleonly ) ) {
387 } elseif ( ( $ot = @array_pop
( $tagstack ) ) != $t ) {
388 @array_push
( $tagstack, $ot );
391 if ( $t == 'table' ) {
392 $tagstack = array_pop( $tablestack );
397 # Keep track for later
398 if ( in_array( $t, $tabletags ) &&
399 ! in_array( 'table', $tagstack ) ) {
401 } else if ( in_array( $t, $tagstack ) &&
402 ! in_array ( $t , $htmlnest ) ) {
404 } elseif( in_array( $t, $htmlsingleonly ) ) {
405 # Hack to force empty tag for uncloseable elements
408 if ( $t == 'table' ) {
409 array_push( $tablestack, $tagstack );
412 array_push( $tagstack, $t );
415 # Replace any variables or template parameters with
417 if( is_callable( $processCallback ) ) {
418 call_user_func_array( $processCallback, array( &$params, $args ) );
421 # Strip non-approved attributes from the tag
422 $newparams = Sanitizer
::fixTagAttributes( $params, $t );
425 $rest = str_replace( '>', '>', $rest );
426 $close = ( $brace == '/>' ) ?
' /' : '';
427 $text .= "<$slash$t$newparams$close>$rest";
431 $text .= '<' . str_replace( '>', '>', $x);
433 # Close off any remaining tags
434 while ( is_array( $tagstack ) && ($t = array_pop( $tagstack )) ) {
436 if ( $t == 'table' ) { $tagstack = array_pop( $tablestack ); }
439 # this might be possible using tidy itself
440 foreach ( $bits as $x ) {
441 preg_match( '/^(\\/?)(\\w+)([^>]*?)(\\/{0,1}>)([^<]*)$/',
443 @list
( $qbar, $slash, $t, $params, $brace, $rest ) = $regs;
444 if ( in_array( $t = strtolower( $t ), $htmlelements ) ) {
445 if( is_callable( $processCallback ) ) {
446 call_user_func_array( $processCallback, array( &$params, $args ) );
448 $newparams = Sanitizer
::fixTagAttributes( $params, $t );
449 $rest = str_replace( '>', '>', $rest );
450 $text .= "<$slash$t$newparams$brace$rest";
452 $text .= '<' . str_replace( '>', '>', $x);
456 wfProfileOut( $fname );
461 * Remove '<!--', '-->', and everything between.
462 * To avoid leaving blank lines, when a comment is both preceded
463 * and followed by a newline (ignoring spaces), trim leading and
464 * trailing spaces and one of the newlines.
467 * @param string $text
470 function removeHTMLcomments( $text ) {
471 $fname='Parser::removeHTMLcomments';
472 wfProfileIn( $fname );
473 while (($start = strpos($text, '<!--')) !== false) {
474 $end = strpos($text, '-->', $start +
4);
475 if ($end === false) {
476 # Unterminated comment; bail out
482 # Trim space and newline if the comment is both
483 # preceded and followed by a newline
484 $spaceStart = max($start - 1, 0);
485 $spaceLen = $end - $spaceStart;
486 while (substr($text, $spaceStart, 1) === ' ' && $spaceStart > 0) {
490 while (substr($text, $spaceStart +
$spaceLen, 1) === ' ')
492 if (substr($text, $spaceStart, 1) === "\n" and substr($text, $spaceStart +
$spaceLen, 1) === "\n") {
493 # Remove the comment, leading and trailing
494 # spaces, and leave only one newline.
495 $text = substr_replace($text, "\n", $spaceStart, $spaceLen +
1);
498 # Remove just the comment.
499 $text = substr_replace($text, '', $start, $end - $start);
502 wfProfileOut( $fname );
507 * Take a tag soup fragment listing an HTML element's attributes
508 * and normalize it to well-formed XML, discarding unwanted attributes.
510 * - Normalizes attribute names to lowercase
511 * - Discards attributes not on a whitelist for the given element
512 * - Turns broken or invalid entities into plaintext
513 * - Double-quotes all attribute values
514 * - Attributes without values are given the name as attribute
515 * - Double attributes are discarded
516 * - Unsafe style attributes are discarded
517 * - Prepends space if there are attributes.
519 * @param string $text
520 * @param string $element
523 * @todo Check for legal values where the DTD limits things.
524 * @todo Check for unique id attribute :P
526 function fixTagAttributes( $text, $element ) {
527 if( trim( $text ) == '' ) {
532 # Since we quote this later, this can be anything distinguishable
533 # from the end of the attribute
543 $whitelist = array_flip( Sanitizer
::attributeWhitelist( $element ) );
545 foreach( $pairs as $set ) {
546 $attribute = strtolower( $set[1] );
547 if( !isset( $whitelist[$attribute] ) ) {
551 $raw = Sanitizer
::getTagAttributeCallback( $set );
552 $value = Sanitizer
::normalizeAttributeValue( $raw );
554 # Strip javascript "expression" from stylesheets.
555 # http://msdn.microsoft.com/workshop/author/dhtml/overview/recalc.asp
556 if( $attribute == 'style' ) {
557 $stripped = Sanitizer
::decodeCharReferences( $value );
559 // Remove any comments; IE gets token splitting wrong
560 $stripped = preg_replace( '!/\\*.*?\\*/!S', ' ', $stripped );
561 $value = htmlspecialchars( $stripped );
563 // ... and continue checks
564 $stripped = preg_replace( '!\\\\([0-9A-Fa-f]{1,6})[ \\n\\r\\t\\f]?!e',
565 'codepointToUtf8(hexdec("$1"))', $stripped );
566 $stripped = str_replace( '\\', '', $stripped );
567 if( preg_match( '/(expression|tps*:\/\/|url\\s*\().*/is',
574 if ( $attribute === 'id' )
575 $value = Sanitizer
::escapeId( $value );
577 # Templates and links may be expanded in later parsing,
578 # creating invalid or dangerous output. Suppress this.
579 $value = strtr( $value, array(
582 "''" => '''',
583 'ISBN' => 'ISBN',
585 'PMID' => 'PMID',
589 $value = preg_replace_callback(
590 '/(' . wfUrlProtocols() . ')/',
591 array( 'Sanitizer', 'armorLinksCallback' ),
594 // If this attribute was previously set, override it.
595 // Output should only have one attribute of each name.
596 $attribs[$attribute] = "$attribute=\"$value\"";
599 return count( $attribs ) ?
' ' . implode( ' ', $attribs ) : '';
603 * Given a value escape it so that it can be used in an id attribute and
604 * return it, this does not validate the value however (see first link)
606 * @link http://www.w3.org/TR/html401/types.html#type-name Valid characters
609 * @link http://www.w3.org/TR/html401/struct/links.html#h-12.2.3 Anchors with the id attribute
618 function escapeId( $id ) {
619 static $replace = array(
624 $id = urlencode( Sanitizer
::decodeCharReferences( strtr( $id, ' ', '_' ) ) );
626 return str_replace( array_keys( $replace ), array_values( $replace ), $id );
630 * Regex replace callback for armoring links against further processing.
631 * @param array $matches
635 function armorLinksCallback( $matches ) {
636 return str_replace( ':', ':', $matches[1] );
640 * Return an associative array of attribute names and values from
641 * a partial tag string. Attribute names are forces to lowercase,
642 * character references are decoded to UTF-8 text.
647 function decodeTagAttributes( $text ) {
650 if( trim( $text ) == '' ) {
663 foreach( $pairs as $set ) {
664 $attribute = strtolower( $set[1] );
665 $value = Sanitizer
::getTagAttributeCallback( $set );
666 $attribs[$attribute] = Sanitizer
::decodeCharReferences( $value );
672 * Pick the appropriate attribute value from a match set from the
673 * MW_ATTRIBS_REGEX matches.
679 function getTagAttributeCallback( $set ) {
680 if( isset( $set[6] ) ) {
681 # Illegal #XXXXXX color with no quotes.
683 } elseif( isset( $set[5] ) ) {
686 } elseif( isset( $set[4] ) ) {
689 } elseif( isset( $set[3] ) ) {
692 } elseif( !isset( $set[2] ) ) {
693 # In XHTML, attributes must have a value.
694 # For 'reduced' form, return explicitly the attribute name here.
697 wfDebugDieBacktrace( "Tag conditions not met. This should never happen and is a bug." );
702 * Normalize whitespace and character references in an XML source-
703 * encoded text for an attribute value.
705 * See http://www.w3.org/TR/REC-xml/#AVNormalize for background,
706 * but note that we're not returning the value, but are returning
707 * XML source fragments that will be slapped into output.
709 * @param string $text
713 function normalizeAttributeValue( $text ) {
714 return str_replace( '"', '"',
716 '/\r\n|[\x20\x0d\x0a\x09]/',
718 Sanitizer
::normalizeCharReferences( $text ) ) );
722 * Ensure that any entities and character references are legal
723 * for XML and XHTML specifically. Any stray bits will be
724 * &-escaped to result in a valid text fragment.
726 * a. any named char refs must be known in XHTML
727 * b. any numeric char refs must be legal chars, not invalid or forbidden
728 * c. use &#x, not &#X
729 * d. fix or reject non-valid attributes
731 * @param string $text
735 function normalizeCharReferences( $text ) {
736 return preg_replace_callback(
738 array( 'Sanitizer', 'normalizeCharReferencesCallback' ),
742 * @param string $matches
745 function normalizeCharReferencesCallback( $matches ) {
747 if( $matches[1] != '' ) {
748 $ret = Sanitizer
::normalizeEntity( $matches[1] );
749 } elseif( $matches[2] != '' ) {
750 $ret = Sanitizer
::decCharReference( $matches[2] );
751 } elseif( $matches[3] != '' ) {
752 $ret = Sanitizer
::hexCharReference( $matches[3] );
753 } elseif( $matches[4] != '' ) {
754 $ret = Sanitizer
::hexCharReference( $matches[4] );
756 if( is_null( $ret ) ) {
757 return htmlspecialchars( $matches[0] );
764 * If the named entity is defined in the HTML 4.0/XHTML 1.0 DTD,
765 * return the named entity reference as is. Otherwise, returns
766 * HTML-escaped text of pseudo-entity source (eg &foo;)
768 * @param string $name
771 function normalizeEntity( $name ) {
772 global $wgHtmlEntities;
773 if( isset( $wgHtmlEntities[$name] ) ) {
776 return "&$name;";
780 function decCharReference( $codepoint ) {
781 $point = intval( $codepoint );
782 if( Sanitizer
::validateCodepoint( $point ) ) {
783 return sprintf( '&#%d;', $point );
789 function hexCharReference( $codepoint ) {
790 $point = hexdec( $codepoint );
791 if( Sanitizer
::validateCodepoint( $point ) ) {
792 return sprintf( '&#x%x;', $point );
799 * Returns true if a given Unicode codepoint is a valid character in XML.
800 * @param int $codepoint
803 function validateCodepoint( $codepoint ) {
804 return ($codepoint == 0x09)
805 ||
($codepoint == 0x0a)
806 ||
($codepoint == 0x0d)
807 ||
($codepoint >= 0x20 && $codepoint <= 0xd7ff)
808 ||
($codepoint >= 0xe000 && $codepoint <= 0xfffd)
809 ||
($codepoint >= 0x10000 && $codepoint <= 0x10ffff);
813 * Decode any character references, numeric or named entities,
814 * in the text and return a UTF-8 string.
816 * @param string $text
820 function decodeCharReferences( $text ) {
821 return preg_replace_callback(
823 array( 'Sanitizer', 'decodeCharReferencesCallback' ),
828 * @param string $matches
831 function decodeCharReferencesCallback( $matches ) {
832 if( $matches[1] != '' ) {
833 return Sanitizer
::decodeEntity( $matches[1] );
834 } elseif( $matches[2] != '' ) {
835 return Sanitizer
::decodeChar( intval( $matches[2] ) );
836 } elseif( $matches[3] != '' ) {
837 return Sanitizer
::decodeChar( hexdec( $matches[3] ) );
838 } elseif( $matches[4] != '' ) {
839 return Sanitizer
::decodeChar( hexdec( $matches[4] ) );
841 # Last case should be an ampersand by itself
846 * Return UTF-8 string for a codepoint if that is a valid
847 * character reference, otherwise U+FFFD REPLACEMENT CHARACTER.
848 * @param int $codepoint
852 function decodeChar( $codepoint ) {
853 if( Sanitizer
::validateCodepoint( $codepoint ) ) {
854 return codepointToUtf8( $codepoint );
856 return UTF8_REPLACEMENT
;
861 * If the named entity is defined in the HTML 4.0/XHTML 1.0 DTD,
862 * return the UTF-8 encoding of that character. Otherwise, returns
863 * pseudo-entity source (eg &foo;)
865 * @param string $name
868 function decodeEntity( $name ) {
869 global $wgHtmlEntities;
870 if( isset( $wgHtmlEntities[$name] ) ) {
871 return codepointToUtf8( $wgHtmlEntities[$name] );
878 * Fetch the whitelist of acceptable attributes for a given
881 * @param string $element
884 function attributeWhitelist( $element ) {
886 if( !isset( $list ) ) {
887 $list = Sanitizer
::setupAttributeWhitelist();
889 return isset( $list[$element] )
897 function setupAttributeWhitelist() {
898 $common = array( 'id', 'class', 'lang', 'dir', 'title', 'style' );
899 $block = array_merge( $common, array( 'align' ) );
900 $tablealign = array( 'align', 'char', 'charoff', 'valign' );
901 $tablecell = array( 'abbr',
907 'nowrap', # deprecated
908 'width', # deprecated
909 'height', # deprecated
910 'bgcolor' # deprecated
913 # Numbers refer to sections in HTML 4.01 standard describing the element.
914 # See: http://www.w3.org/TR/html4/
918 'center' => $common, # deprecated
919 'span' => $block, # ??
948 'blockquote' => array_merge( $common, array( 'cite' ) ),
959 'br' => array( 'id', 'class', 'title', 'style', 'clear' ),
962 'pre' => array_merge( $common, array( 'width' ) ),
965 'ins' => array_merge( $common, array( 'cite', 'datetime' ) ),
966 'del' => array_merge( $common, array( 'cite', 'datetime' ) ),
969 'ul' => array_merge( $common, array( 'type' ) ),
970 'ol' => array_merge( $common, array( 'type', 'start' ) ),
971 'li' => array_merge( $common, array( 'type', 'value' ) ),
979 'table' => array_merge( $common,
980 array( 'summary', 'width', 'border', 'frame',
981 'rules', 'cellspacing', 'cellpadding',
982 'align', 'bgcolor', 'frame', 'rules',
986 'caption' => array_merge( $common, array( 'align' ) ),
989 'thead' => array_merge( $common, $tablealign ),
990 'tfoot' => array_merge( $common, $tablealign ),
991 'tbody' => array_merge( $common, $tablealign ),
994 'colgroup' => array_merge( $common, array( 'span', 'width' ), $tablealign ),
995 'col' => array_merge( $common, array( 'span', 'width' ), $tablealign ),
998 'tr' => array_merge( $common, array( 'bgcolor' ), $tablealign ),
1001 'td' => array_merge( $common, $tablecell, $tablealign ),
1002 'th' => array_merge( $common, $tablecell, $tablealign ),
1010 'strike' => $common,
1015 'font' => array_merge( $common, array( 'size', 'color', 'face' ) ),
1019 'hr' => array_merge( $common, array( 'noshade', 'size', 'width' ) ),
1021 # XHTML Ruby annotation text module, simple ruby only.
1022 # http://www.w3c.org/TR/ruby/
1027 'rt' => $common, #array_merge( $common, array( 'rbspan' ) ),
1034 * Take a fragment of (potentially invalid) HTML and return
1035 * a version with any tags removed, encoded suitably for literal
1036 * inclusion in an attribute value.
1038 * @param string $text HTML fragment
1041 function stripAllTags( $text ) {
1043 $text = preg_replace( '/ < .*? > /x', '', $text );
1045 # Normalize &entities and whitespace
1046 $text = Sanitizer
::normalizeAttributeValue( $text );
1048 # Will be placed into "double-quoted" attributes,
1049 # make sure remaining bits are safe.
1050 $text = str_replace(
1051 array('<', '>', '"'),
1052 array('<', '>', '"'),