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 ) == '' ) {
220 # Since we quote this later, this can be anything distinguishable
221 # from the end of the attribute
222 $attrib = '[A-Za-z0-9]';
223 $space = '[\x09\x0a\x0d\x20]';
225 "/(?:^|$space)($attrib+)
228 # The attribute value: quoted or alone
231 | ([a-zA-Z0-9!#$%&()*,\\-.\\/:;<>?@[\\]^_`{|}~]+)
232 | (\#[0-9a-fA-F]+) # Technically wrong, but lots of
233 # colors are specified like this.
234 # We'll be normalizing it.
243 $whitelist = array_flip( Sanitizer
::attributeWhitelist( $element ) );
245 foreach( $pairs as $set ) {
246 $attribute = strtolower( $set[1] );
247 if( !isset( $whitelist[$attribute] ) ) {
249 } elseif( isset( $set[6] ) ) {
250 # Illegal #XXXXXX color with no quotes.
251 $value = Sanitizer
::normalizeAttributeValue( $set[6] );
252 } elseif( isset( $set[5] ) ) {
254 $value = Sanitizer
::normalizeAttributeValue( $set[5] );
255 } elseif( isset( $set[4] ) ) {
257 $value = str_replace( '"', '"',
258 Sanitizer
::normalizeAttributeValue( $set[4] ) );
259 } elseif( isset( $set[3] ) ) {
261 $value = Sanitizer
::normalizeAttributeValue( $set[3] );
262 } elseif( !isset( $set[2] ) ) {
263 # In XHTML, attributes must have a value.
266 wfDebugDieBacktrace( "Tag conditions not met. This should never happen and is a bug." );
269 # Strip javascript "expression" from stylesheets.
270 # http://msdn.microsoft.com/workshop/author/dhtml/overview/recalc.asp
271 if( $attribute == 'style' && preg_match(
272 '/(expression|tps*:\/\/|url\\s*\().*/is',
273 wfMungeToUtf8( $value ) ) ) {
278 if( !isset( $attribs[$attribute] ) ) {
279 $attribs[$attribute] = "$attribute=\"$value\"";
282 if( empty( $attribs ) ) {
285 return ' ' . implode( ' ', $attribs );
290 * Normalize whitespace and character references in an XML source-
291 * encoded text for an attribute value.
293 * See http://www.w3.org/TR/REC-xml/#AVNormalize for background,
294 * but note that we're not returning the value, but are returning
295 * XML source fragments that will be slapped into output.
297 * @param string $text
301 function normalizeAttributeValue( $text ) {
303 '/\r\n|[\x20\x0d\x0a\x09]/',
305 Sanitizer
::normalizeCharReferences( $text ) );
309 * Ensure that any entities and character references are legal
310 * for XML and XHTML specifically. Any stray bits will be
311 * &-escaped to result in a valid text fragment.
313 * a. any named char refs must be known in XHTML
314 * b. any numeric char refs must be legal chars, not invalid or forbidden
315 * c. use &#x, not &#X
316 * d. fix or reject non-valid attributes
318 * @param string $text
322 function normalizeCharReferences( $text ) {
323 return preg_replace_callback(
329 array( 'Sanitizer', 'normalizeCharReferencesCallback' ),
333 * @param string $matches
336 function normalizeCharReferencesCallback( $matches ) {
338 if( $matches[1] != '' ) {
339 $ret = Sanitizer
::normalizeEntity( $matches[1] );
340 } elseif( $matches[2] != '' ) {
341 $ret = Sanitizer
::decCharReference( $matches[2] );
342 } elseif( $matches[3] != '' ) {
343 $ret = Sanitizer
::hexCharReference( $matches[3] );
344 } elseif( $matches[4] != '' ) {
345 $ret = Sanitizer
::hexCharReference( $matches[4] );
347 if( is_null( $ret ) ) {
348 return htmlspecialchars( $matches[0] );
355 * If the named entity is defined in the HTML 4.0/XHTML 1.0 DTD,
356 * return the named entity reference as is. Otherwise, returns
357 * HTML-escaped text of pseudo-entity source (eg &foo;)
359 * @param string $name
362 function normalizeEntity( $name ) {
363 # List of all named character entities defined in HTML 4.01
364 # http://www.w3.org/TR/html4/sgml/entities.html
365 static $htmlEntities = array(
619 if( isset( $htmlEntities[$name] ) ) {
622 return "&$name;";
626 function decCharReference( $codepoint ) {
627 $point = IntVal( $codepoint );
628 if( Sanitizer
::validateCodepoint( $point ) ) {
629 return sprintf( '&#%d;', $point );
635 function hexCharReference( $codepoint ) {
636 $point = hexdec( $codepoint );
637 if( Sanitizer
::validateCodepoint( $point ) ) {
638 return sprintf( '&#x%x;', $point );
645 * Returns true if a given Unicode codepoint is a valid character in XML.
646 * @param int $codepoint
649 function validateCodepoint( $codepoint ) {
650 return ($codepoint == 0x09)
651 ||
($codepoint == 0x0a)
652 ||
($codepoint == 0x0d)
653 ||
($codepoint >= 0x20 && $codepoint <= 0xd7ff)
654 ||
($codepoint >= 0xe000 && $codepoint <= 0xfffd)
655 ||
($codepoint >= 0x10000 && $codepoint <= 0x10ffff);
659 * Fetch the whitelist of acceptable attributes for a given
662 * @param string $element
665 function attributeWhitelist( $element ) {
666 $list = Sanitizer
::setupAttributeWhitelist();
667 return isset( $list[$element] )
675 function setupAttributeWhitelist() {
676 $common = array( 'id', 'class', 'lang', 'dir', 'title', 'style' );
677 $block = array_merge( $common, array( 'align' ) );
678 $tablealign = array( 'align', 'char', 'charoff', 'valign' );
679 $tablecell = array( 'abbr',
685 'nowrap', # deprecated
686 'width', # deprecated
687 'height', # deprecated
688 'bgcolor' # deprecated
691 # Numbers refer to sections in HTML 4.01 standard describing the element.
692 # See: http://www.w3.org/TR/html4/
696 'center' => $common, # deprecated
697 'span' => $block, # ??
726 'blockquote' => array_merge( $common, array( 'cite' ) ),
737 'br' => array( 'id', 'class', 'title', 'style', 'clear' ),
740 'pre' => array_merge( $common, array( 'width' ) ),
743 'ins' => array_merge( $common, array( 'cite', 'datetime' ) ),
744 'del' => array_merge( $common, array( 'cite', 'datetime' ) ),
747 'ul' => array_merge( $common, array( 'type' ) ),
748 'ol' => array_merge( $common, array( 'type', 'start' ) ),
749 'li' => array_merge( $common, array( 'type', 'value' ) ),
757 'table' => array_merge( $common,
758 array( 'summary', 'width', 'border', 'frame',
759 'rules', 'cellspacing', 'cellpadding',
760 'align', 'bgcolor', 'frame', 'rules',
764 'caption' => array_merge( $common, array( 'align' ) ),
767 'thead' => array_merge( $common, $tablealign ),
768 'tfoot' => array_merge( $common, $tablealign ),
769 'tbody' => array_merge( $common, $tablealign ),
772 'colgroup' => array_merge( $common, array( 'span', 'width' ), $tablealign ),
773 'col' => array_merge( $common, array( 'span', 'width' ), $tablealign ),
776 'tr' => array_merge( $common, array( 'bgcolor' ), $tablealign ),
779 'td' => array_merge( $common, $tablecell, $tablealign ),
780 'th' => array_merge( $common, $tablecell, $tablealign ),
793 'font' => array_merge( $common, array( 'size', 'color', 'face' ) ),
797 'hr' => array_merge( $common, array( 'noshade', 'size', 'width' ) ),
799 # XHTML Ruby annotation text module, simple ruby only.
800 # http://www.w3c.org/TR/ruby/
805 'rt' => $common, #array_merge( $common, array( 'rbspan' ) ),
812 * Take a fragment of (potentially invalid) HTML and return
813 * a version with any tags removed, encoded suitably for literal
814 * inclusion in an attribute value.
816 * @param string $text HTML fragment
819 function stripAllTags( $text ) {
821 $text = preg_replace( '/<[^>]*>/', '', $text );
823 # Normalize &entities and whitespace
824 $text = Sanitizer
::normalizeAttributeValue( $text );
826 # Will be placed into "double-quoted" attributes,
827 # make sure remaining bits are safe.
829 array('<', '>', '"'),
830 array('<', '>', '"'),