Code housekeeping stuff (and barring any stuff-ups on my behalf, there should be...
[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 * @package MediaWiki
24 * @subpackage Parser
25 */
26
27 /**
28 * Regular expression to match various types of character references in
29 * Sanitizer::normalizeCharReferences and Sanitizer::decodeCharReferences
30 */
31 define( 'MW_CHAR_REFS_REGEX',
32 '/&([A-Za-z0-9]+);
33 |&\#([0-9]+);
34 |&\#x([0-9A-Za-z]+);
35 |&\#X([0-9A-Za-z]+);
36 |(&)/x' );
37
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
42 */
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.
56 )
57 )?(?=$space|\$)/sx" );
58
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
63 */
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 );
318
319 /** @package MediaWiki */
320 class Sanitizer {
321 /**
322 * Cleans up HTML, removes dangerous tags and attributes, and
323 * removes HTML comments
324 * @private
325 * @param string $text
326 * @param callback $processCallback to do any variable or parameter replacements in HTML attribute values
327 * @param array $args for the processing callback
328 * @return string
329 */
330 static function removeHTMLtags( $text, $processCallback = null, $args = array() ) {
331 global $wgUseTidy, $wgUserHtml;
332
333 static $htmlpairs, $htmlsingle, $htmlsingleonly, $htmlnest, $tabletags,
334 $htmllist, $listtags, $htmlsingleallowed, $htmlelements, $staticInitialised;
335
336 wfProfileIn( __METHOD__ );
337
338 if ( !$staticInitialised ) {
339 if( $wgUserHtml ) {
340 $htmlpairs = array( # Tags that must be closed
341 'b', 'del', 'i', 'ins', 'u', 'font', 'big', 'small', 'sub', 'sup', 'h1',
342 'h2', 'h3', 'h4', 'h5', 'h6', 'cite', 'code', 'em', 's',
343 'strike', 'strong', 'tt', 'var', 'div', 'center',
344 'blockquote', 'ol', 'ul', 'dl', 'table', 'caption', 'pre',
345 'ruby', 'rt' , 'rb' , 'rp', 'p', 'span', 'u'
346 );
347 $htmlsingle = array(
348 'br', 'hr', 'li', 'dt', 'dd'
349 );
350 $htmlsingleonly = array( # Elements that cannot have close tags
351 'br', 'hr'
352 );
353 $htmlnest = array( # Tags that can be nested--??
354 'table', 'tr', 'td', 'th', 'div', 'blockquote', 'ol', 'ul',
355 'dl', 'font', 'big', 'small', 'sub', 'sup', 'span'
356 );
357 $tabletags = array( # Can only appear inside table
358 'td', 'th', 'tr',
359 );
360 $htmllist = array( # Tags used by list
361 'ul','ol',
362 );
363 $listtags = array( # Tags that can appear in a list
364 'li',
365 );
366
367 } else {
368 $htmlpairs = array();
369 $htmlsingle = array();
370 $htmlnest = array();
371 $tabletags = array();
372 }
373
374 $htmlsingleallowed = array_merge( $htmlsingle, $tabletags );
375 $htmlelements = array_merge( $htmlsingle, $htmlpairs, $htmlnest );
376
377 # Convert them all to hashtables for faster lookup
378 $vars = array( 'htmlpairs', 'htmlsingle', 'htmlsingleonly', 'htmlnest', 'tabletags',
379 'htmllist', 'listtags', 'htmlsingleallowed', 'htmlelements' );
380 foreach ( $vars as $var ) {
381 $$var = array_flip( $$var );
382 }
383 $staticInitialised = true;
384 }
385
386 # Remove HTML comments
387 $text = Sanitizer::removeHTMLcomments( $text );
388 $bits = explode( '<', $text );
389 $text = array_shift( $bits );
390 if(!$wgUseTidy) {
391 $tagstack = $tablestack = array();
392 foreach ( $bits as $x ) {
393 $prev = error_reporting( E_ALL & ~( E_NOTICE | E_WARNING ) );
394 $regs = array();
395 preg_match( '!^(/?)(\\w+)([^>]*?)(/{0,1}>)([^<]*)$!', $x, $regs );
396 list( /* $qbar */, $slash, $t, $params, $brace, $rest ) = $regs;
397 error_reporting( $prev );
398
399 $badtag = 0 ;
400 if ( isset( $htmlelements[$t = strtolower( $t )] ) ) {
401 # Check our stack
402 if ( $slash ) {
403 # Closing a tag...
404 if( isset( $htmlsingleonly[$t] ) ) {
405 $badtag = 1;
406 } elseif ( ( $ot = @array_pop( $tagstack ) ) != $t ) {
407 if ( isset( $htmlsingleallowed[$ot] ) ) {
408 # Pop all elements with an optional close tag
409 # and see if we find a match below them
410 $optstack = array();
411 array_push ($optstack, $ot);
412 while ( ( ( $ot = @array_pop( $tagstack ) ) != $t ) &&
413 isset( $htmlsingleallowed[$ot] ) )
414 {
415 array_push ($optstack, $ot);
416 }
417 if ( $t != $ot ) {
418 # No match. Push the optinal elements back again
419 $badtag = 1;
420 while ( $ot = @array_pop( $optstack ) ) {
421 array_push( $tagstack, $ot );
422 }
423 }
424 } else {
425 @array_push( $tagstack, $ot );
426 # <li> can be nested in <ul> or <ol>, skip those cases:
427 if(!(isset( $htmllist[$ot] ) && isset( $listtags[$t] ) )) {
428 $badtag = 1;
429 }
430 }
431 } else {
432 if ( $t == 'table' ) {
433 $tagstack = array_pop( $tablestack );
434 }
435 }
436 $newparams = '';
437 } else {
438 # Keep track for later
439 if ( isset( $tabletags[$t] ) &&
440 ! in_array( 'table', $tagstack ) ) {
441 $badtag = 1;
442 } else if ( in_array( $t, $tagstack ) &&
443 ! isset( $htmlnest [$t ] ) ) {
444 $badtag = 1 ;
445 # Is it a self closed htmlpair ? (bug 5487)
446 } else if( $brace == '/>' &&
447 isset( $htmlpairs[$t] ) ) {
448 $badtag = 1;
449 } elseif( isset( $htmlsingleonly[$t] ) ) {
450 # Hack to force empty tag for uncloseable elements
451 $brace = '/>';
452 } else if( isset( $htmlsingle[$t] ) ) {
453 # Hack to not close $htmlsingle tags
454 $brace = NULL;
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 == '/>' ) ? ' /' : '';
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 * @link http://www.w3.org/TR/html401/types.html#type-name Valid characters
719 * in the id and
720 * name attributes
721 * @link http://www.w3.org/TR/html401/struct/links.html#h-12.2.3 Anchors with the id attribute
722 *
723 * @bug 4461
724 *
725 * @static
726 *
727 * @param string $id
728 * @return string
729 */
730 static function escapeId( $id ) {
731 static $replace = array(
732 '%3A' => ':',
733 '%' => '.'
734 );
735
736 $id = urlencode( Sanitizer::decodeCharReferences( strtr( $id, ' ', '_' ) ) );
737
738 return str_replace( array_keys( $replace ), array_values( $replace ), $id );
739 }
740
741 /**
742 * Given a value, escape it so that it can be used as a CSS class and
743 * return it.
744 *
745 * TODO: For extra validity, input should be validated UTF-8.
746 *
747 * @link http://www.w3.org/TR/CSS21/syndata.html Valid characters/format
748 *
749 * @param string $class
750 * @return string
751 */
752 static function escapeClass( $class ) {
753 // Convert ugly stuff to underscores and kill underscores in ugly places
754 return rtrim(preg_replace(
755 array('/(^[0-9\\-])|[\\x00-\\x20!"#$%&\'()*+,.\\/:;<=>?@[\\]^`{|}~]|\\xC2\\xA0/','/_+/'),
756 '_',
757 $class ), '_');
758 }
759
760 /**
761 * Regex replace callback for armoring links against further processing.
762 * @param array $matches
763 * @return string
764 * @private
765 */
766 private static function armorLinksCallback( $matches ) {
767 return str_replace( ':', '&#58;', $matches[1] );
768 }
769
770 /**
771 * Return an associative array of attribute names and values from
772 * a partial tag string. Attribute names are forces to lowercase,
773 * character references are decoded to UTF-8 text.
774 *
775 * @param string
776 * @return array
777 */
778 static function decodeTagAttributes( $text ) {
779 $attribs = array();
780
781 if( trim( $text ) == '' ) {
782 return $attribs;
783 }
784
785 $pairs = array();
786 if( !preg_match_all(
787 MW_ATTRIBS_REGEX,
788 $text,
789 $pairs,
790 PREG_SET_ORDER ) ) {
791 return $attribs;
792 }
793
794 foreach( $pairs as $set ) {
795 $attribute = strtolower( $set[1] );
796 $value = Sanitizer::getTagAttributeCallback( $set );
797
798 // Normalize whitespace
799 $value = preg_replace( '/[\t\r\n ]+/', ' ', $value );
800 $value = trim( $value );
801
802 // Decode character references
803 $attribs[$attribute] = Sanitizer::decodeCharReferences( $value );
804 }
805 return $attribs;
806 }
807
808 /**
809 * Pick the appropriate attribute value from a match set from the
810 * MW_ATTRIBS_REGEX matches.
811 *
812 * @param array $set
813 * @return string
814 * @private
815 */
816 private static function getTagAttributeCallback( $set ) {
817 if( isset( $set[6] ) ) {
818 # Illegal #XXXXXX color with no quotes.
819 return $set[6];
820 } elseif( isset( $set[5] ) ) {
821 # No quotes.
822 return $set[5];
823 } elseif( isset( $set[4] ) ) {
824 # Single-quoted
825 return $set[4];
826 } elseif( isset( $set[3] ) ) {
827 # Double-quoted
828 return $set[3];
829 } elseif( !isset( $set[2] ) ) {
830 # In XHTML, attributes must have a value.
831 # For 'reduced' form, return explicitly the attribute name here.
832 return $set[1];
833 } else {
834 throw new MWException( "Tag conditions not met. This should never happen and is a bug." );
835 }
836 }
837
838 /**
839 * Normalize whitespace and character references in an XML source-
840 * encoded text for an attribute value.
841 *
842 * See http://www.w3.org/TR/REC-xml/#AVNormalize for background,
843 * but note that we're not returning the value, but are returning
844 * XML source fragments that will be slapped into output.
845 *
846 * @param string $text
847 * @return string
848 * @private
849 */
850 private static function normalizeAttributeValue( $text ) {
851 return str_replace( '"', '&quot;',
852 preg_replace(
853 '/\r\n|[\x20\x0d\x0a\x09]/',
854 ' ',
855 Sanitizer::normalizeCharReferences( $text ) ) );
856 }
857
858 /**
859 * Ensure that any entities and character references are legal
860 * for XML and XHTML specifically. Any stray bits will be
861 * &amp;-escaped to result in a valid text fragment.
862 *
863 * a. any named char refs must be known in XHTML
864 * b. any numeric char refs must be legal chars, not invalid or forbidden
865 * c. use &#x, not &#X
866 * d. fix or reject non-valid attributes
867 *
868 * @param string $text
869 * @return string
870 * @private
871 */
872 static function normalizeCharReferences( $text ) {
873 return preg_replace_callback(
874 MW_CHAR_REFS_REGEX,
875 array( 'Sanitizer', 'normalizeCharReferencesCallback' ),
876 $text );
877 }
878 /**
879 * @param string $matches
880 * @return string
881 */
882 static function normalizeCharReferencesCallback( $matches ) {
883 $ret = null;
884 if( $matches[1] != '' ) {
885 $ret = Sanitizer::normalizeEntity( $matches[1] );
886 } elseif( $matches[2] != '' ) {
887 $ret = Sanitizer::decCharReference( $matches[2] );
888 } elseif( $matches[3] != '' ) {
889 $ret = Sanitizer::hexCharReference( $matches[3] );
890 } elseif( $matches[4] != '' ) {
891 $ret = Sanitizer::hexCharReference( $matches[4] );
892 }
893 if( is_null( $ret ) ) {
894 return htmlspecialchars( $matches[0] );
895 } else {
896 return $ret;
897 }
898 }
899
900 /**
901 * If the named entity is defined in the HTML 4.0/XHTML 1.0 DTD,
902 * return the named entity reference as is. Otherwise, returns
903 * HTML-escaped text of pseudo-entity source (eg &amp;foo;)
904 *
905 * @param string $name
906 * @return string
907 * @static
908 */
909 static function normalizeEntity( $name ) {
910 global $wgHtmlEntities;
911 if( isset( $wgHtmlEntities[$name] ) ) {
912 return "&$name;";
913 } else {
914 return "&amp;$name;";
915 }
916 }
917
918 static function decCharReference( $codepoint ) {
919 $point = intval( $codepoint );
920 if( Sanitizer::validateCodepoint( $point ) ) {
921 return sprintf( '&#%d;', $point );
922 } else {
923 return null;
924 }
925 }
926
927 static function hexCharReference( $codepoint ) {
928 $point = hexdec( $codepoint );
929 if( Sanitizer::validateCodepoint( $point ) ) {
930 return sprintf( '&#x%x;', $point );
931 } else {
932 return null;
933 }
934 }
935
936 /**
937 * Returns true if a given Unicode codepoint is a valid character in XML.
938 * @param int $codepoint
939 * @return bool
940 */
941 private static function validateCodepoint( $codepoint ) {
942 return ($codepoint == 0x09)
943 || ($codepoint == 0x0a)
944 || ($codepoint == 0x0d)
945 || ($codepoint >= 0x20 && $codepoint <= 0xd7ff)
946 || ($codepoint >= 0xe000 && $codepoint <= 0xfffd)
947 || ($codepoint >= 0x10000 && $codepoint <= 0x10ffff);
948 }
949
950 /**
951 * Decode any character references, numeric or named entities,
952 * in the text and return a UTF-8 string.
953 *
954 * @param string $text
955 * @return string
956 * @public
957 * @static
958 */
959 public static function decodeCharReferences( $text ) {
960 return preg_replace_callback(
961 MW_CHAR_REFS_REGEX,
962 array( 'Sanitizer', 'decodeCharReferencesCallback' ),
963 $text );
964 }
965
966 /**
967 * @param string $matches
968 * @return string
969 */
970 static function decodeCharReferencesCallback( $matches ) {
971 if( $matches[1] != '' ) {
972 return Sanitizer::decodeEntity( $matches[1] );
973 } elseif( $matches[2] != '' ) {
974 return Sanitizer::decodeChar( intval( $matches[2] ) );
975 } elseif( $matches[3] != '' ) {
976 return Sanitizer::decodeChar( hexdec( $matches[3] ) );
977 } elseif( $matches[4] != '' ) {
978 return Sanitizer::decodeChar( hexdec( $matches[4] ) );
979 }
980 # Last case should be an ampersand by itself
981 return $matches[0];
982 }
983
984 /**
985 * Return UTF-8 string for a codepoint if that is a valid
986 * character reference, otherwise U+FFFD REPLACEMENT CHARACTER.
987 * @param int $codepoint
988 * @return string
989 * @private
990 */
991 static function decodeChar( $codepoint ) {
992 if( Sanitizer::validateCodepoint( $codepoint ) ) {
993 return codepointToUtf8( $codepoint );
994 } else {
995 return UTF8_REPLACEMENT;
996 }
997 }
998
999 /**
1000 * If the named entity is defined in the HTML 4.0/XHTML 1.0 DTD,
1001 * return the UTF-8 encoding of that character. Otherwise, returns
1002 * pseudo-entity source (eg &foo;)
1003 *
1004 * @param string $name
1005 * @return string
1006 */
1007 static function decodeEntity( $name ) {
1008 global $wgHtmlEntities;
1009 if( isset( $wgHtmlEntities[$name] ) ) {
1010 return codepointToUtf8( $wgHtmlEntities[$name] );
1011 } else {
1012 return "&$name;";
1013 }
1014 }
1015
1016 /**
1017 * Fetch the whitelist of acceptable attributes for a given
1018 * element name.
1019 *
1020 * @param string $element
1021 * @return array
1022 */
1023 static function attributeWhitelist( $element ) {
1024 static $list;
1025 if( !isset( $list ) ) {
1026 $list = Sanitizer::setupAttributeWhitelist();
1027 }
1028 return isset( $list[$element] )
1029 ? $list[$element]
1030 : array();
1031 }
1032
1033 /**
1034 * @todo Document it a bit
1035 * @return array
1036 */
1037 static function setupAttributeWhitelist() {
1038 $common = array( 'id', 'class', 'lang', 'dir', 'title', 'style' );
1039 $block = array_merge( $common, array( 'align' ) );
1040 $tablealign = array( 'align', 'char', 'charoff', 'valign' );
1041 $tablecell = array( 'abbr',
1042 'axis',
1043 'headers',
1044 'scope',
1045 'rowspan',
1046 'colspan',
1047 'nowrap', # deprecated
1048 'width', # deprecated
1049 'height', # deprecated
1050 'bgcolor' # deprecated
1051 );
1052
1053 # Numbers refer to sections in HTML 4.01 standard describing the element.
1054 # See: http://www.w3.org/TR/html4/
1055 $whitelist = array (
1056 # 7.5.4
1057 'div' => $block,
1058 'center' => $common, # deprecated
1059 'span' => $block, # ??
1060
1061 # 7.5.5
1062 'h1' => $block,
1063 'h2' => $block,
1064 'h3' => $block,
1065 'h4' => $block,
1066 'h5' => $block,
1067 'h6' => $block,
1068
1069 # 7.5.6
1070 # address
1071
1072 # 8.2.4
1073 # bdo
1074
1075 # 9.2.1
1076 'em' => $common,
1077 'strong' => $common,
1078 'cite' => $common,
1079 # dfn
1080 'code' => $common,
1081 # samp
1082 # kbd
1083 'var' => $common,
1084 # abbr
1085 # acronym
1086
1087 # 9.2.2
1088 'blockquote' => array_merge( $common, array( 'cite' ) ),
1089 # q
1090
1091 # 9.2.3
1092 'sub' => $common,
1093 'sup' => $common,
1094
1095 # 9.3.1
1096 'p' => $block,
1097
1098 # 9.3.2
1099 'br' => array( 'id', 'class', 'title', 'style', 'clear' ),
1100
1101 # 9.3.4
1102 'pre' => array_merge( $common, array( 'width' ) ),
1103
1104 # 9.4
1105 'ins' => array_merge( $common, array( 'cite', 'datetime' ) ),
1106 'del' => array_merge( $common, array( 'cite', 'datetime' ) ),
1107
1108 # 10.2
1109 'ul' => array_merge( $common, array( 'type' ) ),
1110 'ol' => array_merge( $common, array( 'type', 'start' ) ),
1111 'li' => array_merge( $common, array( 'type', 'value' ) ),
1112
1113 # 10.3
1114 'dl' => $common,
1115 'dd' => $common,
1116 'dt' => $common,
1117
1118 # 11.2.1
1119 'table' => array_merge( $common,
1120 array( 'summary', 'width', 'border', 'frame',
1121 'rules', 'cellspacing', 'cellpadding',
1122 'align', 'bgcolor',
1123 ) ),
1124
1125 # 11.2.2
1126 'caption' => array_merge( $common, array( 'align' ) ),
1127
1128 # 11.2.3
1129 'thead' => array_merge( $common, $tablealign ),
1130 'tfoot' => array_merge( $common, $tablealign ),
1131 'tbody' => array_merge( $common, $tablealign ),
1132
1133 # 11.2.4
1134 'colgroup' => array_merge( $common, array( 'span', 'width' ), $tablealign ),
1135 'col' => array_merge( $common, array( 'span', 'width' ), $tablealign ),
1136
1137 # 11.2.5
1138 'tr' => array_merge( $common, array( 'bgcolor' ), $tablealign ),
1139
1140 # 11.2.6
1141 'td' => array_merge( $common, $tablecell, $tablealign ),
1142 'th' => array_merge( $common, $tablecell, $tablealign ),
1143
1144 # 15.2.1
1145 'tt' => $common,
1146 'b' => $common,
1147 'i' => $common,
1148 'big' => $common,
1149 'small' => $common,
1150 'strike' => $common,
1151 's' => $common,
1152 'u' => $common,
1153
1154 # 15.2.2
1155 'font' => array_merge( $common, array( 'size', 'color', 'face' ) ),
1156 # basefont
1157
1158 # 15.3
1159 'hr' => array_merge( $common, array( 'noshade', 'size', 'width' ) ),
1160
1161 # XHTML Ruby annotation text module, simple ruby only.
1162 # http://www.w3c.org/TR/ruby/
1163 'ruby' => $common,
1164 # rbc
1165 # rtc
1166 'rb' => $common,
1167 'rt' => $common, #array_merge( $common, array( 'rbspan' ) ),
1168 'rp' => $common,
1169 );
1170 return $whitelist;
1171 }
1172
1173 /**
1174 * Take a fragment of (potentially invalid) HTML and return
1175 * a version with any tags removed, encoded suitably for literal
1176 * inclusion in an attribute value.
1177 *
1178 * @param string $text HTML fragment
1179 * @return string
1180 */
1181 static function stripAllTags( $text ) {
1182 # Actual <tags>
1183 $text = StringUtils::delimiterReplace( '<', '>', '', $text );
1184
1185 # Normalize &entities and whitespace
1186 $text = Sanitizer::normalizeAttributeValue( $text );
1187
1188 # Will be placed into "double-quoted" attributes,
1189 # make sure remaining bits are safe.
1190 $text = str_replace(
1191 array('<', '>', '"'),
1192 array('&lt;', '&gt;', '&quot;'),
1193 $text );
1194
1195 return $text;
1196 }
1197
1198 /**
1199 * Hack up a private DOCTYPE with HTML's standard entity declarations.
1200 * PHP 4 seemed to know these if you gave it an HTML doctype, but
1201 * PHP 5.1 doesn't.
1202 *
1203 * Use for passing XHTML fragments to PHP's XML parsing functions
1204 *
1205 * @return string
1206 * @static
1207 */
1208 static function hackDocType() {
1209 global $wgHtmlEntities;
1210 $out = "<!DOCTYPE html [\n";
1211 foreach( $wgHtmlEntities as $entity => $codepoint ) {
1212 $out .= "<!ENTITY $entity \"&#$codepoint;\">";
1213 }
1214 $out .= "]>\n";
1215 return $out;
1216 }
1217
1218 static function cleanUrl( $url, $hostname=true ) {
1219 # Normalize any HTML entities in input. They will be
1220 # re-escaped by makeExternalLink().
1221 $url = Sanitizer::decodeCharReferences( $url );
1222
1223 # Escape any control characters introduced by the above step
1224 $url = preg_replace( '/[\][<>"\\x00-\\x20\\x7F]/e', "urlencode('\\0')", $url );
1225
1226 # Validate hostname portion
1227 $matches = array();
1228 if( preg_match( '!^([^:]+:)(//[^/]+)?(.*)$!iD', $url, $matches ) ) {
1229 list( /* $whole */, $protocol, $host, $rest ) = $matches;
1230
1231 // Characters that will be ignored in IDNs.
1232 // http://tools.ietf.org/html/3454#section-3.1
1233 // Strip them before further processing so blacklists and such work.
1234 $strip = "/
1235 \\s| # general whitespace
1236 \xc2\xad| # 00ad SOFT HYPHEN
1237 \xe1\xa0\x86| # 1806 MONGOLIAN TODO SOFT HYPHEN
1238 \xe2\x80\x8b| # 200b ZERO WIDTH SPACE
1239 \xe2\x81\xa0| # 2060 WORD JOINER
1240 \xef\xbb\xbf| # feff ZERO WIDTH NO-BREAK SPACE
1241 \xcd\x8f| # 034f COMBINING GRAPHEME JOINER
1242 \xe1\xa0\x8b| # 180b MONGOLIAN FREE VARIATION SELECTOR ONE
1243 \xe1\xa0\x8c| # 180c MONGOLIAN FREE VARIATION SELECTOR TWO
1244 \xe1\xa0\x8d| # 180d MONGOLIAN FREE VARIATION SELECTOR THREE
1245 \xe2\x80\x8c| # 200c ZERO WIDTH NON-JOINER
1246 \xe2\x80\x8d| # 200d ZERO WIDTH JOINER
1247 [\xef\xb8\x80-\xef\xb8\x8f] # fe00-fe00f VARIATION SELECTOR-1-16
1248 /xuD";
1249
1250 $host = preg_replace( $strip, '', $host );
1251
1252 // @fixme: validate hostnames here
1253
1254 return $protocol . $host . $rest;
1255 } else {
1256 return $url;
1257 }
1258 }
1259
1260 }
1261
1262 ?>