3 * (X)HTML 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( !in_array( $t, $htmlsingle ) &&
388 ( $ot = @array_pop
( $tagstack ) ) != $t ) {
389 @array_push
( $tagstack, $ot );
392 if ( $t == 'table' ) {
393 $tagstack = array_pop( $tablestack );
398 # Keep track for later
399 if ( in_array( $t, $tabletags ) &&
400 ! in_array( 'table', $tagstack ) ) {
402 } else if ( in_array( $t, $tagstack ) &&
403 ! in_array ( $t , $htmlnest ) ) {
405 } elseif( in_array( $t, $htmlsingleonly ) ) {
406 # Hack to force empty tag for uncloseable elements
408 } else if ( ! in_array( $t, $htmlsingle ) ) {
409 if ( $t == 'table' ) {
410 array_push( $tablestack, $tagstack );
413 array_push( $tagstack, $t );
416 # Replace any variables or template parameters with
418 if( is_callable( $processCallback ) ) {
419 call_user_func_array( $processCallback, array( &$params, $args ) );
422 # Strip non-approved attributes from the tag
423 $newparams = Sanitizer
::fixTagAttributes( $params, $t );
426 $rest = str_replace( '>', '>', $rest );
427 $close = ( $brace == '/>' ) ?
' /' : '';
428 $text .= "<$slash$t$newparams$close>$rest";
432 $text .= '<' . str_replace( '>', '>', $x);
434 # Close off any remaining tags
435 while ( is_array( $tagstack ) && ($t = array_pop( $tagstack )) ) {
437 if ( $t == 'table' ) { $tagstack = array_pop( $tablestack ); }
440 # this might be possible using tidy itself
441 foreach ( $bits as $x ) {
442 preg_match( '/^(\\/?)(\\w+)([^>]*?)(\\/{0,1}>)([^<]*)$/',
444 @list
( $qbar, $slash, $t, $params, $brace, $rest ) = $regs;
445 if ( in_array( $t = strtolower( $t ), $htmlelements ) ) {
446 if( is_callable( $processCallback ) ) {
447 call_user_func_array( $processCallback, array( &$params, $args ) );
449 $newparams = Sanitizer
::fixTagAttributes( $params, $t );
450 $rest = str_replace( '>', '>', $rest );
451 $text .= "<$slash$t$newparams$brace$rest";
453 $text .= '<' . str_replace( '>', '>', $x);
457 wfProfileOut( $fname );
462 * Remove '<!--', '-->', and everything between.
463 * To avoid leaving blank lines, when a comment is both preceded
464 * and followed by a newline (ignoring spaces), trim leading and
465 * trailing spaces and one of the newlines.
468 * @param string $text
471 function removeHTMLcomments( $text ) {
472 $fname='Parser::removeHTMLcomments';
473 wfProfileIn( $fname );
474 while (($start = strpos($text, '<!--')) !== false) {
475 $end = strpos($text, '-->', $start +
4);
476 if ($end === false) {
477 # Unterminated comment; bail out
483 # Trim space and newline if the comment is both
484 # preceded and followed by a newline
485 $spaceStart = max($start - 1, 0);
486 $spaceLen = $end - $spaceStart;
487 while (substr($text, $spaceStart, 1) === ' ' && $spaceStart > 0) {
491 while (substr($text, $spaceStart +
$spaceLen, 1) === ' ')
493 if (substr($text, $spaceStart, 1) === "\n" and substr($text, $spaceStart +
$spaceLen, 1) === "\n") {
494 # Remove the comment, leading and trailing
495 # spaces, and leave only one newline.
496 $text = substr_replace($text, "\n", $spaceStart, $spaceLen +
1);
499 # Remove just the comment.
500 $text = substr_replace($text, '', $start, $end - $start);
503 wfProfileOut( $fname );
508 * Take a tag soup fragment listing an HTML element's attributes
509 * and normalize it to well-formed XML, discarding unwanted attributes.
511 * - Normalizes attribute names to lowercase
512 * - Discards attributes not on a whitelist for the given element
513 * - Turns broken or invalid entities into plaintext
514 * - Double-quotes all attribute values
515 * - Attributes without values are given the name as attribute
516 * - Double attributes are discarded
517 * - Unsafe style attributes are discarded
518 * - Prepends space if there are attributes.
520 * @param string $text
521 * @param string $element
524 * @todo Check for legal values where the DTD limits things.
525 * @todo Check for unique id attribute :P
527 function fixTagAttributes( $text, $element ) {
528 if( trim( $text ) == '' ) {
533 # Since we quote this later, this can be anything distinguishable
534 # 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 # Templates and links may be expanded in later parsing,
575 # creating invalid or dangerous output. Suppress this.
576 $value = strtr( $value, array(
579 "''" => '''',
580 'ISBN' => 'ISBN',
582 'PMID' => 'PMID',
586 $value = preg_replace_callback(
587 '/(' . wfUrlProtocols() . ')/',
588 array( 'Sanitizer', 'armorLinksCallback' ),
591 // If this attribute was previously set, override it.
592 // Output should only have one attribute of each name.
593 $attribs[$attribute] = "$attribute=\"$value\"";
595 if( empty( $attribs ) ) {
598 return ' ' . implode( ' ', $attribs );
603 * Regex replace callback for armoring links against further processing.
604 * @param array $matches
608 function armorLinksCallback( $matches ) {
609 return str_replace( ':', ':', $matches[1] );
613 * Return an associative array of attribute names and values from
614 * a partial tag string. Attribute names are forces to lowercase,
615 * character references are decoded to UTF-8 text.
620 function decodeTagAttributes( $text ) {
623 if( trim( $text ) == '' ) {
635 foreach( $pairs as $set ) {
636 $attribute = strtolower( $set[1] );
637 $value = Sanitizer
::getTagAttributeCallback( $set );
638 $attribs[$attribute] = Sanitizer
::decodeCharReferences( $value );
644 * Pick the appropriate attribute value from a match set from the
645 * MW_ATTRIBS_REGEX matches.
651 function getTagAttributeCallback( $set ) {
652 if( isset( $set[6] ) ) {
653 # Illegal #XXXXXX color with no quotes.
655 } elseif( isset( $set[5] ) ) {
658 } elseif( isset( $set[4] ) ) {
661 } elseif( isset( $set[3] ) ) {
664 } elseif( !isset( $set[2] ) ) {
665 # In XHTML, attributes must have a value.
666 # For 'reduced' form, return explicitly the attribute name here.
669 wfDebugDieBacktrace( "Tag conditions not met. This should never happen and is a bug." );
674 * Normalize whitespace and character references in an XML source-
675 * encoded text for an attribute value.
677 * See http://www.w3.org/TR/REC-xml/#AVNormalize for background,
678 * but note that we're not returning the value, but are returning
679 * XML source fragments that will be slapped into output.
681 * @param string $text
685 function normalizeAttributeValue( $text ) {
686 return str_replace( '"', '"',
688 '/\r\n|[\x20\x0d\x0a\x09]/',
690 Sanitizer
::normalizeCharReferences( $text ) ) );
694 * Ensure that any entities and character references are legal
695 * for XML and XHTML specifically. Any stray bits will be
696 * &-escaped to result in a valid text fragment.
698 * a. any named char refs must be known in XHTML
699 * b. any numeric char refs must be legal chars, not invalid or forbidden
700 * c. use &#x, not &#X
701 * d. fix or reject non-valid attributes
703 * @param string $text
707 function normalizeCharReferences( $text ) {
708 return preg_replace_callback(
710 array( 'Sanitizer', 'normalizeCharReferencesCallback' ),
714 * @param string $matches
717 function normalizeCharReferencesCallback( $matches ) {
719 if( $matches[1] != '' ) {
720 $ret = Sanitizer
::normalizeEntity( $matches[1] );
721 } elseif( $matches[2] != '' ) {
722 $ret = Sanitizer
::decCharReference( $matches[2] );
723 } elseif( $matches[3] != '' ) {
724 $ret = Sanitizer
::hexCharReference( $matches[3] );
725 } elseif( $matches[4] != '' ) {
726 $ret = Sanitizer
::hexCharReference( $matches[4] );
728 if( is_null( $ret ) ) {
729 return htmlspecialchars( $matches[0] );
736 * If the named entity is defined in the HTML 4.0/XHTML 1.0 DTD,
737 * return the named entity reference as is. Otherwise, returns
738 * HTML-escaped text of pseudo-entity source (eg &foo;)
740 * @param string $name
743 function normalizeEntity( $name ) {
744 global $wgHtmlEntities;
745 if( isset( $wgHtmlEntities[$name] ) ) {
748 return "&$name;";
752 function decCharReference( $codepoint ) {
753 $point = intval( $codepoint );
754 if( Sanitizer
::validateCodepoint( $point ) ) {
755 return sprintf( '&#%d;', $point );
761 function hexCharReference( $codepoint ) {
762 $point = hexdec( $codepoint );
763 if( Sanitizer
::validateCodepoint( $point ) ) {
764 return sprintf( '&#x%x;', $point );
771 * Returns true if a given Unicode codepoint is a valid character in XML.
772 * @param int $codepoint
775 function validateCodepoint( $codepoint ) {
776 return ($codepoint == 0x09)
777 ||
($codepoint == 0x0a)
778 ||
($codepoint == 0x0d)
779 ||
($codepoint >= 0x20 && $codepoint <= 0xd7ff)
780 ||
($codepoint >= 0xe000 && $codepoint <= 0xfffd)
781 ||
($codepoint >= 0x10000 && $codepoint <= 0x10ffff);
785 * Decode any character references, numeric or named entities,
786 * in the text and return a UTF-8 string.
788 * @param string $text
792 function decodeCharReferences( $text ) {
793 return preg_replace_callback(
795 array( 'Sanitizer', 'decodeCharReferencesCallback' ),
800 * @param string $matches
803 function decodeCharReferencesCallback( $matches ) {
804 if( $matches[1] != '' ) {
805 return Sanitizer
::decodeEntity( $matches[1] );
806 } elseif( $matches[2] != '' ) {
807 return Sanitizer
::decodeChar( intval( $matches[2] ) );
808 } elseif( $matches[3] != '' ) {
809 return Sanitizer
::decodeChar( hexdec( $matches[3] ) );
810 } elseif( $matches[4] != '' ) {
811 return Sanitizer
::decodeChar( hexdec( $matches[4] ) );
813 # Last case should be an ampersand by itself
818 * Return UTF-8 string for a codepoint if that is a valid
819 * character reference, otherwise U+FFFD REPLACEMENT CHARACTER.
820 * @param int $codepoint
824 function decodeChar( $codepoint ) {
825 if( Sanitizer
::validateCodepoint( $codepoint ) ) {
826 return codepointToUtf8( $codepoint );
828 return UTF8_REPLACEMENT
;
833 * If the named entity is defined in the HTML 4.0/XHTML 1.0 DTD,
834 * return the UTF-8 encoding of that character. Otherwise, returns
835 * pseudo-entity source (eg &foo;)
837 * @param string $name
840 function decodeEntity( $name ) {
841 global $wgHtmlEntities;
842 if( isset( $wgHtmlEntities[$name] ) ) {
843 return codepointToUtf8( $wgHtmlEntities[$name] );
850 * Fetch the whitelist of acceptable attributes for a given
853 * @param string $element
856 function attributeWhitelist( $element ) {
858 if( !isset( $list ) ) {
859 $list = Sanitizer
::setupAttributeWhitelist();
861 return isset( $list[$element] )
869 function setupAttributeWhitelist() {
870 $common = array( 'id', 'class', 'lang', 'dir', 'title', 'style' );
871 $block = array_merge( $common, array( 'align' ) );
872 $tablealign = array( 'align', 'char', 'charoff', 'valign' );
873 $tablecell = array( 'abbr',
879 'nowrap', # deprecated
880 'width', # deprecated
881 'height', # deprecated
882 'bgcolor' # deprecated
885 # Numbers refer to sections in HTML 4.01 standard describing the element.
886 # See: http://www.w3.org/TR/html4/
890 'center' => $common, # deprecated
891 'span' => $block, # ??
920 'blockquote' => array_merge( $common, array( 'cite' ) ),
931 'br' => array( 'id', 'class', 'title', 'style', 'clear' ),
934 'pre' => array_merge( $common, array( 'width' ) ),
937 'ins' => array_merge( $common, array( 'cite', 'datetime' ) ),
938 'del' => array_merge( $common, array( 'cite', 'datetime' ) ),
941 'ul' => array_merge( $common, array( 'type' ) ),
942 'ol' => array_merge( $common, array( 'type', 'start' ) ),
943 'li' => array_merge( $common, array( 'type', 'value' ) ),
951 'table' => array_merge( $common,
952 array( 'summary', 'width', 'border', 'frame',
953 'rules', 'cellspacing', 'cellpadding',
954 'align', 'bgcolor', 'frame', 'rules',
958 'caption' => array_merge( $common, array( 'align' ) ),
961 'thead' => array_merge( $common, $tablealign ),
962 'tfoot' => array_merge( $common, $tablealign ),
963 'tbody' => array_merge( $common, $tablealign ),
966 'colgroup' => array_merge( $common, array( 'span', 'width' ), $tablealign ),
967 'col' => array_merge( $common, array( 'span', 'width' ), $tablealign ),
970 'tr' => array_merge( $common, array( 'bgcolor' ), $tablealign ),
973 'td' => array_merge( $common, $tablecell, $tablealign ),
974 'th' => array_merge( $common, $tablecell, $tablealign ),
987 'font' => array_merge( $common, array( 'size', 'color', 'face' ) ),
991 'hr' => array_merge( $common, array( 'noshade', 'size', 'width' ) ),
993 # XHTML Ruby annotation text module, simple ruby only.
994 # http://www.w3c.org/TR/ruby/
999 'rt' => $common, #array_merge( $common, array( 'rbspan' ) ),
1006 * Take a fragment of (potentially invalid) HTML and return
1007 * a version with any tags removed, encoded suitably for literal
1008 * inclusion in an attribute value.
1010 * @param string $text HTML fragment
1013 function stripAllTags( $text ) {
1015 $text = preg_replace( '/<[^>]*>/', '', $text );
1017 # Normalize &entities and whitespace
1018 $text = Sanitizer
::normalizeAttributeValue( $text );
1020 # Will be placed into "double-quoted" attributes,
1021 # make sure remaining bits are safe.
1022 $text = str_replace(
1023 array('<', '>', '"'),
1024 array('<', '>', '"'),