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
30 * Cleans up HTML, removes dangerous tags and attributes, and
31 * removes HTML comments
36 function removeHTMLtags( $text ) {
37 global $wgUseTidy, $wgUserHtml;
38 $fname = 'Parser::removeHTMLtags';
39 wfProfileIn( $fname );
42 $htmlpairs = array( # Tags that must be closed
43 'b', 'del', 'i', 'ins', 'u', 'font', 'big', 'small', 'sub', 'sup', 'h1',
44 'h2', 'h3', 'h4', 'h5', 'h6', 'cite', 'code', 'em', 's',
45 'strike', 'strong', 'tt', 'var', 'div', 'center',
46 'blockquote', 'ol', 'ul', 'dl', 'table', 'caption', 'pre',
47 'ruby', 'rt' , 'rb' , 'rp', 'p', 'span'
50 'br', 'hr', 'li', 'dt', 'dd'
52 $htmlnest = array( # Tags that can be nested--??
53 'table', 'tr', 'td', 'th', 'div', 'blockquote', 'ol', 'ul',
54 'dl', 'font', 'big', 'small', 'sub', 'sup', 'span'
56 $tabletags = array( # Can only appear inside table
61 $htmlsingle = array();
66 $htmlsingle = array_merge( $tabletags, $htmlsingle );
67 $htmlelements = array_merge( $htmlsingle, $htmlpairs );
69 # Remove HTML comments
70 $text = Sanitizer
::removeHTMLcomments( $text );
72 $bits = explode( '<', $text );
73 $text = array_shift( $bits );
75 $tagstack = array(); $tablestack = array();
76 foreach ( $bits as $x ) {
77 $prev = error_reporting( E_ALL
& ~
( E_NOTICE | E_WARNING
) );
78 preg_match( '/^(\\/?)(\\w+)([^>]*)(\\/{0,1}>)([^<]*)$/',
80 list( $qbar, $slash, $t, $params, $brace, $rest ) = $regs;
81 error_reporting( $prev );
84 if ( in_array( $t = strtolower( $t ), $htmlelements ) ) {
88 if ( ! in_array( $t, $htmlsingle ) &&
89 ( $ot = @array_pop
( $tagstack ) ) != $t ) {
90 @array_push
( $tagstack, $ot );
93 if ( $t == 'table' ) {
94 $tagstack = array_pop( $tablestack );
99 # Keep track for later
100 if ( in_array( $t, $tabletags ) &&
101 ! in_array( 'table', $tagstack ) ) {
103 } else if ( in_array( $t, $tagstack ) &&
104 ! in_array ( $t , $htmlnest ) ) {
106 } else if ( ! in_array( $t, $htmlsingle ) ) {
107 if ( $t == 'table' ) {
108 array_push( $tablestack, $tagstack );
111 array_push( $tagstack, $t );
113 # Strip non-approved attributes from the tag
114 $newparams = Sanitizer
::fixTagAttributes( $params, $t );
117 $rest = str_replace( '>', '>', $rest );
118 $text .= "<$slash$t$newparams$brace$rest";
122 $text .= '<' . str_replace( '>', '>', $x);
124 # Close off any remaining tags
125 while ( is_array( $tagstack ) && ($t = array_pop( $tagstack )) ) {
127 if ( $t == 'table' ) { $tagstack = array_pop( $tablestack ); }
130 # this might be possible using tidy itself
131 foreach ( $bits as $x ) {
132 preg_match( '/^(\\/?)(\\w+)([^>]*)(\\/{0,1}>)([^<]*)$/',
134 @list
( $qbar, $slash, $t, $params, $brace, $rest ) = $regs;
135 if ( in_array( $t = strtolower( $t ), $htmlelements ) ) {
136 $newparams = Sanitizer
::fixTagAttributes( $params, $t );
137 $rest = str_replace( '>', '>', $rest );
138 $text .= "<$slash$t$newparams$brace$rest";
140 $text .= '<' . str_replace( '>', '>', $x);
144 wfProfileOut( $fname );
149 * Remove '<!--', '-->', and everything between.
150 * To avoid leaving blank lines, when a comment is both preceded
151 * and followed by a newline (ignoring spaces), trim leading and
152 * trailing spaces and one of the newlines.
155 * @param string $text
158 function removeHTMLcomments( $text ) {
159 $fname='Parser::removeHTMLcomments';
160 wfProfileIn( $fname );
161 while (($start = strpos($text, '<!--')) !== false) {
162 $end = strpos($text, '-->', $start +
4);
163 if ($end === false) {
164 # Unterminated comment; bail out
170 # Trim space and newline if the comment is both
171 # preceded and followed by a newline
172 $spaceStart = max($start - 1, 0);
173 $spaceLen = $end - $spaceStart;
174 while (substr($text, $spaceStart, 1) === ' ' && $spaceStart > 0) {
178 while (substr($text, $spaceStart +
$spaceLen, 1) === ' ')
180 if (substr($text, $spaceStart, 1) === "\n" and substr($text, $spaceStart +
$spaceLen, 1) === "\n") {
181 # Remove the comment, leading and trailing
182 # spaces, and leave only one newline.
183 $text = substr_replace($text, "\n", $spaceStart, $spaceLen +
1);
186 # Remove just the comment.
187 $text = substr_replace($text, '', $start, $end - $start);
190 wfProfileOut( $fname );
195 * Take a tag soup fragment listing an HTML element's attributes
196 * and normalize it to well-formed XML, discarding unwanted attributes.
198 * - Normalizes attribute names to lowercase
199 * - Discards attributes not on a whitelist for the given element
200 * - Turns broken or invalid entities into plaintext
201 * - Double-quotes all attribute values
202 * - Attributes without values are given the name as attribute
203 * - Double attributes are discarded
204 * - Unsafe style attributes are discarded
205 * - Prepends space if there are attributes.
207 * @param string $text
208 * @param string $element
211 * @todo Check for legal values where the DTD limits things.
212 * @todo Check for unique id attribute :P
214 function fixTagAttributes( $text, $element ) {
215 if( trim( $text ) == '' ) {
219 $attrib = '[A-Za-z0-9]'; #FIXME
220 $space = '[\x09\x0a\x0d\x20]';
222 "/(?:^|$space)($attrib+)
225 # The attribute value: quoted or alone
229 | (\#[0-9a-fA-F]+) # Technically wrong, but lots of
230 # colors are specified like this.
231 # We'll be normalizing it.
240 $whitelist = array_flip( Sanitizer
::attributeWhitelist( $element ) );
242 foreach( $pairs as $set ) {
243 $attribute = strtolower( $set[1] );
244 if( !isset( $whitelist[$attribute] ) ) {
247 if( $set[2] == '' ) {
248 # In XHTML, attributes must have a value.
250 } elseif( $set[3] != '' ) {
252 $value = Sanitizer
::normalizeAttributeValue( $set[3] );
253 } elseif( $set[4] != '' ) {
255 $value = str_replace( '"', '"',
256 Sanitizer
::normalizeAttributeValue( $set[4] ) );
257 } elseif( $set[5] != '' ) {
259 $value = Sanitizer
::normalizeAttributeValue( $set[5] );
260 } elseif( $set[6] != '' ) {
261 # Illegal #XXXXXX color with no quotes.
262 $value = Sanitizer
::normalizeAttributeValue( $set[6] );
264 wfDebugDieBacktrace( "Tag conditions not met. Something's very odd." );
267 # Strip javascript "expression" from stylesheets.
268 # http://msdn.microsoft.com/workshop/author/dhtml/overview/recalc.asp
269 if( $attribute == 'style' && preg_match(
270 '/(expression|tps*:\/\/|url\\s*\().*/is',
271 wfMungeToUtf8( $value ) ) ) {
276 if( !isset( $attribs[$attribute] ) ) {
277 $attribs[$attribute] = "$attribute=\"$value\"";
280 if( empty( $attribs ) ) {
283 return ' ' . implode( ' ', $attribs );
288 * Normalize whitespace and character references in an XML source-
289 * encoded text for an attribute value.
291 * See http://www.w3.org/TR/REC-xml/#AVNormalize for background,
292 * but note that we're not returning the value, but are returning
293 * XML source fragments that will be slapped into output.
295 * @param string $text
299 function normalizeAttributeValue( $text ) {
301 '/\r\n|[\x20\x0d\x0a\x09]/',
303 Sanitizer
::normalizeCharReferences( $text ) );
307 * Ensure that any entities and character references are legal
308 * for XML and XHTML specifically. Any stray bits will be
309 * &-escaped to result in a valid text fragment.
311 * a. any named char refs must be known in XHTML
312 * b. any numeric char refs must be legal chars, not invalid or forbidden
313 * c. use &#x, not &#X
314 * d. fix or reject non-valid attributes
316 * @param string $text
320 function normalizeCharReferences( $text ) {
321 return preg_replace_callback(
327 array( 'Sanitizer', 'normalizeCharReferencesCallback' ),
331 * @param string $matches
334 function normalizeCharReferencesCallback( $matches ) {
336 if( $matches[1] != '' ) {
337 $ret = Sanitizer
::normalizeEntity( $matches[1] );
338 } elseif( $matches[2] != '' ) {
339 $ret = Sanitizer
::decCharReference( $matches[2] );
340 } elseif( $matches[3] != '' ) {
341 $ret = Sanitizer
::hexCharReference( $matches[3] );
342 } elseif( $matches[4] != '' ) {
343 $ret = Sanitizer
::hexCharReference( $matches[4] );
345 if( is_null( $ret ) ) {
346 return htmlspecialchars( $matches[0] );
353 * If the named entity is defined in the HTML 4.0/XHTML 1.0 DTD,
354 * return the named entity reference as is. Otherwise, returns
355 * HTML-escaped text of pseudo-entity source (eg &foo;)
357 * @param string $name
360 function normalizeEntity( $name ) {
361 # List of all named character entities defined in HTML 4.01
362 # http://www.w3.org/TR/html4/sgml/entities.html
363 static $htmlEntities = array(
617 if( isset( $htmlEntities[$name] ) ) {
620 return "&$name;";
624 function decCharReference( $codepoint ) {
625 $point = IntVal( $codepoint );
626 if( Sanitizer
::validateCodepoint( $point ) ) {
627 return sprintf( '&#%d;', $point );
633 function hexCharReference( $codepoint ) {
634 $point = hexdec( $codepoint );
635 if( Sanitizer
::validateCodepoint( $point ) ) {
636 return sprintf( '&#x%x;', $point );
643 * Returns true if a given Unicode codepoint is a valid character in XML.
644 * @param int $codepoint
647 function validateCodepoint( $codepoint ) {
648 return ($codepoint == 0x09)
649 ||
($codepoint == 0x0a)
650 ||
($codepoint == 0x0d)
651 ||
($codepoint >= 0x20 && $codepoint <= 0xd7ff)
652 ||
($codepoint >= 0xe000 && $codepoint <= 0xfffd)
653 ||
($codepoint >= 0x10000 && $codepoint <= 0x10ffff);
657 * Fetch the whitelist of acceptable attributes for a given
660 * @param string $element
663 function attributeWhitelist( $element ) {
664 $list = Sanitizer
::setupAttributeWhitelist();
665 return isset( $list[$element] )
673 function setupAttributeWhitelist() {
674 $common = array( 'id', 'class', 'lang', 'dir', 'title', 'style' );
675 $block = array_merge( $common, array( 'align' ) );
676 $tablealign = array( 'align', 'char', 'charoff', 'valign' );
677 $tablecell = array( 'abbr',
683 'nowrap', # deprecated
684 'width', # deprecated
685 'height' # deprecated
688 # Numbers refer to sections in HTML 4.01 standard describing the element.
689 # See: http://www.w3.org/TR/html4/
693 'center' => $common, # deprecated
694 'span' => $block, # ??
723 'blockquote' => array_merge( $common, array( 'cite' ) ),
734 'br' => array( 'id', 'class', 'title', 'style', 'clear' ),
737 'pre' => array_merge( $common, array( 'width' ) ),
740 'ins' => array_merge( $common, array( 'cite', 'datetime' ) ),
741 'del' => array_merge( $common, array( 'cite', 'datetime' ) ),
744 'ul' => array_merge( $common, array( 'type' ) ),
745 'ol' => array_merge( $common, array( 'type', 'start' ) ),
746 'li' => array_merge( $common, array( 'type', 'value' ) ),
754 'table' => array_merge( $common,
755 array( 'summary', 'width', 'border', 'frame',
756 'rules', 'cellspacing', 'cellpadding',
757 'align', 'bgcolor', 'frame', 'rules',
761 'caption' => array_merge( $common, array( 'align' ) ),
764 'thead' => array_merge( $common, $tablealign ),
765 'tfoot' => array_merge( $common, $tablealign ),
766 'tbody' => array_merge( $common, $tablealign ),
769 'colgroup' => array_merge( $common, array( 'span', 'width' ), $tablealign ),
770 'col' => array_merge( $common, array( 'span', 'width' ), $tablealign ),
773 'tr' => array_merge( $common, array( 'bgcolor' ), $tablealign ),
776 'td' => array_merge( $common, $tablecell, $tablealign ),
777 'th' => array_merge( $common, $tablecell, $tablealign ),
790 'font' => array_merge( $common, array( 'size', 'color', 'face' ) ),
794 'hr' => array_merge( $common, array( 'noshade', 'size', 'width' ) ),
796 # XHTML Ruby annotation text module, simple ruby only.
797 # http://www.w3c.org/TR/ruby/
802 'rt' => $common, #array_merge( $common, array( 'rbspan' ) ),
809 * Take a fragment of (potentially invalid) HTML and return
810 * a version with any tags removed, encoded suitably for literal
811 * inclusion in an attribute value.
813 * @param string $text HTML fragment
816 function stripAllTags( $text ) {
818 $text = preg_replace( '/<[^>]*>/', '', $text );
820 # Normalize &entities and whitespace
821 $text = Sanitizer
::normalizeAttributeValue( $text );
823 # Will be placed into "double-quoted" attributes,
824 # make sure remaining bits are safe.
826 array('<', '>', '"'),
827 array('<', '>', '"'),