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',
608 $value = preg_replace_callback(
609 '/(' . wfUrlProtocols() . ')/',
610 array( 'Sanitizer', 'armorLinksCallback' ),
613 // If this attribute was previously set, override it.
614 // Output should only have one attribute of each name.
615 $attribs[$attribute] = "$attribute=\"$value\"";
618 return count( $attribs ) ?
' ' . implode( ' ', $attribs ) : '';
622 * Given a value escape it so that it can be used in an id attribute and
623 * return it, this does not validate the value however (see first link)
625 * @link http://www.w3.org/TR/html401/types.html#type-name Valid characters
628 * @link http://www.w3.org/TR/html401/struct/links.html#h-12.2.3 Anchors with the id attribute
637 function escapeId( $id ) {
638 static $replace = array(
643 $id = urlencode( Sanitizer
::decodeCharReferences( strtr( $id, ' ', '_' ) ) );
645 return str_replace( array_keys( $replace ), array_values( $replace ), $id );
649 * Regex replace callback for armoring links against further processing.
650 * @param array $matches
654 function armorLinksCallback( $matches ) {
655 return str_replace( ':', ':', $matches[1] );
659 * Return an associative array of attribute names and values from
660 * a partial tag string. Attribute names are forces to lowercase,
661 * character references are decoded to UTF-8 text.
666 function decodeTagAttributes( $text ) {
669 if( trim( $text ) == '' ) {
682 foreach( $pairs as $set ) {
683 $attribute = strtolower( $set[1] );
684 $value = Sanitizer
::getTagAttributeCallback( $set );
685 $attribs[$attribute] = Sanitizer
::decodeCharReferences( $value );
691 * Pick the appropriate attribute value from a match set from the
692 * MW_ATTRIBS_REGEX matches.
698 function getTagAttributeCallback( $set ) {
699 if( isset( $set[6] ) ) {
700 # Illegal #XXXXXX color with no quotes.
702 } elseif( isset( $set[5] ) ) {
705 } elseif( isset( $set[4] ) ) {
708 } elseif( isset( $set[3] ) ) {
711 } elseif( !isset( $set[2] ) ) {
712 # In XHTML, attributes must have a value.
713 # For 'reduced' form, return explicitly the attribute name here.
716 wfDebugDieBacktrace( "Tag conditions not met. This should never happen and is a bug." );
721 * Normalize whitespace and character references in an XML source-
722 * encoded text for an attribute value.
724 * See http://www.w3.org/TR/REC-xml/#AVNormalize for background,
725 * but note that we're not returning the value, but are returning
726 * XML source fragments that will be slapped into output.
728 * @param string $text
732 function normalizeAttributeValue( $text ) {
733 return str_replace( '"', '"',
735 '/\r\n|[\x20\x0d\x0a\x09]/',
737 Sanitizer
::normalizeCharReferences( $text ) ) );
741 * Ensure that any entities and character references are legal
742 * for XML and XHTML specifically. Any stray bits will be
743 * &-escaped to result in a valid text fragment.
745 * a. any named char refs must be known in XHTML
746 * b. any numeric char refs must be legal chars, not invalid or forbidden
747 * c. use &#x, not &#X
748 * d. fix or reject non-valid attributes
750 * @param string $text
754 function normalizeCharReferences( $text ) {
755 return preg_replace_callback(
757 array( 'Sanitizer', 'normalizeCharReferencesCallback' ),
761 * @param string $matches
764 function normalizeCharReferencesCallback( $matches ) {
766 if( $matches[1] != '' ) {
767 $ret = Sanitizer
::normalizeEntity( $matches[1] );
768 } elseif( $matches[2] != '' ) {
769 $ret = Sanitizer
::decCharReference( $matches[2] );
770 } elseif( $matches[3] != '' ) {
771 $ret = Sanitizer
::hexCharReference( $matches[3] );
772 } elseif( $matches[4] != '' ) {
773 $ret = Sanitizer
::hexCharReference( $matches[4] );
775 if( is_null( $ret ) ) {
776 return htmlspecialchars( $matches[0] );
783 * If the named entity is defined in the HTML 4.0/XHTML 1.0 DTD,
784 * return the named entity reference as is. Otherwise, returns
785 * HTML-escaped text of pseudo-entity source (eg &foo;)
787 * @param string $name
790 function normalizeEntity( $name ) {
791 global $wgHtmlEntities;
792 if( isset( $wgHtmlEntities[$name] ) ) {
795 return "&$name;";
799 function decCharReference( $codepoint ) {
800 $point = intval( $codepoint );
801 if( Sanitizer
::validateCodepoint( $point ) ) {
802 return sprintf( '&#%d;', $point );
808 function hexCharReference( $codepoint ) {
809 $point = hexdec( $codepoint );
810 if( Sanitizer
::validateCodepoint( $point ) ) {
811 return sprintf( '&#x%x;', $point );
818 * Returns true if a given Unicode codepoint is a valid character in XML.
819 * @param int $codepoint
822 function validateCodepoint( $codepoint ) {
823 return ($codepoint == 0x09)
824 ||
($codepoint == 0x0a)
825 ||
($codepoint == 0x0d)
826 ||
($codepoint >= 0x20 && $codepoint <= 0xd7ff)
827 ||
($codepoint >= 0xe000 && $codepoint <= 0xfffd)
828 ||
($codepoint >= 0x10000 && $codepoint <= 0x10ffff);
832 * Decode any character references, numeric or named entities,
833 * in the text and return a UTF-8 string.
835 * @param string $text
839 function decodeCharReferences( $text ) {
840 return preg_replace_callback(
842 array( 'Sanitizer', 'decodeCharReferencesCallback' ),
847 * @param string $matches
850 function decodeCharReferencesCallback( $matches ) {
851 if( $matches[1] != '' ) {
852 return Sanitizer
::decodeEntity( $matches[1] );
853 } elseif( $matches[2] != '' ) {
854 return Sanitizer
::decodeChar( intval( $matches[2] ) );
855 } elseif( $matches[3] != '' ) {
856 return Sanitizer
::decodeChar( hexdec( $matches[3] ) );
857 } elseif( $matches[4] != '' ) {
858 return Sanitizer
::decodeChar( hexdec( $matches[4] ) );
860 # Last case should be an ampersand by itself
865 * Return UTF-8 string for a codepoint if that is a valid
866 * character reference, otherwise U+FFFD REPLACEMENT CHARACTER.
867 * @param int $codepoint
871 function decodeChar( $codepoint ) {
872 if( Sanitizer
::validateCodepoint( $codepoint ) ) {
873 return codepointToUtf8( $codepoint );
875 return UTF8_REPLACEMENT
;
880 * If the named entity is defined in the HTML 4.0/XHTML 1.0 DTD,
881 * return the UTF-8 encoding of that character. Otherwise, returns
882 * pseudo-entity source (eg &foo;)
884 * @param string $name
887 function decodeEntity( $name ) {
888 global $wgHtmlEntities;
889 if( isset( $wgHtmlEntities[$name] ) ) {
890 return codepointToUtf8( $wgHtmlEntities[$name] );
897 * Fetch the whitelist of acceptable attributes for a given
900 * @param string $element
903 function attributeWhitelist( $element ) {
905 if( !isset( $list ) ) {
906 $list = Sanitizer
::setupAttributeWhitelist();
908 return isset( $list[$element] )
916 function setupAttributeWhitelist() {
917 $common = array( 'id', 'class', 'lang', 'dir', 'title', 'style' );
918 $block = array_merge( $common, array( 'align' ) );
919 $tablealign = array( 'align', 'char', 'charoff', 'valign' );
920 $tablecell = array( 'abbr',
926 'nowrap', # deprecated
927 'width', # deprecated
928 'height', # deprecated
929 'bgcolor' # deprecated
932 # Numbers refer to sections in HTML 4.01 standard describing the element.
933 # See: http://www.w3.org/TR/html4/
937 'center' => $common, # deprecated
938 'span' => $block, # ??
967 'blockquote' => array_merge( $common, array( 'cite' ) ),
978 'br' => array( 'id', 'class', 'title', 'style', 'clear' ),
981 'pre' => array_merge( $common, array( 'width' ) ),
984 'ins' => array_merge( $common, array( 'cite', 'datetime' ) ),
985 'del' => array_merge( $common, array( 'cite', 'datetime' ) ),
988 'ul' => array_merge( $common, array( 'type' ) ),
989 'ol' => array_merge( $common, array( 'type', 'start' ) ),
990 'li' => array_merge( $common, array( 'type', 'value' ) ),
998 'table' => array_merge( $common,
999 array( 'summary', 'width', 'border', 'frame',
1000 'rules', 'cellspacing', 'cellpadding',
1001 'align', 'bgcolor', 'frame', 'rules',
1005 'caption' => array_merge( $common, array( 'align' ) ),
1008 'thead' => array_merge( $common, $tablealign ),
1009 'tfoot' => array_merge( $common, $tablealign ),
1010 'tbody' => array_merge( $common, $tablealign ),
1013 'colgroup' => array_merge( $common, array( 'span', 'width' ), $tablealign ),
1014 'col' => array_merge( $common, array( 'span', 'width' ), $tablealign ),
1017 'tr' => array_merge( $common, array( 'bgcolor' ), $tablealign ),
1020 'td' => array_merge( $common, $tablecell, $tablealign ),
1021 'th' => array_merge( $common, $tablecell, $tablealign ),
1029 'strike' => $common,
1034 'font' => array_merge( $common, array( 'size', 'color', 'face' ) ),
1038 'hr' => array_merge( $common, array( 'noshade', 'size', 'width' ) ),
1040 # XHTML Ruby annotation text module, simple ruby only.
1041 # http://www.w3c.org/TR/ruby/
1046 'rt' => $common, #array_merge( $common, array( 'rbspan' ) ),
1053 * Take a fragment of (potentially invalid) HTML and return
1054 * a version with any tags removed, encoded suitably for literal
1055 * inclusion in an attribute value.
1057 * @param string $text HTML fragment
1060 function stripAllTags( $text ) {
1062 $text = preg_replace( '/ < .*? > /x', '', $text );
1064 # Normalize &entities and whitespace
1065 $text = Sanitizer
::normalizeAttributeValue( $text );
1067 # Will be placed into "double-quoted" attributes,
1068 # make sure remaining bits are safe.
1069 $text = str_replace(
1070 array('<', '>', '"'),
1071 array('<', '>', '"'),
1078 * Hack up a private DOCTYPE with HTML's standard entity declarations.
1079 * PHP 4 seemed to know these if you gave it an HTML doctype, but
1082 * Use for passing XHTML fragments to PHP's XML parsing functions
1087 function hackDocType() {
1088 global $wgHtmlEntities;
1089 $out = "<!DOCTYPE html [\n";
1090 foreach( $wgHtmlEntities as $entity => $codepoint ) {
1091 $out .= "<!ENTITY $entity \"&#$codepoint;\">";