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',
609 $value = preg_replace_callback(
610 '/(' . wfUrlProtocols() . ')/',
611 array( 'Sanitizer', 'armorLinksCallback' ),
614 // If this attribute was previously set, override it.
615 // Output should only have one attribute of each name.
616 $attribs[$attribute] = "$attribute=\"$value\"";
619 return count( $attribs ) ?
' ' . implode( ' ', $attribs ) : '';
623 * Given a value escape it so that it can be used in an id attribute and
624 * return it, this does not validate the value however (see first link)
626 * @link http://www.w3.org/TR/html401/types.html#type-name Valid characters
629 * @link http://www.w3.org/TR/html401/struct/links.html#h-12.2.3 Anchors with the id attribute
638 function escapeId( $id ) {
639 static $replace = array(
644 $id = urlencode( Sanitizer
::decodeCharReferences( strtr( $id, ' ', '_' ) ) );
646 return str_replace( array_keys( $replace ), array_values( $replace ), $id );
650 * Regex replace callback for armoring links against further processing.
651 * @param array $matches
655 function armorLinksCallback( $matches ) {
656 return str_replace( ':', ':', $matches[1] );
660 * Return an associative array of attribute names and values from
661 * a partial tag string. Attribute names are forces to lowercase,
662 * character references are decoded to UTF-8 text.
667 function decodeTagAttributes( $text ) {
670 if( trim( $text ) == '' ) {
683 foreach( $pairs as $set ) {
684 $attribute = strtolower( $set[1] );
685 $value = Sanitizer
::getTagAttributeCallback( $set );
686 $attribs[$attribute] = Sanitizer
::decodeCharReferences( $value );
692 * Pick the appropriate attribute value from a match set from the
693 * MW_ATTRIBS_REGEX matches.
699 function getTagAttributeCallback( $set ) {
700 if( isset( $set[6] ) ) {
701 # Illegal #XXXXXX color with no quotes.
703 } elseif( isset( $set[5] ) ) {
706 } elseif( isset( $set[4] ) ) {
709 } elseif( isset( $set[3] ) ) {
712 } elseif( !isset( $set[2] ) ) {
713 # In XHTML, attributes must have a value.
714 # For 'reduced' form, return explicitly the attribute name here.
717 wfDebugDieBacktrace( "Tag conditions not met. This should never happen and is a bug." );
722 * Normalize whitespace and character references in an XML source-
723 * encoded text for an attribute value.
725 * See http://www.w3.org/TR/REC-xml/#AVNormalize for background,
726 * but note that we're not returning the value, but are returning
727 * XML source fragments that will be slapped into output.
729 * @param string $text
733 function normalizeAttributeValue( $text ) {
734 return str_replace( '"', '"',
736 '/\r\n|[\x20\x0d\x0a\x09]/',
738 Sanitizer
::normalizeCharReferences( $text ) ) );
742 * Ensure that any entities and character references are legal
743 * for XML and XHTML specifically. Any stray bits will be
744 * &-escaped to result in a valid text fragment.
746 * a. any named char refs must be known in XHTML
747 * b. any numeric char refs must be legal chars, not invalid or forbidden
748 * c. use &#x, not &#X
749 * d. fix or reject non-valid attributes
751 * @param string $text
755 function normalizeCharReferences( $text ) {
756 return preg_replace_callback(
758 array( 'Sanitizer', 'normalizeCharReferencesCallback' ),
762 * @param string $matches
765 function normalizeCharReferencesCallback( $matches ) {
767 if( $matches[1] != '' ) {
768 $ret = Sanitizer
::normalizeEntity( $matches[1] );
769 } elseif( $matches[2] != '' ) {
770 $ret = Sanitizer
::decCharReference( $matches[2] );
771 } elseif( $matches[3] != '' ) {
772 $ret = Sanitizer
::hexCharReference( $matches[3] );
773 } elseif( $matches[4] != '' ) {
774 $ret = Sanitizer
::hexCharReference( $matches[4] );
776 if( is_null( $ret ) ) {
777 return htmlspecialchars( $matches[0] );
784 * If the named entity is defined in the HTML 4.0/XHTML 1.0 DTD,
785 * return the named entity reference as is. Otherwise, returns
786 * HTML-escaped text of pseudo-entity source (eg &foo;)
788 * @param string $name
791 function normalizeEntity( $name ) {
792 global $wgHtmlEntities;
793 if( isset( $wgHtmlEntities[$name] ) ) {
796 return "&$name;";
800 function decCharReference( $codepoint ) {
801 $point = intval( $codepoint );
802 if( Sanitizer
::validateCodepoint( $point ) ) {
803 return sprintf( '&#%d;', $point );
809 function hexCharReference( $codepoint ) {
810 $point = hexdec( $codepoint );
811 if( Sanitizer
::validateCodepoint( $point ) ) {
812 return sprintf( '&#x%x;', $point );
819 * Returns true if a given Unicode codepoint is a valid character in XML.
820 * @param int $codepoint
823 function validateCodepoint( $codepoint ) {
824 return ($codepoint == 0x09)
825 ||
($codepoint == 0x0a)
826 ||
($codepoint == 0x0d)
827 ||
($codepoint >= 0x20 && $codepoint <= 0xd7ff)
828 ||
($codepoint >= 0xe000 && $codepoint <= 0xfffd)
829 ||
($codepoint >= 0x10000 && $codepoint <= 0x10ffff);
833 * Decode any character references, numeric or named entities,
834 * in the text and return a UTF-8 string.
836 * @param string $text
840 function decodeCharReferences( $text ) {
841 return preg_replace_callback(
843 array( 'Sanitizer', 'decodeCharReferencesCallback' ),
848 * @param string $matches
851 function decodeCharReferencesCallback( $matches ) {
852 if( $matches[1] != '' ) {
853 return Sanitizer
::decodeEntity( $matches[1] );
854 } elseif( $matches[2] != '' ) {
855 return Sanitizer
::decodeChar( intval( $matches[2] ) );
856 } elseif( $matches[3] != '' ) {
857 return Sanitizer
::decodeChar( hexdec( $matches[3] ) );
858 } elseif( $matches[4] != '' ) {
859 return Sanitizer
::decodeChar( hexdec( $matches[4] ) );
861 # Last case should be an ampersand by itself
866 * Return UTF-8 string for a codepoint if that is a valid
867 * character reference, otherwise U+FFFD REPLACEMENT CHARACTER.
868 * @param int $codepoint
872 function decodeChar( $codepoint ) {
873 if( Sanitizer
::validateCodepoint( $codepoint ) ) {
874 return codepointToUtf8( $codepoint );
876 return UTF8_REPLACEMENT
;
881 * If the named entity is defined in the HTML 4.0/XHTML 1.0 DTD,
882 * return the UTF-8 encoding of that character. Otherwise, returns
883 * pseudo-entity source (eg &foo;)
885 * @param string $name
888 function decodeEntity( $name ) {
889 global $wgHtmlEntities;
890 if( isset( $wgHtmlEntities[$name] ) ) {
891 return codepointToUtf8( $wgHtmlEntities[$name] );
898 * Fetch the whitelist of acceptable attributes for a given
901 * @param string $element
904 function attributeWhitelist( $element ) {
906 if( !isset( $list ) ) {
907 $list = Sanitizer
::setupAttributeWhitelist();
909 return isset( $list[$element] )
917 function setupAttributeWhitelist() {
918 $common = array( 'id', 'class', 'lang', 'dir', 'title', 'style' );
919 $block = array_merge( $common, array( 'align' ) );
920 $tablealign = array( 'align', 'char', 'charoff', 'valign' );
921 $tablecell = array( 'abbr',
927 'nowrap', # deprecated
928 'width', # deprecated
929 'height', # deprecated
930 'bgcolor' # deprecated
933 # Numbers refer to sections in HTML 4.01 standard describing the element.
934 # See: http://www.w3.org/TR/html4/
938 'center' => $common, # deprecated
939 'span' => $block, # ??
968 'blockquote' => array_merge( $common, array( 'cite' ) ),
979 'br' => array( 'id', 'class', 'title', 'style', 'clear' ),
982 'pre' => array_merge( $common, array( 'width' ) ),
985 'ins' => array_merge( $common, array( 'cite', 'datetime' ) ),
986 'del' => array_merge( $common, array( 'cite', 'datetime' ) ),
989 'ul' => array_merge( $common, array( 'type' ) ),
990 'ol' => array_merge( $common, array( 'type', 'start' ) ),
991 'li' => array_merge( $common, array( 'type', 'value' ) ),
999 'table' => array_merge( $common,
1000 array( 'summary', 'width', 'border', 'frame',
1001 'rules', 'cellspacing', 'cellpadding',
1002 'align', 'bgcolor', 'frame', 'rules',
1006 'caption' => array_merge( $common, array( 'align' ) ),
1009 'thead' => array_merge( $common, $tablealign ),
1010 'tfoot' => array_merge( $common, $tablealign ),
1011 'tbody' => array_merge( $common, $tablealign ),
1014 'colgroup' => array_merge( $common, array( 'span', 'width' ), $tablealign ),
1015 'col' => array_merge( $common, array( 'span', 'width' ), $tablealign ),
1018 'tr' => array_merge( $common, array( 'bgcolor' ), $tablealign ),
1021 'td' => array_merge( $common, $tablecell, $tablealign ),
1022 'th' => array_merge( $common, $tablecell, $tablealign ),
1030 'strike' => $common,
1035 'font' => array_merge( $common, array( 'size', 'color', 'face' ) ),
1039 'hr' => array_merge( $common, array( 'noshade', 'size', 'width' ) ),
1041 # XHTML Ruby annotation text module, simple ruby only.
1042 # http://www.w3c.org/TR/ruby/
1047 'rt' => $common, #array_merge( $common, array( 'rbspan' ) ),
1054 * Take a fragment of (potentially invalid) HTML and return
1055 * a version with any tags removed, encoded suitably for literal
1056 * inclusion in an attribute value.
1058 * @param string $text HTML fragment
1061 function stripAllTags( $text ) {
1063 $text = preg_replace( '/ < .*? > /x', '', $text );
1065 # Normalize &entities and whitespace
1066 $text = Sanitizer
::normalizeAttributeValue( $text );
1068 # Will be placed into "double-quoted" attributes,
1069 # make sure remaining bits are safe.
1070 $text = str_replace(
1071 array('<', '>', '"'),
1072 array('<', '>', '"'),
1079 * Hack up a private DOCTYPE with HTML's standard entity declarations.
1080 * PHP 4 seemed to know these if you gave it an HTML doctype, but
1083 * Use for passing XHTML fragments to PHP's XML parsing functions
1088 function hackDocType() {
1089 global $wgHtmlEntities;
1090 $out = "<!DOCTYPE html [\n";
1091 foreach( $wgHtmlEntities as $entity => $codepoint ) {
1092 $out .= "<!ENTITY $entity \"&#$codepoint;\">";