4 * (X)HTML sanitizer for MediaWiki
6 * Copyright (C) 2002-2005 Brion Vibber <brion@pobox.com> et al
7 * http://www.mediawiki.org/
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
22 * http://www.gnu.org/copyleft/gpl.html
29 * Regular expression to match various types of character references in
30 * Sanitizer::normalizeCharReferences and Sanitizer::decodeCharReferences
32 define( 'MW_CHAR_REFS_REGEX',
40 * List of all named character entities defined in HTML 4.01
41 * http://www.w3.org/TR/html4/sgml/entities.html
44 global $wgHtmlEntities;
45 $wgHtmlEntities = array(
301 * Cleans up HTML, removes dangerous tags and attributes, and
302 * removes HTML comments
304 * @param string $text
307 function removeHTMLtags( $text ) {
308 global $wgUseTidy, $wgUserHtml;
309 $fname = 'Parser::removeHTMLtags';
310 wfProfileIn( $fname );
313 $htmlpairs = array( # Tags that must be closed
314 'b', 'del', 'i', 'ins', 'u', 'font', 'big', 'small', 'sub', 'sup', 'h1',
315 'h2', 'h3', 'h4', 'h5', 'h6', 'cite', 'code', 'em', 's',
316 'strike', 'strong', 'tt', 'var', 'div', 'center',
317 'blockquote', 'ol', 'ul', 'dl', 'table', 'caption', 'pre',
318 'ruby', 'rt' , 'rb' , 'rp', 'p', 'span'
321 'br', 'hr', 'li', 'dt', 'dd'
323 $htmlnest = array( # Tags that can be nested--??
324 'table', 'tr', 'td', 'th', 'div', 'blockquote', 'ol', 'ul',
325 'dl', 'font', 'big', 'small', 'sub', 'sup', 'span'
327 $tabletags = array( # Can only appear inside table
331 $htmlpairs = array();
332 $htmlsingle = array();
334 $tabletags = array();
337 $htmlsingle = array_merge( $tabletags, $htmlsingle );
338 $htmlelements = array_merge( $htmlsingle, $htmlpairs );
340 # Remove HTML comments
341 $text = Sanitizer
::removeHTMLcomments( $text );
343 $bits = explode( '<', $text );
344 $text = array_shift( $bits );
346 $tagstack = array(); $tablestack = array();
347 foreach ( $bits as $x ) {
348 $prev = error_reporting( E_ALL
& ~
( E_NOTICE | E_WARNING
) );
349 preg_match( '/^(\\/?)(\\w+)([^>]*)(\\/{0,1}>)([^<]*)$/',
351 list( $qbar, $slash, $t, $params, $brace, $rest ) = $regs;
352 error_reporting( $prev );
355 if ( in_array( $t = strtolower( $t ), $htmlelements ) ) {
359 if ( ! in_array( $t, $htmlsingle ) &&
360 ( $ot = @array_pop
( $tagstack ) ) != $t ) {
361 @array_push
( $tagstack, $ot );
364 if ( $t == 'table' ) {
365 $tagstack = array_pop( $tablestack );
370 # Keep track for later
371 if ( in_array( $t, $tabletags ) &&
372 ! in_array( 'table', $tagstack ) ) {
374 } else if ( in_array( $t, $tagstack ) &&
375 ! in_array ( $t , $htmlnest ) ) {
377 } else if ( ! in_array( $t, $htmlsingle ) ) {
378 if ( $t == 'table' ) {
379 array_push( $tablestack, $tagstack );
382 array_push( $tagstack, $t );
384 # Strip non-approved attributes from the tag
385 $newparams = Sanitizer
::fixTagAttributes( $params, $t );
388 $rest = str_replace( '>', '>', $rest );
389 $text .= "<$slash$t$newparams$brace$rest";
393 $text .= '<' . str_replace( '>', '>', $x);
395 # Close off any remaining tags
396 while ( is_array( $tagstack ) && ($t = array_pop( $tagstack )) ) {
398 if ( $t == 'table' ) { $tagstack = array_pop( $tablestack ); }
401 # this might be possible using tidy itself
402 foreach ( $bits as $x ) {
403 preg_match( '/^(\\/?)(\\w+)([^>]*)(\\/{0,1}>)([^<]*)$/',
405 @list
( $qbar, $slash, $t, $params, $brace, $rest ) = $regs;
406 if ( in_array( $t = strtolower( $t ), $htmlelements ) ) {
407 $newparams = Sanitizer
::fixTagAttributes( $params, $t );
408 $rest = str_replace( '>', '>', $rest );
409 $text .= "<$slash$t$newparams$brace$rest";
411 $text .= '<' . str_replace( '>', '>', $x);
415 wfProfileOut( $fname );
420 * Remove '<!--', '-->', and everything between.
421 * To avoid leaving blank lines, when a comment is both preceded
422 * and followed by a newline (ignoring spaces), trim leading and
423 * trailing spaces and one of the newlines.
426 * @param string $text
429 function removeHTMLcomments( $text ) {
430 $fname='Parser::removeHTMLcomments';
431 wfProfileIn( $fname );
432 while (($start = strpos($text, '<!--')) !== false) {
433 $end = strpos($text, '-->', $start +
4);
434 if ($end === false) {
435 # Unterminated comment; bail out
441 # Trim space and newline if the comment is both
442 # preceded and followed by a newline
443 $spaceStart = max($start - 1, 0);
444 $spaceLen = $end - $spaceStart;
445 while (substr($text, $spaceStart, 1) === ' ' && $spaceStart > 0) {
449 while (substr($text, $spaceStart +
$spaceLen, 1) === ' ')
451 if (substr($text, $spaceStart, 1) === "\n" and substr($text, $spaceStart +
$spaceLen, 1) === "\n") {
452 # Remove the comment, leading and trailing
453 # spaces, and leave only one newline.
454 $text = substr_replace($text, "\n", $spaceStart, $spaceLen +
1);
457 # Remove just the comment.
458 $text = substr_replace($text, '', $start, $end - $start);
461 wfProfileOut( $fname );
466 * Take a tag soup fragment listing an HTML element's attributes
467 * and normalize it to well-formed XML, discarding unwanted attributes.
469 * - Normalizes attribute names to lowercase
470 * - Discards attributes not on a whitelist for the given element
471 * - Turns broken or invalid entities into plaintext
472 * - Double-quotes all attribute values
473 * - Attributes without values are given the name as attribute
474 * - Double attributes are discarded
475 * - Unsafe style attributes are discarded
476 * - Prepends space if there are attributes.
478 * @param string $text
479 * @param string $element
482 * @todo Check for legal values where the DTD limits things.
483 * @todo Check for unique id attribute :P
485 function fixTagAttributes( $text, $element ) {
486 if( trim( $text ) == '' ) {
491 # Since we quote this later, this can be anything distinguishable
492 # from the end of the attribute
493 $attrib = '[A-Za-z0-9]';
494 $space = '[\x09\x0a\x0d\x20]';
496 "/(?:^|$space)($attrib+)
499 # The attribute value: quoted or alone
502 | ([a-zA-Z0-9!#$%&()*,\\-.\\/:;<>?@[\\]^_`{|}~]+)
503 | (\#[0-9a-fA-F]+) # Technically wrong, but lots of
504 # colors are specified like this.
505 # We'll be normalizing it.
514 $whitelist = array_flip( Sanitizer
::attributeWhitelist( $element ) );
516 foreach( $pairs as $set ) {
517 $attribute = strtolower( $set[1] );
518 if( !isset( $whitelist[$attribute] ) ) {
520 } elseif( isset( $set[6] ) ) {
521 # Illegal #XXXXXX color with no quotes.
522 $value = Sanitizer
::normalizeAttributeValue( $set[6] );
523 } elseif( isset( $set[5] ) ) {
525 $value = Sanitizer
::normalizeAttributeValue( $set[5] );
526 } elseif( isset( $set[4] ) ) {
528 $value = str_replace( '"', '"',
529 Sanitizer
::normalizeAttributeValue( $set[4] ) );
530 } elseif( isset( $set[3] ) ) {
532 $value = Sanitizer
::normalizeAttributeValue( $set[3] );
533 } elseif( !isset( $set[2] ) ) {
534 # In XHTML, attributes must have a value.
537 wfDebugDieBacktrace( "Tag conditions not met. This should never happen and is a bug." );
540 # Strip javascript "expression" from stylesheets.
541 # http://msdn.microsoft.com/workshop/author/dhtml/overview/recalc.asp
542 if( $attribute == 'style' && preg_match(
543 '/(expression|tps*:\/\/|url\\s*\().*/is',
544 Sanitizer
::decodeCharReferences( $value ) ) ) {
549 if( !isset( $attribs[$attribute] ) ) {
550 $attribs[$attribute] = "$attribute=\"$value\"";
553 if( empty( $attribs ) ) {
556 return ' ' . implode( ' ', $attribs );
561 * Normalize whitespace and character references in an XML source-
562 * encoded text for an attribute value.
564 * See http://www.w3.org/TR/REC-xml/#AVNormalize for background,
565 * but note that we're not returning the value, but are returning
566 * XML source fragments that will be slapped into output.
568 * @param string $text
572 function normalizeAttributeValue( $text ) {
574 '/\r\n|[\x20\x0d\x0a\x09]/',
576 Sanitizer
::normalizeCharReferences( $text ) );
580 * Ensure that any entities and character references are legal
581 * for XML and XHTML specifically. Any stray bits will be
582 * &-escaped to result in a valid text fragment.
584 * a. any named char refs must be known in XHTML
585 * b. any numeric char refs must be legal chars, not invalid or forbidden
586 * c. use &#x, not &#X
587 * d. fix or reject non-valid attributes
589 * @param string $text
593 function normalizeCharReferences( $text ) {
594 return preg_replace_callback(
596 array( 'Sanitizer', 'normalizeCharReferencesCallback' ),
600 * @param string $matches
603 function normalizeCharReferencesCallback( $matches ) {
605 if( $matches[1] != '' ) {
606 $ret = Sanitizer
::normalizeEntity( $matches[1] );
607 } elseif( $matches[2] != '' ) {
608 $ret = Sanitizer
::decCharReference( $matches[2] );
609 } elseif( $matches[3] != '' ) {
610 $ret = Sanitizer
::hexCharReference( $matches[3] );
611 } elseif( $matches[4] != '' ) {
612 $ret = Sanitizer
::hexCharReference( $matches[4] );
614 if( is_null( $ret ) ) {
615 return htmlspecialchars( $matches[0] );
622 * If the named entity is defined in the HTML 4.0/XHTML 1.0 DTD,
623 * return the named entity reference as is. Otherwise, returns
624 * HTML-escaped text of pseudo-entity source (eg &foo;)
626 * @param string $name
629 function normalizeEntity( $name ) {
630 global $wgHtmlEntities;
631 if( isset( $wgHtmlEntities[$name] ) ) {
634 return "&$name;";
638 function decCharReference( $codepoint ) {
639 $point = IntVal( $codepoint );
640 if( Sanitizer
::validateCodepoint( $point ) ) {
641 return sprintf( '&#%d;', $point );
647 function hexCharReference( $codepoint ) {
648 $point = hexdec( $codepoint );
649 if( Sanitizer
::validateCodepoint( $point ) ) {
650 return sprintf( '&#x%x;', $point );
657 * Returns true if a given Unicode codepoint is a valid character in XML.
658 * @param int $codepoint
661 function validateCodepoint( $codepoint ) {
662 return ($codepoint == 0x09)
663 ||
($codepoint == 0x0a)
664 ||
($codepoint == 0x0d)
665 ||
($codepoint >= 0x20 && $codepoint <= 0xd7ff)
666 ||
($codepoint >= 0xe000 && $codepoint <= 0xfffd)
667 ||
($codepoint >= 0x10000 && $codepoint <= 0x10ffff);
671 * Decode any character references, numeric or named entities,
672 * in the text and return a UTF-8 string.
674 * @param string $text
678 function decodeCharReferences( $text ) {
679 return preg_replace_callback(
681 array( 'Sanitizer', 'decodeCharReferencesCallback' ),
686 * @param string $matches
689 function decodeCharReferencesCallback( $matches ) {
690 if( $matches[1] != '' ) {
691 return Sanitizer
::decodeEntity( $matches[1] );
692 } elseif( $matches[2] != '' ) {
693 return Sanitizer
::decodeChar( intval( $matches[2] ) );
694 } elseif( $matches[3] != '' ) {
695 return Sanitizer
::decodeChar( hexdec( $matches[3] ) );
696 } elseif( $matches[4] != '' ) {
697 return Sanitizer
::decodeChar( hexdec( $matches[4] ) );
699 # Last case should be an ampersand by itself
704 * Return UTF-8 string for a codepoint if that is a valid
705 * character reference, otherwise U+FFFD REPLACEMENT CHARACTER.
706 * @param int $codepoint
710 function decodeChar( $codepoint ) {
711 if( Sanitizer
::validateCodepoint( $codepoint ) ) {
712 return codepointToUtf8( $codepoint );
714 return UTF8_REPLACEMENT
;
719 * If the named entity is defined in the HTML 4.0/XHTML 1.0 DTD,
720 * return the UTF-8 encoding of that character. Otherwise, returns
721 * pseudo-entity source (eg &foo;)
723 * @param string $name
726 function decodeEntity( $name ) {
727 global $wgHtmlEntities;
728 if( isset( $wgHtmlEntities[$name] ) ) {
729 return codepointToUtf8( $wgHtmlEntities[$name] );
736 * Fetch the whitelist of acceptable attributes for a given
739 * @param string $element
742 function attributeWhitelist( $element ) {
744 if( !isset( $list ) ) {
745 $list = Sanitizer
::setupAttributeWhitelist();
747 return isset( $list[$element] )
755 function setupAttributeWhitelist() {
756 $common = array( 'id', 'class', 'lang', 'dir', 'title', 'style' );
757 $block = array_merge( $common, array( 'align' ) );
758 $tablealign = array( 'align', 'char', 'charoff', 'valign' );
759 $tablecell = array( 'abbr',
765 'nowrap', # deprecated
766 'width', # deprecated
767 'height', # deprecated
768 'bgcolor' # deprecated
771 # Numbers refer to sections in HTML 4.01 standard describing the element.
772 # See: http://www.w3.org/TR/html4/
776 'center' => $common, # deprecated
777 'span' => $block, # ??
806 'blockquote' => array_merge( $common, array( 'cite' ) ),
817 'br' => array( 'id', 'class', 'title', 'style', 'clear' ),
820 'pre' => array_merge( $common, array( 'width' ) ),
823 'ins' => array_merge( $common, array( 'cite', 'datetime' ) ),
824 'del' => array_merge( $common, array( 'cite', 'datetime' ) ),
827 'ul' => array_merge( $common, array( 'type' ) ),
828 'ol' => array_merge( $common, array( 'type', 'start' ) ),
829 'li' => array_merge( $common, array( 'type', 'value' ) ),
837 'table' => array_merge( $common,
838 array( 'summary', 'width', 'border', 'frame',
839 'rules', 'cellspacing', 'cellpadding',
840 'align', 'bgcolor', 'frame', 'rules',
844 'caption' => array_merge( $common, array( 'align' ) ),
847 'thead' => array_merge( $common, $tablealign ),
848 'tfoot' => array_merge( $common, $tablealign ),
849 'tbody' => array_merge( $common, $tablealign ),
852 'colgroup' => array_merge( $common, array( 'span', 'width' ), $tablealign ),
853 'col' => array_merge( $common, array( 'span', 'width' ), $tablealign ),
856 'tr' => array_merge( $common, array( 'bgcolor' ), $tablealign ),
859 'td' => array_merge( $common, $tablecell, $tablealign ),
860 'th' => array_merge( $common, $tablecell, $tablealign ),
873 'font' => array_merge( $common, array( 'size', 'color', 'face' ) ),
877 'hr' => array_merge( $common, array( 'noshade', 'size', 'width' ) ),
879 # XHTML Ruby annotation text module, simple ruby only.
880 # http://www.w3c.org/TR/ruby/
885 'rt' => $common, #array_merge( $common, array( 'rbspan' ) ),
892 * Take a fragment of (potentially invalid) HTML and return
893 * a version with any tags removed, encoded suitably for literal
894 * inclusion in an attribute value.
896 * @param string $text HTML fragment
899 function stripAllTags( $text ) {
901 $text = preg_replace( '/<[^>]*>/', '', $text );
903 # Normalize &entities and whitespace
904 $text = Sanitizer
::normalizeAttributeValue( $text );
906 # Will be placed into "double-quoted" attributes,
907 # make sure remaining bits are safe.
909 array('<', '>', '"'),
910 array('<', '>', '"'),