Update and fixes.
[mediawiki.git] / includes / Sanitizer.php
blob28b1c27576d08c0dae84c4323b242209d2aa8833
1 <?php
2 /**
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
23 * @file
24 * @ingroup Parser
27 /**
28 * Regular expression to match various types of character references in
29 * Sanitizer::normalizeCharReferences and Sanitizer::decodeCharReferences
31 define( 'MW_CHAR_REFS_REGEX',
32 '/&([A-Za-z0-9\x80-\xff]+);
33 |&\#([0-9]+);
34 |&\#x([0-9A-Za-z]+);
35 |&\#X([0-9A-Za-z]+);
36 |(&)/x' );
38 /**
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+)
47 ($space*=$space*
48 (?:
49 # The attribute value: quoted or alone
50 \"([^<\"]*)\"
51 | '([^<']*)'
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" );
59 /**
60 * List of all named character entities defined in HTML 4.01
61 * http://www.w3.org/TR/html4/sgml/entities.html
62 * @private
64 global $wgHtmlEntities;
65 $wgHtmlEntities = array(
66 'Aacute' => 193,
67 'aacute' => 225,
68 'Acirc' => 194,
69 'acirc' => 226,
70 'acute' => 180,
71 'AElig' => 198,
72 'aelig' => 230,
73 'Agrave' => 192,
74 'agrave' => 224,
75 'alefsym' => 8501,
76 'Alpha' => 913,
77 'alpha' => 945,
78 'amp' => 38,
79 'and' => 8743,
80 'ang' => 8736,
81 'Aring' => 197,
82 'aring' => 229,
83 'asymp' => 8776,
84 'Atilde' => 195,
85 'atilde' => 227,
86 'Auml' => 196,
87 'auml' => 228,
88 'bdquo' => 8222,
89 'Beta' => 914,
90 'beta' => 946,
91 'brvbar' => 166,
92 'bull' => 8226,
93 'cap' => 8745,
94 'Ccedil' => 199,
95 'ccedil' => 231,
96 'cedil' => 184,
97 'cent' => 162,
98 'Chi' => 935,
99 'chi' => 967,
100 'circ' => 710,
101 'clubs' => 9827,
102 'cong' => 8773,
103 'copy' => 169,
104 'crarr' => 8629,
105 'cup' => 8746,
106 'curren' => 164,
107 'dagger' => 8224,
108 'Dagger' => 8225,
109 'darr' => 8595,
110 'dArr' => 8659,
111 'deg' => 176,
112 'Delta' => 916,
113 'delta' => 948,
114 'diams' => 9830,
115 'divide' => 247,
116 'Eacute' => 201,
117 'eacute' => 233,
118 'Ecirc' => 202,
119 'ecirc' => 234,
120 'Egrave' => 200,
121 'egrave' => 232,
122 'empty' => 8709,
123 'emsp' => 8195,
124 'ensp' => 8194,
125 'Epsilon' => 917,
126 'epsilon' => 949,
127 'equiv' => 8801,
128 'Eta' => 919,
129 'eta' => 951,
130 'ETH' => 208,
131 'eth' => 240,
132 'Euml' => 203,
133 'euml' => 235,
134 'euro' => 8364,
135 'exist' => 8707,
136 'fnof' => 402,
137 'forall' => 8704,
138 'frac12' => 189,
139 'frac14' => 188,
140 'frac34' => 190,
141 'frasl' => 8260,
142 'Gamma' => 915,
143 'gamma' => 947,
144 'ge' => 8805,
145 'gt' => 62,
146 'harr' => 8596,
147 'hArr' => 8660,
148 'hearts' => 9829,
149 'hellip' => 8230,
150 'Iacute' => 205,
151 'iacute' => 237,
152 'Icirc' => 206,
153 'icirc' => 238,
154 'iexcl' => 161,
155 'Igrave' => 204,
156 'igrave' => 236,
157 'image' => 8465,
158 'infin' => 8734,
159 'int' => 8747,
160 'Iota' => 921,
161 'iota' => 953,
162 'iquest' => 191,
163 'isin' => 8712,
164 'Iuml' => 207,
165 'iuml' => 239,
166 'Kappa' => 922,
167 'kappa' => 954,
168 'Lambda' => 923,
169 'lambda' => 955,
170 'lang' => 9001,
171 'laquo' => 171,
172 'larr' => 8592,
173 'lArr' => 8656,
174 'lceil' => 8968,
175 'ldquo' => 8220,
176 'le' => 8804,
177 'lfloor' => 8970,
178 'lowast' => 8727,
179 'loz' => 9674,
180 'lrm' => 8206,
181 'lsaquo' => 8249,
182 'lsquo' => 8216,
183 'lt' => 60,
184 'macr' => 175,
185 'mdash' => 8212,
186 'micro' => 181,
187 'middot' => 183,
188 'minus' => 8722,
189 'Mu' => 924,
190 'mu' => 956,
191 'nabla' => 8711,
192 'nbsp' => 160,
193 'ndash' => 8211,
194 'ne' => 8800,
195 'ni' => 8715,
196 'not' => 172,
197 'notin' => 8713,
198 'nsub' => 8836,
199 'Ntilde' => 209,
200 'ntilde' => 241,
201 'Nu' => 925,
202 'nu' => 957,
203 'Oacute' => 211,
204 'oacute' => 243,
205 'Ocirc' => 212,
206 'ocirc' => 244,
207 'OElig' => 338,
208 'oelig' => 339,
209 'Ograve' => 210,
210 'ograve' => 242,
211 'oline' => 8254,
212 'Omega' => 937,
213 'omega' => 969,
214 'Omicron' => 927,
215 'omicron' => 959,
216 'oplus' => 8853,
217 'or' => 8744,
218 'ordf' => 170,
219 'ordm' => 186,
220 'Oslash' => 216,
221 'oslash' => 248,
222 'Otilde' => 213,
223 'otilde' => 245,
224 'otimes' => 8855,
225 'Ouml' => 214,
226 'ouml' => 246,
227 'para' => 182,
228 'part' => 8706,
229 'permil' => 8240,
230 'perp' => 8869,
231 'Phi' => 934,
232 'phi' => 966,
233 'Pi' => 928,
234 'pi' => 960,
235 'piv' => 982,
236 'plusmn' => 177,
237 'pound' => 163,
238 'prime' => 8242,
239 'Prime' => 8243,
240 'prod' => 8719,
241 'prop' => 8733,
242 'Psi' => 936,
243 'psi' => 968,
244 'quot' => 34,
245 'radic' => 8730,
246 'rang' => 9002,
247 'raquo' => 187,
248 'rarr' => 8594,
249 'rArr' => 8658,
250 'rceil' => 8969,
251 'rdquo' => 8221,
252 'real' => 8476,
253 'reg' => 174,
254 'rfloor' => 8971,
255 'Rho' => 929,
256 'rho' => 961,
257 'rlm' => 8207,
258 'rsaquo' => 8250,
259 'rsquo' => 8217,
260 'sbquo' => 8218,
261 'Scaron' => 352,
262 'scaron' => 353,
263 'sdot' => 8901,
264 'sect' => 167,
265 'shy' => 173,
266 'Sigma' => 931,
267 'sigma' => 963,
268 'sigmaf' => 962,
269 'sim' => 8764,
270 'spades' => 9824,
271 'sub' => 8834,
272 'sube' => 8838,
273 'sum' => 8721,
274 'sup' => 8835,
275 'sup1' => 185,
276 'sup2' => 178,
277 'sup3' => 179,
278 'supe' => 8839,
279 'szlig' => 223,
280 'Tau' => 932,
281 'tau' => 964,
282 'there4' => 8756,
283 'Theta' => 920,
284 'theta' => 952,
285 'thetasym' => 977,
286 'thinsp' => 8201,
287 'THORN' => 222,
288 'thorn' => 254,
289 'tilde' => 732,
290 'times' => 215,
291 'trade' => 8482,
292 'Uacute' => 218,
293 'uacute' => 250,
294 'uarr' => 8593,
295 'uArr' => 8657,
296 'Ucirc' => 219,
297 'ucirc' => 251,
298 'Ugrave' => 217,
299 'ugrave' => 249,
300 'uml' => 168,
301 'upsih' => 978,
302 'Upsilon' => 933,
303 'upsilon' => 965,
304 'Uuml' => 220,
305 'uuml' => 252,
306 'weierp' => 8472,
307 'Xi' => 926,
308 'xi' => 958,
309 'Yacute' => 221,
310 'yacute' => 253,
311 'yen' => 165,
312 'Yuml' => 376,
313 'yuml' => 255,
314 'Zeta' => 918,
315 'zeta' => 950,
316 'zwj' => 8205,
317 'zwnj' => 8204 );
320 * Character entity aliases accepted by MediaWiki
322 global $wgHtmlEntityAliases;
323 $wgHtmlEntityAliases = array(
324 'רלמ' => 'rlm',
325 'رلم' => 'rlm',
330 * XHTML sanitizer for MediaWiki
331 * @ingroup Parser
333 class Sanitizer {
334 const NONE = 0;
335 const INITIAL_NONLETTER = 1;
338 * Cleans up HTML, removes dangerous tags and attributes, and
339 * removes HTML comments
340 * @private
341 * @param string $text
342 * @param callback $processCallback to do any variable or parameter replacements in HTML attribute values
343 * @param array $args for the processing callback
344 * @return string
346 static function removeHTMLtags( $text, $processCallback = null, $args = array(), $extratags = array() ) {
347 global $wgUseTidy;
349 static $htmlpairs, $htmlsingle, $htmlsingleonly, $htmlnest, $tabletags,
350 $htmllist, $listtags, $htmlsingleallowed, $htmlelements, $staticInitialised;
352 wfProfileIn( __METHOD__ );
354 if ( !$staticInitialised ) {
356 $htmlpairs = array_merge( $extratags, array( # Tags that must be closed
357 'b', 'del', 'i', 'ins', 'u', 'font', 'big', 'small', 'sub', 'sup', 'h1',
358 'h2', 'h3', 'h4', 'h5', 'h6', 'cite', 'code', 'em', 's',
359 'strike', 'strong', 'tt', 'var', 'div', 'center',
360 'blockquote', 'ol', 'ul', 'dl', 'table', 'caption', 'pre',
361 'ruby', 'rt' , 'rb' , 'rp', 'p', 'span', 'u'
362 ) );
363 $htmlsingle = array(
364 'br', 'hr', 'li', 'dt', 'dd'
366 $htmlsingleonly = array( # Elements that cannot have close tags
367 'br', 'hr'
369 $htmlnest = array( # Tags that can be nested--??
370 'table', 'tr', 'td', 'th', 'div', 'blockquote', 'ol', 'ul',
371 'dl', 'font', 'big', 'small', 'sub', 'sup', 'span'
373 $tabletags = array( # Can only appear inside table, we will close them
374 'td', 'th', 'tr',
376 $htmllist = array( # Tags used by list
377 'ul','ol',
379 $listtags = array( # Tags that can appear in a list
380 'li',
383 $htmlsingleallowed = array_merge( $htmlsingle, $tabletags );
384 $htmlelements = array_merge( $htmlsingle, $htmlpairs, $htmlnest );
386 # Convert them all to hashtables for faster lookup
387 $vars = array( 'htmlpairs', 'htmlsingle', 'htmlsingleonly', 'htmlnest', 'tabletags',
388 'htmllist', 'listtags', 'htmlsingleallowed', 'htmlelements' );
389 foreach ( $vars as $var ) {
390 $$var = array_flip( $$var );
392 $staticInitialised = true;
395 # Remove HTML comments
396 $text = Sanitizer::removeHTMLcomments( $text );
397 $bits = explode( '<', $text );
398 $text = str_replace( '>', '&gt;', array_shift( $bits ) );
399 if(!$wgUseTidy) {
400 $tagstack = $tablestack = array();
401 foreach ( $bits as $x ) {
402 $regs = array();
403 if( preg_match( '!^(/?)(\\w+)([^>]*?)(/{0,1}>)([^<]*)$!', $x, $regs ) ) {
404 list( /* $qbar */, $slash, $t, $params, $brace, $rest ) = $regs;
405 } else {
406 $slash = $t = $params = $brace = $rest = null;
409 $badtag = 0 ;
410 if ( isset( $htmlelements[$t = strtolower( $t )] ) ) {
411 # Check our stack
412 if ( $slash ) {
413 # Closing a tag...
414 if( isset( $htmlsingleonly[$t] ) ) {
415 $badtag = 1;
416 } elseif ( ( $ot = @array_pop( $tagstack ) ) != $t ) {
417 if ( isset( $htmlsingleallowed[$ot] ) ) {
418 # Pop all elements with an optional close tag
419 # and see if we find a match below them
420 $optstack = array();
421 array_push ($optstack, $ot);
422 while ( ( ( $ot = @array_pop( $tagstack ) ) != $t ) &&
423 isset( $htmlsingleallowed[$ot] ) )
425 array_push ($optstack, $ot);
427 if ( $t != $ot ) {
428 # No match. Push the optinal elements back again
429 $badtag = 1;
430 while ( $ot = @array_pop( $optstack ) ) {
431 array_push( $tagstack, $ot );
434 } else {
435 @array_push( $tagstack, $ot );
436 # <li> can be nested in <ul> or <ol>, skip those cases:
437 if(!(isset( $htmllist[$ot] ) && isset( $listtags[$t] ) )) {
438 $badtag = 1;
441 } else {
442 if ( $t == 'table' ) {
443 $tagstack = array_pop( $tablestack );
446 $newparams = '';
447 } else {
448 # Keep track for later
449 if ( isset( $tabletags[$t] ) &&
450 ! in_array( 'table', $tagstack ) ) {
451 $badtag = 1;
452 } else if ( in_array( $t, $tagstack ) &&
453 ! isset( $htmlnest [$t ] ) ) {
454 $badtag = 1 ;
455 # Is it a self closed htmlpair ? (bug 5487)
456 } else if( $brace == '/>' &&
457 isset( $htmlpairs[$t] ) ) {
458 $badtag = 1;
459 } elseif( isset( $htmlsingleonly[$t] ) ) {
460 # Hack to force empty tag for uncloseable elements
461 $brace = '/>';
462 } else if( isset( $htmlsingle[$t] ) ) {
463 # Hack to not close $htmlsingle tags
464 $brace = NULL;
465 } else if( isset( $tabletags[$t] )
466 && in_array($t ,$tagstack) ) {
467 // New table tag but forgot to close the previous one
468 $text .= "</$t>";
469 } else {
470 if ( $t == 'table' ) {
471 array_push( $tablestack, $tagstack );
472 $tagstack = array();
474 array_push( $tagstack, $t );
477 # Replace any variables or template parameters with
478 # plaintext results.
479 if( is_callable( $processCallback ) ) {
480 call_user_func_array( $processCallback, array( &$params, $args ) );
483 # Strip non-approved attributes from the tag
484 $newparams = Sanitizer::fixTagAttributes( $params, $t );
486 if ( ! $badtag ) {
487 $rest = str_replace( '>', '&gt;', $rest );
488 $close = ( $brace == '/>' && !$slash ) ? ' /' : '';
489 $text .= "<$slash$t$newparams$close>$rest";
490 continue;
493 $text .= '&lt;' . str_replace( '>', '&gt;', $x);
495 # Close off any remaining tags
496 while ( is_array( $tagstack ) && ($t = array_pop( $tagstack )) ) {
497 $text .= "</$t>\n";
498 if ( $t == 'table' ) { $tagstack = array_pop( $tablestack ); }
500 } else {
501 # this might be possible using tidy itself
502 foreach ( $bits as $x ) {
503 preg_match( '/^(\\/?)(\\w+)([^>]*?)(\\/{0,1}>)([^<]*)$/',
504 $x, $regs );
505 @list( /* $qbar */, $slash, $t, $params, $brace, $rest ) = $regs;
506 if ( isset( $htmlelements[$t = strtolower( $t )] ) ) {
507 if( is_callable( $processCallback ) ) {
508 call_user_func_array( $processCallback, array( &$params, $args ) );
510 $newparams = Sanitizer::fixTagAttributes( $params, $t );
511 $rest = str_replace( '>', '&gt;', $rest );
512 $text .= "<$slash$t$newparams$brace$rest";
513 } else {
514 $text .= '&lt;' . str_replace( '>', '&gt;', $x);
518 wfProfileOut( __METHOD__ );
519 return $text;
523 * Remove '<!--', '-->', and everything between.
524 * To avoid leaving blank lines, when a comment is both preceded
525 * and followed by a newline (ignoring spaces), trim leading and
526 * trailing spaces and one of the newlines.
528 * @private
529 * @param string $text
530 * @return string
532 static function removeHTMLcomments( $text ) {
533 wfProfileIn( __METHOD__ );
534 while (($start = strpos($text, '<!--')) !== false) {
535 $end = strpos($text, '-->', $start + 4);
536 if ($end === false) {
537 # Unterminated comment; bail out
538 break;
541 $end += 3;
543 # Trim space and newline if the comment is both
544 # preceded and followed by a newline
545 $spaceStart = max($start - 1, 0);
546 $spaceLen = $end - $spaceStart;
547 while (substr($text, $spaceStart, 1) === ' ' && $spaceStart > 0) {
548 $spaceStart--;
549 $spaceLen++;
551 while (substr($text, $spaceStart + $spaceLen, 1) === ' ')
552 $spaceLen++;
553 if (substr($text, $spaceStart, 1) === "\n" and substr($text, $spaceStart + $spaceLen, 1) === "\n") {
554 # Remove the comment, leading and trailing
555 # spaces, and leave only one newline.
556 $text = substr_replace($text, "\n", $spaceStart, $spaceLen + 1);
558 else {
559 # Remove just the comment.
560 $text = substr_replace($text, '', $start, $end - $start);
563 wfProfileOut( __METHOD__ );
564 return $text;
568 * Take an array of attribute names and values and normalize or discard
569 * illegal values for the given element type.
571 * - Discards attributes not on a whitelist for the given element
572 * - Unsafe style attributes are discarded
573 * - Invalid id attributes are reencoded
575 * @param array $attribs
576 * @param string $element
577 * @return array
579 * @todo Check for legal values where the DTD limits things.
580 * @todo Check for unique id attribute :P
582 static function validateTagAttributes( $attribs, $element ) {
583 return Sanitizer::validateAttributes( $attribs,
584 Sanitizer::attributeWhitelist( $element ) );
588 * Take an array of attribute names and values and normalize or discard
589 * illegal values for the given whitelist.
591 * - Discards attributes not the given whitelist
592 * - Unsafe style attributes are discarded
593 * - Invalid id attributes are reencoded
595 * @param array $attribs
596 * @param array $whitelist list of allowed attribute names
597 * @return array
599 * @todo Check for legal values where the DTD limits things.
600 * @todo Check for unique id attribute :P
602 static function validateAttributes( $attribs, $whitelist ) {
603 $whitelist = array_flip( $whitelist );
604 $out = array();
605 foreach( $attribs as $attribute => $value ) {
606 if( !isset( $whitelist[$attribute] ) ) {
607 continue;
609 # Strip javascript "expression" from stylesheets.
610 # http://msdn.microsoft.com/workshop/author/dhtml/overview/recalc.asp
611 if( $attribute == 'style' ) {
612 $value = Sanitizer::checkCss( $value );
613 if( $value === false ) {
614 # haxx0r
615 continue;
619 if ( $attribute === 'id' )
620 $value = Sanitizer::escapeId( $value );
622 // If this attribute was previously set, override it.
623 // Output should only have one attribute of each name.
624 $out[$attribute] = $value;
626 return $out;
630 * Merge two sets of HTML attributes.
631 * Conflicting items in the second set will override those
632 * in the first, except for 'class' attributes which will be
633 * combined.
635 * @todo implement merging for other attributes such as style
636 * @param array $a
637 * @param array $b
638 * @return array
640 static function mergeAttributes( $a, $b ) {
641 $out = array_merge( $a, $b );
642 if( isset( $a['class'] )
643 && isset( $b['class'] )
644 && $a['class'] !== $b['class'] ) {
646 $out['class'] = implode( ' ',
647 array_unique(
648 preg_split( '/\s+/',
649 $a['class'] . ' ' . $b['class'],
651 PREG_SPLIT_NO_EMPTY ) ) );
653 return $out;
657 * Pick apart some CSS and check it for forbidden or unsafe structures.
658 * Returns a sanitized string, or false if it was just too evil.
660 * Currently URL references, 'expression', 'tps' are forbidden.
662 * @param string $value
663 * @return mixed
665 static function checkCss( $value ) {
666 $stripped = Sanitizer::decodeCharReferences( $value );
668 // Remove any comments; IE gets token splitting wrong
669 $stripped = StringUtils::delimiterReplace( '/*', '*/', ' ', $stripped );
671 $value = $stripped;
673 // ... and continue checks
674 $stripped = preg_replace( '!\\\\([0-9A-Fa-f]{1,6})[ \\n\\r\\t\\f]?!e',
675 'codepointToUtf8(hexdec("$1"))', $stripped );
676 $stripped = str_replace( '\\', '', $stripped );
677 if( preg_match( '/(?:expression|tps*:\/\/|url\\s*\().*/is',
678 $stripped ) ) {
679 # haxx0r
680 return false;
683 return $value;
687 * Take a tag soup fragment listing an HTML element's attributes
688 * and normalize it to well-formed XML, discarding unwanted attributes.
689 * Output is safe for further wikitext processing, with escaping of
690 * values that could trigger problems.
692 * - Normalizes attribute names to lowercase
693 * - Discards attributes not on a whitelist for the given element
694 * - Turns broken or invalid entities into plaintext
695 * - Double-quotes all attribute values
696 * - Attributes without values are given the name as attribute
697 * - Double attributes are discarded
698 * - Unsafe style attributes are discarded
699 * - Prepends space if there are attributes.
701 * @param string $text
702 * @param string $element
703 * @return string
705 static function fixTagAttributes( $text, $element ) {
706 if( trim( $text ) == '' ) {
707 return '';
710 $stripped = Sanitizer::validateTagAttributes(
711 Sanitizer::decodeTagAttributes( $text ), $element );
713 $attribs = array();
714 foreach( $stripped as $attribute => $value ) {
715 $encAttribute = htmlspecialchars( $attribute );
716 $encValue = Sanitizer::safeEncodeAttribute( $value );
718 $attribs[] = "$encAttribute=\"$encValue\"";
720 return count( $attribs ) ? ' ' . implode( ' ', $attribs ) : '';
724 * Encode an attribute value for HTML output.
725 * @param $text
726 * @return HTML-encoded text fragment
728 static function encodeAttribute( $text ) {
729 $encValue = htmlspecialchars( $text, ENT_QUOTES );
731 // Whitespace is normalized during attribute decoding,
732 // so if we've been passed non-spaces we must encode them
733 // ahead of time or they won't be preserved.
734 $encValue = strtr( $encValue, array(
735 "\n" => '&#10;',
736 "\r" => '&#13;',
737 "\t" => '&#9;',
738 ) );
740 return $encValue;
744 * Encode an attribute value for HTML tags, with extra armoring
745 * against further wiki processing.
746 * @param $text
747 * @return HTML-encoded text fragment
749 static function safeEncodeAttribute( $text ) {
750 $encValue = Sanitizer::encodeAttribute( $text );
752 # Templates and links may be expanded in later parsing,
753 # creating invalid or dangerous output. Suppress this.
754 $encValue = strtr( $encValue, array(
755 '<' => '&lt;', // This should never happen,
756 '>' => '&gt;', // we've received invalid input
757 '"' => '&quot;', // which should have been escaped.
758 '{' => '&#123;',
759 '[' => '&#91;',
760 "''" => '&#39;&#39;',
761 'ISBN' => '&#73;SBN',
762 'RFC' => '&#82;FC',
763 'PMID' => '&#80;MID',
764 '|' => '&#124;',
765 '__' => '&#95;_',
766 ) );
768 # Stupid hack
769 $encValue = preg_replace_callback(
770 '/(' . wfUrlProtocols() . ')/',
771 array( 'Sanitizer', 'armorLinksCallback' ),
772 $encValue );
773 return $encValue;
777 * Given a value escape it so that it can be used in an id attribute and
778 * return it, this does not validate the value however (see first link)
780 * @see http://www.w3.org/TR/html401/types.html#type-name Valid characters
781 * in the id and
782 * name attributes
783 * @see http://www.w3.org/TR/html401/struct/links.html#h-12.2.3 Anchors with the id attribute
785 * @param string $id Id to validate
786 * @param int $flags Currently only two values: Sanitizer::INITIAL_NONLETTER
787 * (default) permits initial non-letter characters,
788 * such as if you're adding a prefix to them.
789 * Sanitizer::NONE will prepend an 'x' if the id
790 * would otherwise start with a nonletter.
791 * @return string
793 static function escapeId( $id, $flags = Sanitizer::INITIAL_NONLETTER ) {
794 static $replace = array(
795 '%3A' => ':',
796 '%' => '.'
799 $id = urlencode( Sanitizer::decodeCharReferences( strtr( $id, ' ', '_' ) ) );
800 $id = str_replace( array_keys( $replace ), array_values( $replace ), $id );
802 if( ~$flags & Sanitizer::INITIAL_NONLETTER
803 && !preg_match( '/[a-zA-Z]/', $id[0] ) ) {
804 // Initial character must be a letter!
805 $id = "x$id";
807 return $id;
811 * Given a value, escape it so that it can be used as a CSS class and
812 * return it.
814 * @todo For extra validity, input should be validated UTF-8.
816 * @see http://www.w3.org/TR/CSS21/syndata.html Valid characters/format
818 * @param string $class
819 * @return string
821 static function escapeClass( $class ) {
822 // Convert ugly stuff to underscores and kill underscores in ugly places
823 return rtrim(preg_replace(
824 array('/(^[0-9\\-])|[\\x00-\\x20!"#$%&\'()*+,.\\/:;<=>?@[\\]^`{|}~]|\\xC2\\xA0/','/_+/'),
825 '_',
826 $class ), '_');
830 * Regex replace callback for armoring links against further processing.
831 * @param array $matches
832 * @return string
833 * @private
835 private static function armorLinksCallback( $matches ) {
836 return str_replace( ':', '&#58;', $matches[1] );
840 * Return an associative array of attribute names and values from
841 * a partial tag string. Attribute names are forces to lowercase,
842 * character references are decoded to UTF-8 text.
844 * @param string
845 * @return array
847 static function decodeTagAttributes( $text ) {
848 $attribs = array();
850 if( trim( $text ) == '' ) {
851 return $attribs;
854 $pairs = array();
855 if( !preg_match_all(
856 MW_ATTRIBS_REGEX,
857 $text,
858 $pairs,
859 PREG_SET_ORDER ) ) {
860 return $attribs;
863 foreach( $pairs as $set ) {
864 $attribute = strtolower( $set[1] );
865 $value = Sanitizer::getTagAttributeCallback( $set );
867 // Normalize whitespace
868 $value = preg_replace( '/[\t\r\n ]+/', ' ', $value );
869 $value = trim( $value );
871 // Decode character references
872 $attribs[$attribute] = Sanitizer::decodeCharReferences( $value );
874 return $attribs;
878 * Pick the appropriate attribute value from a match set from the
879 * MW_ATTRIBS_REGEX matches.
881 * @param array $set
882 * @return string
883 * @private
885 private static function getTagAttributeCallback( $set ) {
886 if( isset( $set[6] ) ) {
887 # Illegal #XXXXXX color with no quotes.
888 return $set[6];
889 } elseif( isset( $set[5] ) ) {
890 # No quotes.
891 return $set[5];
892 } elseif( isset( $set[4] ) ) {
893 # Single-quoted
894 return $set[4];
895 } elseif( isset( $set[3] ) ) {
896 # Double-quoted
897 return $set[3];
898 } elseif( !isset( $set[2] ) ) {
899 # In XHTML, attributes must have a value.
900 # For 'reduced' form, return explicitly the attribute name here.
901 return $set[1];
902 } else {
903 throw new MWException( "Tag conditions not met. This should never happen and is a bug." );
908 * Normalize whitespace and character references in an XML source-
909 * encoded text for an attribute value.
911 * See http://www.w3.org/TR/REC-xml/#AVNormalize for background,
912 * but note that we're not returning the value, but are returning
913 * XML source fragments that will be slapped into output.
915 * @param string $text
916 * @return string
917 * @private
919 private static function normalizeAttributeValue( $text ) {
920 return str_replace( '"', '&quot;',
921 self::normalizeWhitespace(
922 Sanitizer::normalizeCharReferences( $text ) ) );
925 private static function normalizeWhitespace( $text ) {
926 return preg_replace(
927 '/\r\n|[\x20\x0d\x0a\x09]/',
928 ' ',
929 $text );
933 * Ensure that any entities and character references are legal
934 * for XML and XHTML specifically. Any stray bits will be
935 * &amp;-escaped to result in a valid text fragment.
937 * a. any named char refs must be known in XHTML
938 * b. any numeric char refs must be legal chars, not invalid or forbidden
939 * c. use &#x, not &#X
940 * d. fix or reject non-valid attributes
942 * @param string $text
943 * @return string
944 * @private
946 static function normalizeCharReferences( $text ) {
947 return preg_replace_callback(
948 MW_CHAR_REFS_REGEX,
949 array( 'Sanitizer', 'normalizeCharReferencesCallback' ),
950 $text );
953 * @param string $matches
954 * @return string
956 static function normalizeCharReferencesCallback( $matches ) {
957 $ret = null;
958 if( $matches[1] != '' ) {
959 $ret = Sanitizer::normalizeEntity( $matches[1] );
960 } elseif( $matches[2] != '' ) {
961 $ret = Sanitizer::decCharReference( $matches[2] );
962 } elseif( $matches[3] != '' ) {
963 $ret = Sanitizer::hexCharReference( $matches[3] );
964 } elseif( $matches[4] != '' ) {
965 $ret = Sanitizer::hexCharReference( $matches[4] );
967 if( is_null( $ret ) ) {
968 return htmlspecialchars( $matches[0] );
969 } else {
970 return $ret;
975 * If the named entity is defined in the HTML 4.0/XHTML 1.0 DTD,
976 * return the named entity reference as is. If the entity is a
977 * MediaWiki-specific alias, returns the HTML equivalent. Otherwise,
978 * returns HTML-escaped text of pseudo-entity source (eg &amp;foo;)
980 * @param string $name
981 * @return string
982 * @static
984 static function normalizeEntity( $name ) {
985 global $wgHtmlEntities, $wgHtmlEntityAliases;
986 if ( isset( $wgHtmlEntityAliases[$name] ) ) {
987 return "&{$wgHtmlEntityAliases[$name]};";
988 } elseif( isset( $wgHtmlEntities[$name] ) ) {
989 return "&$name;";
990 } else {
991 return "&amp;$name;";
995 static function decCharReference( $codepoint ) {
996 $point = intval( $codepoint );
997 if( Sanitizer::validateCodepoint( $point ) ) {
998 return sprintf( '&#%d;', $point );
999 } else {
1000 return null;
1004 static function hexCharReference( $codepoint ) {
1005 $point = hexdec( $codepoint );
1006 if( Sanitizer::validateCodepoint( $point ) ) {
1007 return sprintf( '&#x%x;', $point );
1008 } else {
1009 return null;
1014 * Returns true if a given Unicode codepoint is a valid character in XML.
1015 * @param int $codepoint
1016 * @return bool
1018 private static function validateCodepoint( $codepoint ) {
1019 return ($codepoint == 0x09)
1020 || ($codepoint == 0x0a)
1021 || ($codepoint == 0x0d)
1022 || ($codepoint >= 0x20 && $codepoint <= 0xd7ff)
1023 || ($codepoint >= 0xe000 && $codepoint <= 0xfffd)
1024 || ($codepoint >= 0x10000 && $codepoint <= 0x10ffff);
1028 * Decode any character references, numeric or named entities,
1029 * in the text and return a UTF-8 string.
1031 * @param string $text
1032 * @return string
1033 * @public
1034 * @static
1036 public static function decodeCharReferences( $text ) {
1037 return preg_replace_callback(
1038 MW_CHAR_REFS_REGEX,
1039 array( 'Sanitizer', 'decodeCharReferencesCallback' ),
1040 $text );
1044 * @param string $matches
1045 * @return string
1047 static function decodeCharReferencesCallback( $matches ) {
1048 if( $matches[1] != '' ) {
1049 return Sanitizer::decodeEntity( $matches[1] );
1050 } elseif( $matches[2] != '' ) {
1051 return Sanitizer::decodeChar( intval( $matches[2] ) );
1052 } elseif( $matches[3] != '' ) {
1053 return Sanitizer::decodeChar( hexdec( $matches[3] ) );
1054 } elseif( $matches[4] != '' ) {
1055 return Sanitizer::decodeChar( hexdec( $matches[4] ) );
1057 # Last case should be an ampersand by itself
1058 return $matches[0];
1062 * Return UTF-8 string for a codepoint if that is a valid
1063 * character reference, otherwise U+FFFD REPLACEMENT CHARACTER.
1064 * @param int $codepoint
1065 * @return string
1066 * @private
1068 static function decodeChar( $codepoint ) {
1069 if( Sanitizer::validateCodepoint( $codepoint ) ) {
1070 return codepointToUtf8( $codepoint );
1071 } else {
1072 return UTF8_REPLACEMENT;
1077 * If the named entity is defined in the HTML 4.0/XHTML 1.0 DTD,
1078 * return the UTF-8 encoding of that character. Otherwise, returns
1079 * pseudo-entity source (eg &foo;)
1081 * @param string $name
1082 * @return string
1084 static function decodeEntity( $name ) {
1085 global $wgHtmlEntities, $wgHtmlEntityAliases;
1086 if ( isset( $wgHtmlEntityAliases[$name] ) ) {
1087 $name = $wgHtmlEntityAliases[$name];
1089 if( isset( $wgHtmlEntities[$name] ) ) {
1090 return codepointToUtf8( $wgHtmlEntities[$name] );
1091 } else {
1092 return "&$name;";
1097 * Fetch the whitelist of acceptable attributes for a given
1098 * element name.
1100 * @param string $element
1101 * @return array
1103 static function attributeWhitelist( $element ) {
1104 static $list;
1105 if( !isset( $list ) ) {
1106 $list = Sanitizer::setupAttributeWhitelist();
1108 return isset( $list[$element] )
1109 ? $list[$element]
1110 : array();
1114 * @todo Document it a bit
1115 * @return array
1117 static function setupAttributeWhitelist() {
1118 $common = array( 'id', 'class', 'lang', 'dir', 'title', 'style' );
1119 $block = array_merge( $common, array( 'align' ) );
1120 $tablealign = array( 'align', 'char', 'charoff', 'valign' );
1121 $tablecell = array( 'abbr',
1122 'axis',
1123 'headers',
1124 'scope',
1125 'rowspan',
1126 'colspan',
1127 'nowrap', # deprecated
1128 'width', # deprecated
1129 'height', # deprecated
1130 'bgcolor' # deprecated
1133 # Numbers refer to sections in HTML 4.01 standard describing the element.
1134 # See: http://www.w3.org/TR/html4/
1135 $whitelist = array (
1136 # 7.5.4
1137 'div' => $block,
1138 'center' => $common, # deprecated
1139 'span' => $block, # ??
1141 # 7.5.5
1142 'h1' => $block,
1143 'h2' => $block,
1144 'h3' => $block,
1145 'h4' => $block,
1146 'h5' => $block,
1147 'h6' => $block,
1149 # 7.5.6
1150 # address
1152 # 8.2.4
1153 # bdo
1155 # 9.2.1
1156 'em' => $common,
1157 'strong' => $common,
1158 'cite' => $common,
1159 # dfn
1160 'code' => $common,
1161 # samp
1162 # kbd
1163 'var' => $common,
1164 # abbr
1165 # acronym
1167 # 9.2.2
1168 'blockquote' => array_merge( $common, array( 'cite' ) ),
1171 # 9.2.3
1172 'sub' => $common,
1173 'sup' => $common,
1175 # 9.3.1
1176 'p' => $block,
1178 # 9.3.2
1179 'br' => array( 'id', 'class', 'title', 'style', 'clear' ),
1181 # 9.3.4
1182 'pre' => array_merge( $common, array( 'width' ) ),
1184 # 9.4
1185 'ins' => array_merge( $common, array( 'cite', 'datetime' ) ),
1186 'del' => array_merge( $common, array( 'cite', 'datetime' ) ),
1188 # 10.2
1189 'ul' => array_merge( $common, array( 'type' ) ),
1190 'ol' => array_merge( $common, array( 'type', 'start' ) ),
1191 'li' => array_merge( $common, array( 'type', 'value' ) ),
1193 # 10.3
1194 'dl' => $common,
1195 'dd' => $common,
1196 'dt' => $common,
1198 # 11.2.1
1199 'table' => array_merge( $common,
1200 array( 'summary', 'width', 'border', 'frame',
1201 'rules', 'cellspacing', 'cellpadding',
1202 'align', 'bgcolor',
1203 ) ),
1205 # 11.2.2
1206 'caption' => array_merge( $common, array( 'align' ) ),
1208 # 11.2.3
1209 'thead' => array_merge( $common, $tablealign ),
1210 'tfoot' => array_merge( $common, $tablealign ),
1211 'tbody' => array_merge( $common, $tablealign ),
1213 # 11.2.4
1214 'colgroup' => array_merge( $common, array( 'span', 'width' ), $tablealign ),
1215 'col' => array_merge( $common, array( 'span', 'width' ), $tablealign ),
1217 # 11.2.5
1218 'tr' => array_merge( $common, array( 'bgcolor' ), $tablealign ),
1220 # 11.2.6
1221 'td' => array_merge( $common, $tablecell, $tablealign ),
1222 'th' => array_merge( $common, $tablecell, $tablealign ),
1224 # 13.2
1225 # Not usually allowed, but may be used for extension-style hooks
1226 # such as <math> when it is rasterized
1227 'img' => array_merge( $common, array( 'alt' ) ),
1229 # 15.2.1
1230 'tt' => $common,
1231 'b' => $common,
1232 'i' => $common,
1233 'big' => $common,
1234 'small' => $common,
1235 'strike' => $common,
1236 's' => $common,
1237 'u' => $common,
1239 # 15.2.2
1240 'font' => array_merge( $common, array( 'size', 'color', 'face' ) ),
1241 # basefont
1243 # 15.3
1244 'hr' => array_merge( $common, array( 'noshade', 'size', 'width' ) ),
1246 # XHTML Ruby annotation text module, simple ruby only.
1247 # http://www.w3c.org/TR/ruby/
1248 'ruby' => $common,
1249 # rbc
1250 # rtc
1251 'rb' => $common,
1252 'rt' => $common, #array_merge( $common, array( 'rbspan' ) ),
1253 'rp' => $common,
1255 # MathML root element, where used for extensions
1256 # 'title' may not be 100% valid here; it's XHTML
1257 # http://www.w3.org/TR/REC-MathML/
1258 'math' => array( 'class', 'style', 'id', 'title' ),
1260 return $whitelist;
1264 * Take a fragment of (potentially invalid) HTML and return
1265 * a version with any tags removed, encoded as plain text.
1267 * Warning: this return value must be further escaped for literal
1268 * inclusion in HTML output as of 1.10!
1270 * @param string $text HTML fragment
1271 * @return string
1273 static function stripAllTags( $text ) {
1274 # Actual <tags>
1275 $text = StringUtils::delimiterReplace( '<', '>', '', $text );
1277 # Normalize &entities and whitespace
1278 $text = self::decodeCharReferences( $text );
1279 $text = self::normalizeWhitespace( $text );
1281 return $text;
1285 * Hack up a private DOCTYPE with HTML's standard entity declarations.
1286 * PHP 4 seemed to know these if you gave it an HTML doctype, but
1287 * PHP 5.1 doesn't.
1289 * Use for passing XHTML fragments to PHP's XML parsing functions
1291 * @return string
1292 * @static
1294 static function hackDocType() {
1295 global $wgHtmlEntities;
1296 $out = "<!DOCTYPE html [\n";
1297 foreach( $wgHtmlEntities as $entity => $codepoint ) {
1298 $out .= "<!ENTITY $entity \"&#$codepoint;\">";
1300 $out .= "]>\n";
1301 return $out;
1304 static function cleanUrl( $url, $hostname=true ) {
1305 # Normalize any HTML entities in input. They will be
1306 # re-escaped by makeExternalLink().
1307 $url = Sanitizer::decodeCharReferences( $url );
1309 # Escape any control characters introduced by the above step
1310 $url = preg_replace( '/[\][<>"\\x00-\\x20\\x7F]/e', "urlencode('\\0')", $url );
1312 # Validate hostname portion
1313 $matches = array();
1314 if( preg_match( '!^([^:]+:)(//[^/]+)?(.*)$!iD', $url, $matches ) ) {
1315 list( /* $whole */, $protocol, $host, $rest ) = $matches;
1317 // Characters that will be ignored in IDNs.
1318 // http://tools.ietf.org/html/3454#section-3.1
1319 // Strip them before further processing so blacklists and such work.
1320 $strip = "/
1321 \\s| # general whitespace
1322 \xc2\xad| # 00ad SOFT HYPHEN
1323 \xe1\xa0\x86| # 1806 MONGOLIAN TODO SOFT HYPHEN
1324 \xe2\x80\x8b| # 200b ZERO WIDTH SPACE
1325 \xe2\x81\xa0| # 2060 WORD JOINER
1326 \xef\xbb\xbf| # feff ZERO WIDTH NO-BREAK SPACE
1327 \xcd\x8f| # 034f COMBINING GRAPHEME JOINER
1328 \xe1\xa0\x8b| # 180b MONGOLIAN FREE VARIATION SELECTOR ONE
1329 \xe1\xa0\x8c| # 180c MONGOLIAN FREE VARIATION SELECTOR TWO
1330 \xe1\xa0\x8d| # 180d MONGOLIAN FREE VARIATION SELECTOR THREE
1331 \xe2\x80\x8c| # 200c ZERO WIDTH NON-JOINER
1332 \xe2\x80\x8d| # 200d ZERO WIDTH JOINER
1333 [\xef\xb8\x80-\xef\xb8\x8f] # fe00-fe00f VARIATION SELECTOR-1-16
1334 /xuD";
1336 $host = preg_replace( $strip, '', $host );
1338 // @fixme: validate hostnames here
1340 return $protocol . $host . $rest;
1341 } else {
1342 return $url;