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(
580 '<' => '<', // This should never happen,
581 '>' => '>', // we've received invalid input
582 '"' => '"', // which should have been escaped.
585 "''" => '''',
586 'ISBN' => 'ISBN',
588 'PMID' => 'PMID',
592 $value = preg_replace_callback(
593 '/(' . wfUrlProtocols() . ')/',
594 array( 'Sanitizer', 'armorLinksCallback' ),
597 // If this attribute was previously set, override it.
598 // Output should only have one attribute of each name.
599 $attribs[$attribute] = "$attribute=\"$value\"";
602 return count( $attribs ) ?
' ' . implode( ' ', $attribs ) : '';
606 * Given a value escape it so that it can be used in an id attribute and
607 * return it, this does not validate the value however (see first link)
609 * @link http://www.w3.org/TR/html401/types.html#type-name Valid characters
612 * @link http://www.w3.org/TR/html401/struct/links.html#h-12.2.3 Anchors with the id attribute
621 function escapeId( $id ) {
622 static $replace = array(
627 $id = urlencode( Sanitizer
::decodeCharReferences( strtr( $id, ' ', '_' ) ) );
629 return str_replace( array_keys( $replace ), array_values( $replace ), $id );
633 * Regex replace callback for armoring links against further processing.
634 * @param array $matches
638 function armorLinksCallback( $matches ) {
639 return str_replace( ':', ':', $matches[1] );
643 * Return an associative array of attribute names and values from
644 * a partial tag string. Attribute names are forces to lowercase,
645 * character references are decoded to UTF-8 text.
650 function decodeTagAttributes( $text ) {
653 if( trim( $text ) == '' ) {
666 foreach( $pairs as $set ) {
667 $attribute = strtolower( $set[1] );
668 $value = Sanitizer
::getTagAttributeCallback( $set );
669 $attribs[$attribute] = Sanitizer
::decodeCharReferences( $value );
675 * Pick the appropriate attribute value from a match set from the
676 * MW_ATTRIBS_REGEX matches.
682 function getTagAttributeCallback( $set ) {
683 if( isset( $set[6] ) ) {
684 # Illegal #XXXXXX color with no quotes.
686 } elseif( isset( $set[5] ) ) {
689 } elseif( isset( $set[4] ) ) {
692 } elseif( isset( $set[3] ) ) {
695 } elseif( !isset( $set[2] ) ) {
696 # In XHTML, attributes must have a value.
697 # For 'reduced' form, return explicitly the attribute name here.
700 wfDebugDieBacktrace( "Tag conditions not met. This should never happen and is a bug." );
705 * Normalize whitespace and character references in an XML source-
706 * encoded text for an attribute value.
708 * See http://www.w3.org/TR/REC-xml/#AVNormalize for background,
709 * but note that we're not returning the value, but are returning
710 * XML source fragments that will be slapped into output.
712 * @param string $text
716 function normalizeAttributeValue( $text ) {
717 return str_replace( '"', '"',
719 '/\r\n|[\x20\x0d\x0a\x09]/',
721 Sanitizer
::normalizeCharReferences( $text ) ) );
725 * Ensure that any entities and character references are legal
726 * for XML and XHTML specifically. Any stray bits will be
727 * &-escaped to result in a valid text fragment.
729 * a. any named char refs must be known in XHTML
730 * b. any numeric char refs must be legal chars, not invalid or forbidden
731 * c. use &#x, not &#X
732 * d. fix or reject non-valid attributes
734 * @param string $text
738 function normalizeCharReferences( $text ) {
739 return preg_replace_callback(
741 array( 'Sanitizer', 'normalizeCharReferencesCallback' ),
745 * @param string $matches
748 function normalizeCharReferencesCallback( $matches ) {
750 if( $matches[1] != '' ) {
751 $ret = Sanitizer
::normalizeEntity( $matches[1] );
752 } elseif( $matches[2] != '' ) {
753 $ret = Sanitizer
::decCharReference( $matches[2] );
754 } elseif( $matches[3] != '' ) {
755 $ret = Sanitizer
::hexCharReference( $matches[3] );
756 } elseif( $matches[4] != '' ) {
757 $ret = Sanitizer
::hexCharReference( $matches[4] );
759 if( is_null( $ret ) ) {
760 return htmlspecialchars( $matches[0] );
767 * If the named entity is defined in the HTML 4.0/XHTML 1.0 DTD,
768 * return the named entity reference as is. Otherwise, returns
769 * HTML-escaped text of pseudo-entity source (eg &foo;)
771 * @param string $name
774 function normalizeEntity( $name ) {
775 global $wgHtmlEntities;
776 if( isset( $wgHtmlEntities[$name] ) ) {
779 return "&$name;";
783 function decCharReference( $codepoint ) {
784 $point = intval( $codepoint );
785 if( Sanitizer
::validateCodepoint( $point ) ) {
786 return sprintf( '&#%d;', $point );
792 function hexCharReference( $codepoint ) {
793 $point = hexdec( $codepoint );
794 if( Sanitizer
::validateCodepoint( $point ) ) {
795 return sprintf( '&#x%x;', $point );
802 * Returns true if a given Unicode codepoint is a valid character in XML.
803 * @param int $codepoint
806 function validateCodepoint( $codepoint ) {
807 return ($codepoint == 0x09)
808 ||
($codepoint == 0x0a)
809 ||
($codepoint == 0x0d)
810 ||
($codepoint >= 0x20 && $codepoint <= 0xd7ff)
811 ||
($codepoint >= 0xe000 && $codepoint <= 0xfffd)
812 ||
($codepoint >= 0x10000 && $codepoint <= 0x10ffff);
816 * Decode any character references, numeric or named entities,
817 * in the text and return a UTF-8 string.
819 * @param string $text
823 function decodeCharReferences( $text ) {
824 return preg_replace_callback(
826 array( 'Sanitizer', 'decodeCharReferencesCallback' ),
831 * @param string $matches
834 function decodeCharReferencesCallback( $matches ) {
835 if( $matches[1] != '' ) {
836 return Sanitizer
::decodeEntity( $matches[1] );
837 } elseif( $matches[2] != '' ) {
838 return Sanitizer
::decodeChar( intval( $matches[2] ) );
839 } elseif( $matches[3] != '' ) {
840 return Sanitizer
::decodeChar( hexdec( $matches[3] ) );
841 } elseif( $matches[4] != '' ) {
842 return Sanitizer
::decodeChar( hexdec( $matches[4] ) );
844 # Last case should be an ampersand by itself
849 * Return UTF-8 string for a codepoint if that is a valid
850 * character reference, otherwise U+FFFD REPLACEMENT CHARACTER.
851 * @param int $codepoint
855 function decodeChar( $codepoint ) {
856 if( Sanitizer
::validateCodepoint( $codepoint ) ) {
857 return codepointToUtf8( $codepoint );
859 return UTF8_REPLACEMENT
;
864 * If the named entity is defined in the HTML 4.0/XHTML 1.0 DTD,
865 * return the UTF-8 encoding of that character. Otherwise, returns
866 * pseudo-entity source (eg &foo;)
868 * @param string $name
871 function decodeEntity( $name ) {
872 global $wgHtmlEntities;
873 if( isset( $wgHtmlEntities[$name] ) ) {
874 return codepointToUtf8( $wgHtmlEntities[$name] );
881 * Fetch the whitelist of acceptable attributes for a given
884 * @param string $element
887 function attributeWhitelist( $element ) {
889 if( !isset( $list ) ) {
890 $list = Sanitizer
::setupAttributeWhitelist();
892 return isset( $list[$element] )
900 function setupAttributeWhitelist() {
901 $common = array( 'id', 'class', 'lang', 'dir', 'title', 'style' );
902 $block = array_merge( $common, array( 'align' ) );
903 $tablealign = array( 'align', 'char', 'charoff', 'valign' );
904 $tablecell = array( 'abbr',
910 'nowrap', # deprecated
911 'width', # deprecated
912 'height', # deprecated
913 'bgcolor' # deprecated
916 # Numbers refer to sections in HTML 4.01 standard describing the element.
917 # See: http://www.w3.org/TR/html4/
921 'center' => $common, # deprecated
922 'span' => $block, # ??
951 'blockquote' => array_merge( $common, array( 'cite' ) ),
962 'br' => array( 'id', 'class', 'title', 'style', 'clear' ),
965 'pre' => array_merge( $common, array( 'width' ) ),
968 'ins' => array_merge( $common, array( 'cite', 'datetime' ) ),
969 'del' => array_merge( $common, array( 'cite', 'datetime' ) ),
972 'ul' => array_merge( $common, array( 'type' ) ),
973 'ol' => array_merge( $common, array( 'type', 'start' ) ),
974 'li' => array_merge( $common, array( 'type', 'value' ) ),
982 'table' => array_merge( $common,
983 array( 'summary', 'width', 'border', 'frame',
984 'rules', 'cellspacing', 'cellpadding',
985 'align', 'bgcolor', 'frame', 'rules',
989 'caption' => array_merge( $common, array( 'align' ) ),
992 'thead' => array_merge( $common, $tablealign ),
993 'tfoot' => array_merge( $common, $tablealign ),
994 'tbody' => array_merge( $common, $tablealign ),
997 'colgroup' => array_merge( $common, array( 'span', 'width' ), $tablealign ),
998 'col' => array_merge( $common, array( 'span', 'width' ), $tablealign ),
1001 'tr' => array_merge( $common, array( 'bgcolor' ), $tablealign ),
1004 'td' => array_merge( $common, $tablecell, $tablealign ),
1005 'th' => array_merge( $common, $tablecell, $tablealign ),
1013 'strike' => $common,
1018 'font' => array_merge( $common, array( 'size', 'color', 'face' ) ),
1022 'hr' => array_merge( $common, array( 'noshade', 'size', 'width' ) ),
1024 # XHTML Ruby annotation text module, simple ruby only.
1025 # http://www.w3c.org/TR/ruby/
1030 'rt' => $common, #array_merge( $common, array( 'rbspan' ) ),
1037 * Take a fragment of (potentially invalid) HTML and return
1038 * a version with any tags removed, encoded suitably for literal
1039 * inclusion in an attribute value.
1041 * @param string $text HTML fragment
1044 function stripAllTags( $text ) {
1046 $text = preg_replace( '/ < .*? > /x', '', $text );
1048 # Normalize &entities and whitespace
1049 $text = Sanitizer
::normalizeAttributeValue( $text );
1051 # Will be placed into "double-quoted" attributes,
1052 # make sure remaining bits are safe.
1053 $text = str_replace(
1054 array('<', '>', '"'),
1055 array('<', '>', '"'),
1062 * Hack up a private DOCTYPE with HTML's standard entity declarations.
1063 * PHP 4 seemed to know these if you gave it an HTML doctype, but
1066 * Use for passing XHTML fragments to PHP's XML parsing functions
1071 function hackDocType() {
1072 global $wgHtmlEntities;
1073 $out = "<!DOCTYPE html [\n";
1074 foreach( $wgHtmlEntities as $entity => $codepoint ) {
1075 $out .= "<!ENTITY $entity \"&#$codepoint;\">";