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