Follow-up on r49330
[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 * @file
24 * @ingroup 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\x80-\xff]+);
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 /**
320 * Character entity aliases accepted by MediaWiki
321 */
322 global $wgHtmlEntityAliases;
323 $wgHtmlEntityAliases = array(
324 'רלמ' => 'rlm',
325 'رلم' => 'rlm',
326 );
327
328
329 /**
330 * XHTML sanitizer for MediaWiki
331 * @ingroup Parser
332 */
333 class Sanitizer {
334 /**
335 * Cleans up HTML, removes dangerous tags and attributes, and
336 * removes HTML comments
337 * @private
338 * @param string $text
339 * @param callback $processCallback to do any variable or parameter replacements in HTML attribute values
340 * @param array $args for the processing callback
341 * @param array $extratags for any extra tags to include
342 * @param array $removetags for any tags (default or extra) to exclude
343 * @return string
344 */
345 static function removeHTMLtags( $text, $processCallback = null, $args = array(), $extratags = array(), $removetags = array() ) {
346 global $wgUseTidy;
347
348 static $htmlpairs, $htmlsingle, $htmlsingleonly, $htmlnest, $tabletags,
349 $htmllist, $listtags, $htmlsingleallowed, $htmlelements, $staticInitialised;
350
351 wfProfileIn( __METHOD__ );
352
353 if ( !$staticInitialised ) {
354
355 $htmlpairs = array_merge( $extratags, array( # Tags that must be closed
356 'b', 'del', 'i', 'ins', 'u', 'font', 'big', 'small', 'sub', 'sup', 'h1',
357 'h2', 'h3', 'h4', 'h5', 'h6', 'cite', 'code', 'em', 's',
358 'strike', 'strong', 'tt', 'var', 'div', 'center',
359 'blockquote', 'ol', 'ul', 'dl', 'table', 'caption', 'pre',
360 'ruby', 'rt' , 'rb' , 'rp', 'p', 'span', 'u'
361 ) );
362 $htmlsingle = array(
363 'br', 'hr', 'li', 'dt', 'dd'
364 );
365 $htmlsingleonly = array( # Elements that cannot have close tags
366 'br', 'hr'
367 );
368 $htmlnest = array( # Tags that can be nested--??
369 'table', 'tr', 'td', 'th', 'div', 'blockquote', 'ol', 'ul',
370 'dl', 'font', 'big', 'small', 'sub', 'sup', 'span'
371 );
372 $tabletags = array( # Can only appear inside table, we will close them
373 'td', 'th', 'tr',
374 );
375 $htmllist = array( # Tags used by list
376 'ul','ol',
377 );
378 $listtags = array( # Tags that can appear in a list
379 'li',
380 );
381
382 $htmlsingleallowed = array_unique( array_merge( $htmlsingle, $tabletags ) );
383 # Only allow elements that aren't specified in $removetags
384 # Doing it here since this is the top-level check
385 $htmlelements = array_diff( array_unique( array_merge( $htmlsingle, $htmlpairs, $htmlnest ) ), $removetags );
386
387 # Convert them all to hashtables for faster lookup
388 $vars = array( 'htmlpairs', 'htmlsingle', 'htmlsingleonly', 'htmlnest', 'tabletags',
389 'htmllist', 'listtags', 'htmlsingleallowed', 'htmlelements' );
390 foreach ( $vars as $var ) {
391 $$var = array_flip( $$var );
392 }
393 $staticInitialised = true;
394 }
395
396 # Remove HTML comments
397 $text = Sanitizer::removeHTMLcomments( $text );
398 $bits = explode( '<', $text );
399 $text = str_replace( '>', '&gt;', array_shift( $bits ) );
400 if(!$wgUseTidy) {
401 $tagstack = $tablestack = array();
402 foreach ( $bits as $x ) {
403 $regs = array();
404 if( preg_match( '!^(/?)(\\w+)([^>]*?)(/{0,1}>)([^<]*)$!', $x, $regs ) ) {
405 list( /* $qbar */, $slash, $t, $params, $brace, $rest ) = $regs;
406 } else {
407 $slash = $t = $params = $brace = $rest = null;
408 }
409
410 $badtag = 0 ;
411 if ( isset( $htmlelements[$t = strtolower( $t )] ) ) {
412 # Check our stack
413 if ( $slash ) {
414 # Closing a tag...
415 if( isset( $htmlsingleonly[$t] ) ) {
416 $badtag = 1;
417 } elseif ( ( $ot = @array_pop( $tagstack ) ) != $t ) {
418 if ( isset( $htmlsingleallowed[$ot] ) ) {
419 # Pop all elements with an optional close tag
420 # and see if we find a match below them
421 $optstack = array();
422 array_push ($optstack, $ot);
423 while ( ( ( $ot = @array_pop( $tagstack ) ) != $t ) &&
424 isset( $htmlsingleallowed[$ot] ) )
425 {
426 array_push ($optstack, $ot);
427 }
428 if ( $t != $ot ) {
429 # No match. Push the optinal elements back again
430 $badtag = 1;
431 while ( $ot = @array_pop( $optstack ) ) {
432 array_push( $tagstack, $ot );
433 }
434 }
435 } else {
436 @array_push( $tagstack, $ot );
437 # <li> can be nested in <ul> or <ol>, skip those cases:
438 if(!(isset( $htmllist[$ot] ) && isset( $listtags[$t] ) )) {
439 $badtag = 1;
440 }
441 }
442 } else {
443 if ( $t == 'table' ) {
444 $tagstack = array_pop( $tablestack );
445 }
446 }
447 $newparams = '';
448 } else {
449 # Keep track for later
450 if ( isset( $tabletags[$t] ) &&
451 ! in_array( 'table', $tagstack ) ) {
452 $badtag = 1;
453 } else if ( in_array( $t, $tagstack ) &&
454 ! isset( $htmlnest [$t ] ) ) {
455 $badtag = 1 ;
456 # Is it a self closed htmlpair ? (bug 5487)
457 } else if( $brace == '/>' &&
458 isset( $htmlpairs[$t] ) ) {
459 $badtag = 1;
460 } elseif( isset( $htmlsingleonly[$t] ) ) {
461 # Hack to force empty tag for uncloseable elements
462 $brace = '/>';
463 } else if( isset( $htmlsingle[$t] ) ) {
464 # Hack to not close $htmlsingle tags
465 $brace = NULL;
466 } else if( isset( $tabletags[$t] )
467 && in_array($t ,$tagstack) ) {
468 // New table tag but forgot to close the previous one
469 $text .= "</$t>";
470 } else {
471 if ( $t == 'table' ) {
472 array_push( $tablestack, $tagstack );
473 $tagstack = array();
474 }
475 array_push( $tagstack, $t );
476 }
477
478 # Replace any variables or template parameters with
479 # plaintext results.
480 if( is_callable( $processCallback ) ) {
481 call_user_func_array( $processCallback, array( &$params, $args ) );
482 }
483
484 # Strip non-approved attributes from the tag
485 $newparams = Sanitizer::fixTagAttributes( $params, $t );
486 }
487 if ( ! $badtag ) {
488 $rest = str_replace( '>', '&gt;', $rest );
489 $close = ( $brace == '/>' && !$slash ) ? ' /' : '';
490 $text .= "<$slash$t$newparams$close>$rest";
491 continue;
492 }
493 }
494 $text .= '&lt;' . str_replace( '>', '&gt;', $x);
495 }
496 # Close off any remaining tags
497 while ( is_array( $tagstack ) && ($t = array_pop( $tagstack )) ) {
498 $text .= "</$t>\n";
499 if ( $t == 'table' ) { $tagstack = array_pop( $tablestack ); }
500 }
501 } else {
502 # this might be possible using tidy itself
503 foreach ( $bits as $x ) {
504 preg_match( '/^(\\/?)(\\w+)([^>]*?)(\\/{0,1}>)([^<]*)$/',
505 $x, $regs );
506 @list( /* $qbar */, $slash, $t, $params, $brace, $rest ) = $regs;
507 if ( isset( $htmlelements[$t = strtolower( $t )] ) ) {
508 if( is_callable( $processCallback ) ) {
509 call_user_func_array( $processCallback, array( &$params, $args ) );
510 }
511 $newparams = Sanitizer::fixTagAttributes( $params, $t );
512 $rest = str_replace( '>', '&gt;', $rest );
513 $text .= "<$slash$t$newparams$brace$rest";
514 } else {
515 $text .= '&lt;' . str_replace( '>', '&gt;', $x);
516 }
517 }
518 }
519 wfProfileOut( __METHOD__ );
520 return $text;
521 }
522
523 /**
524 * Remove '<!--', '-->', and everything between.
525 * To avoid leaving blank lines, when a comment is both preceded
526 * and followed by a newline (ignoring spaces), trim leading and
527 * trailing spaces and one of the newlines.
528 *
529 * @private
530 * @param string $text
531 * @return string
532 */
533 static function removeHTMLcomments( $text ) {
534 wfProfileIn( __METHOD__ );
535 while (($start = strpos($text, '<!--')) !== false) {
536 $end = strpos($text, '-->', $start + 4);
537 if ($end === false) {
538 # Unterminated comment; bail out
539 break;
540 }
541
542 $end += 3;
543
544 # Trim space and newline if the comment is both
545 # preceded and followed by a newline
546 $spaceStart = max($start - 1, 0);
547 $spaceLen = $end - $spaceStart;
548 while (substr($text, $spaceStart, 1) === ' ' && $spaceStart > 0) {
549 $spaceStart--;
550 $spaceLen++;
551 }
552 while (substr($text, $spaceStart + $spaceLen, 1) === ' ')
553 $spaceLen++;
554 if (substr($text, $spaceStart, 1) === "\n" and substr($text, $spaceStart + $spaceLen, 1) === "\n") {
555 # Remove the comment, leading and trailing
556 # spaces, and leave only one newline.
557 $text = substr_replace($text, "\n", $spaceStart, $spaceLen + 1);
558 }
559 else {
560 # Remove just the comment.
561 $text = substr_replace($text, '', $start, $end - $start);
562 }
563 }
564 wfProfileOut( __METHOD__ );
565 return $text;
566 }
567
568 /**
569 * Take an array of attribute names and values and normalize or discard
570 * illegal values for the given element type.
571 *
572 * - Discards attributes not on a whitelist for the given element
573 * - Unsafe style attributes are discarded
574 * - Invalid id attributes are reencoded
575 *
576 * @param array $attribs
577 * @param string $element
578 * @return array
579 *
580 * @todo Check for legal values where the DTD limits things.
581 * @todo Check for unique id attribute :P
582 */
583 static function validateTagAttributes( $attribs, $element ) {
584 return Sanitizer::validateAttributes( $attribs,
585 Sanitizer::attributeWhitelist( $element ) );
586 }
587
588 /**
589 * Take an array of attribute names and values and normalize or discard
590 * illegal values for the given whitelist.
591 *
592 * - Discards attributes not the given whitelist
593 * - Unsafe style attributes are discarded
594 * - Invalid id attributes are reencoded
595 *
596 * @param array $attribs
597 * @param array $whitelist list of allowed attribute names
598 * @return array
599 *
600 * @todo Check for legal values where the DTD limits things.
601 * @todo Check for unique id attribute :P
602 */
603 static function validateAttributes( $attribs, $whitelist ) {
604 $whitelist = array_flip( $whitelist );
605 $out = array();
606 foreach( $attribs as $attribute => $value ) {
607 if( !isset( $whitelist[$attribute] ) ) {
608 continue;
609 }
610 # Strip javascript "expression" from stylesheets.
611 # http://msdn.microsoft.com/workshop/author/dhtml/overview/recalc.asp
612 if( $attribute == 'style' ) {
613 $value = Sanitizer::checkCss( $value );
614 if( $value === false ) {
615 # haxx0r
616 continue;
617 }
618 }
619
620 if ( $attribute === 'id' ) {
621 global $wgEnforceHtmlIds;
622 $value = Sanitizer::escapeId( $value,
623 $wgEnforceHtmlIds ? 'noninitial' : 'xml' );
624 }
625
626 // If this attribute was previously set, override it.
627 // Output should only have one attribute of each name.
628 $out[$attribute] = $value;
629 }
630 return $out;
631 }
632
633 /**
634 * Merge two sets of HTML attributes. Conflicting items in the second set
635 * will override those in the first, except for 'class' attributes which
636 * will be combined (if they're both strings).
637 *
638 * @todo implement merging for other attributes such as style
639 * @param array $a
640 * @param array $b
641 * @return array
642 */
643 static function mergeAttributes( $a, $b ) {
644 $out = array_merge( $a, $b );
645 if( isset( $a['class'] ) && isset( $b['class'] )
646 && is_string( $a['class'] ) && is_string( $b['class'] )
647 && $a['class'] !== $b['class'] ) {
648 $classes = preg_split( '/\s+/', "{$a['class']} {$b['class']}",
649 -1, PREG_SPLIT_NO_EMPTY );
650 $out['class'] = implode( ' ', array_unique( $classes ) );
651 }
652 return $out;
653 }
654
655 /**
656 * Pick apart some CSS and check it for forbidden or unsafe structures.
657 * Returns a sanitized string, or false if it was just too evil.
658 *
659 * Currently URL references, 'expression', 'tps' are forbidden.
660 *
661 * @param string $value
662 * @return mixed
663 */
664 static function checkCss( $value ) {
665 $stripped = Sanitizer::decodeCharReferences( $value );
666
667 // Remove any comments; IE gets token splitting wrong
668 $stripped = StringUtils::delimiterReplace( '/*', '*/', ' ', $stripped );
669
670 $value = $stripped;
671
672 // ... and continue checks
673 $stripped = preg_replace( '!\\\\([0-9A-Fa-f]{1,6})[ \\n\\r\\t\\f]?!e',
674 'codepointToUtf8(hexdec("$1"))', $stripped );
675 $stripped = str_replace( '\\', '', $stripped );
676 if( preg_match( '/(?:expression|tps*:\/\/|url\\s*\().*/is',
677 $stripped ) ) {
678 # haxx0r
679 return false;
680 }
681
682 return $value;
683 }
684
685 /**
686 * Take a tag soup fragment listing an HTML element's attributes
687 * and normalize it to well-formed XML, discarding unwanted attributes.
688 * Output is safe for further wikitext processing, with escaping of
689 * values that could trigger problems.
690 *
691 * - Normalizes attribute names to lowercase
692 * - Discards attributes not on a whitelist for the given element
693 * - Turns broken or invalid entities into plaintext
694 * - Double-quotes all attribute values
695 * - Attributes without values are given the name as attribute
696 * - Double attributes are discarded
697 * - Unsafe style attributes are discarded
698 * - Prepends space if there are attributes.
699 *
700 * @param string $text
701 * @param string $element
702 * @return string
703 */
704 static function fixTagAttributes( $text, $element ) {
705 if( trim( $text ) == '' ) {
706 return '';
707 }
708
709 $stripped = Sanitizer::validateTagAttributes(
710 Sanitizer::decodeTagAttributes( $text ), $element );
711
712 $attribs = array();
713 foreach( $stripped as $attribute => $value ) {
714 $encAttribute = htmlspecialchars( $attribute );
715 $encValue = Sanitizer::safeEncodeAttribute( $value );
716
717 $attribs[] = "$encAttribute=\"$encValue\"";
718 }
719 return count( $attribs ) ? ' ' . implode( ' ', $attribs ) : '';
720 }
721
722 /**
723 * Encode an attribute value for HTML output.
724 * @param $text
725 * @return HTML-encoded text fragment
726 */
727 static function encodeAttribute( $text ) {
728 $encValue = htmlspecialchars( $text, ENT_QUOTES );
729
730 // Whitespace is normalized during attribute decoding,
731 // so if we've been passed non-spaces we must encode them
732 // ahead of time or they won't be preserved.
733 $encValue = strtr( $encValue, array(
734 "\n" => '&#10;',
735 "\r" => '&#13;',
736 "\t" => '&#9;',
737 ) );
738
739 return $encValue;
740 }
741
742 /**
743 * Encode an attribute value for HTML tags, with extra armoring
744 * against further wiki processing.
745 * @param $text
746 * @return HTML-encoded text fragment
747 */
748 static function safeEncodeAttribute( $text ) {
749 $encValue = Sanitizer::encodeAttribute( $text );
750
751 # Templates and links may be expanded in later parsing,
752 # creating invalid or dangerous output. Suppress this.
753 $encValue = strtr( $encValue, array(
754 '<' => '&lt;', // This should never happen,
755 '>' => '&gt;', // we've received invalid input
756 '"' => '&quot;', // which should have been escaped.
757 '{' => '&#123;',
758 '[' => '&#91;',
759 "''" => '&#39;&#39;',
760 'ISBN' => '&#73;SBN',
761 'RFC' => '&#82;FC',
762 'PMID' => '&#80;MID',
763 '|' => '&#124;',
764 '__' => '&#95;_',
765 ) );
766
767 # Stupid hack
768 $encValue = preg_replace_callback(
769 '/(' . wfUrlProtocols() . ')/',
770 array( 'Sanitizer', 'armorLinksCallback' ),
771 $encValue );
772 return $encValue;
773 }
774
775 /**
776 * Given a value escape it so that it can be used in an id attribute and
777 * return it, this does not validate the value however (see first link)
778 *
779 * @see http://www.w3.org/TR/html401/types.html#type-name Valid characters
780 * in the id and
781 * name attributes
782 * @see http://www.w3.org/TR/html401/struct/links.html#h-12.2.3 Anchors with the id attribute
783 *
784 * @param string $id Id to validate
785 * @param mixed $options String or array of strings (default is array()):
786 * 'noninitial': This is a non-initial fragment of an id, not a full id,
787 * so don't pay attention if the first character isn't valid at the
788 * beginning of an id.
789 * 'xml': Don't restrict the id to be HTML4-compatible. This option
790 * allows any alphabetic character to be used, per the XML standard.
791 * Therefore, it also completely changes the type of escaping: instead
792 * of weird dot-encoding, runs of invalid characters (mostly
793 * whitespace) are just compressed into a single underscore.
794 * @return string
795 */
796 static function escapeId( $id, $options = array() ) {
797 $options = (array)$options;
798
799 if ( !in_array( 'xml', $options ) ) {
800 # HTML4-style escaping
801 static $replace = array(
802 '%3A' => ':',
803 '%' => '.'
804 );
805
806 $id = urlencode( Sanitizer::decodeCharReferences( strtr( $id, ' ', '_' ) ) );
807 $id = str_replace( array_keys( $replace ), array_values( $replace ), $id );
808
809 if ( !preg_match( '/^[a-zA-Z]/', $id )
810 && !in_array( 'noninitial', $options ) ) {
811 // Initial character must be a letter!
812 $id = "x$id";
813 }
814 return $id;
815 }
816
817 # XML-style escaping. For the patterns used, see the XML 1.0 standard,
818 # 5th edition, NameStartChar and NameChar: <http://www.w3.org/TR/REC-xml/>
819 $nameStartChar = ':a-zA-Z_\xC0-\xD6\xD8-\xF6\xF8-\x{2FF}\x{370}-\x{37D}'
820 . '\x{37F}-\x{1FFF}\x{200C}-\x{200D}\x{2070}-\x{218F}\x{2C00}-\x{2FEF}'
821 . '\x{3001}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFFD}\x{10000}-\x{EFFFF}';
822 $nameChar = $nameStartChar . '.\-0-9\xB7\x{0300}-\x{036F}'
823 . '\x{203F}-\x{2040}';
824 # Replace _ as well so we don't get multiple consecutive underscores
825 $id = preg_replace( "/([^$nameChar]|_)+/u", '_', $id );
826 $id = trim( $id, '_' );
827
828 if ( !preg_match( "/^[$nameStartChar]/u", $id )
829 && !in_array( 'noninitial', $options ) ) {
830 $id = "_$id";
831 }
832
833 return $id;
834 }
835
836 /**
837 * Given a value, escape it so that it can be used as a CSS class and
838 * return it.
839 *
840 * @todo For extra validity, input should be validated UTF-8.
841 *
842 * @see http://www.w3.org/TR/CSS21/syndata.html Valid characters/format
843 *
844 * @param string $class
845 * @return string
846 */
847 static function escapeClass( $class ) {
848 // Convert ugly stuff to underscores and kill underscores in ugly places
849 return rtrim(preg_replace(
850 array('/(^[0-9\\-])|[\\x00-\\x20!"#$%&\'()*+,.\\/:;<=>?@[\\]^`{|}~]|\\xC2\\xA0/','/_+/'),
851 '_',
852 $class ), '_');
853 }
854
855 /**
856 * Given HTML input, escape with htmlspecialchars but un-escape entites.
857 * This allows (generally harmless) entities like &nbsp; to survive.
858 *
859 * @param string $html String to escape
860 * @return string Escaped input
861 */
862 static function escapeHtmlAllowEntities( $html ) {
863 # It seems wise to escape ' as well as ", as a matter of course. Can't
864 # hurt.
865 $html = htmlspecialchars( $html, ENT_QUOTES );
866 $html = str_replace( '&amp;', '&', $html );
867 $html = Sanitizer::normalizeCharReferences( $html );
868 return $html;
869 }
870
871 /**
872 * Regex replace callback for armoring links against further processing.
873 * @param array $matches
874 * @return string
875 * @private
876 */
877 private static function armorLinksCallback( $matches ) {
878 return str_replace( ':', '&#58;', $matches[1] );
879 }
880
881 /**
882 * Return an associative array of attribute names and values from
883 * a partial tag string. Attribute names are forces to lowercase,
884 * character references are decoded to UTF-8 text.
885 *
886 * @param string
887 * @return array
888 */
889 public static function decodeTagAttributes( $text ) {
890 $attribs = array();
891
892 if( trim( $text ) == '' ) {
893 return $attribs;
894 }
895
896 $pairs = array();
897 if( !preg_match_all(
898 MW_ATTRIBS_REGEX,
899 $text,
900 $pairs,
901 PREG_SET_ORDER ) ) {
902 return $attribs;
903 }
904
905 foreach( $pairs as $set ) {
906 $attribute = strtolower( $set[1] );
907 $value = Sanitizer::getTagAttributeCallback( $set );
908
909 // Normalize whitespace
910 $value = preg_replace( '/[\t\r\n ]+/', ' ', $value );
911 $value = trim( $value );
912
913 // Decode character references
914 $attribs[$attribute] = Sanitizer::decodeCharReferences( $value );
915 }
916 return $attribs;
917 }
918
919 /**
920 * Pick the appropriate attribute value from a match set from the
921 * MW_ATTRIBS_REGEX matches.
922 *
923 * @param array $set
924 * @return string
925 * @private
926 */
927 private static function getTagAttributeCallback( $set ) {
928 if( isset( $set[6] ) ) {
929 # Illegal #XXXXXX color with no quotes.
930 return $set[6];
931 } elseif( isset( $set[5] ) ) {
932 # No quotes.
933 return $set[5];
934 } elseif( isset( $set[4] ) ) {
935 # Single-quoted
936 return $set[4];
937 } elseif( isset( $set[3] ) ) {
938 # Double-quoted
939 return $set[3];
940 } elseif( !isset( $set[2] ) ) {
941 # In XHTML, attributes must have a value.
942 # For 'reduced' form, return explicitly the attribute name here.
943 return $set[1];
944 } else {
945 throw new MWException( "Tag conditions not met. This should never happen and is a bug." );
946 }
947 }
948
949 /**
950 * Normalize whitespace and character references in an XML source-
951 * encoded text for an attribute value.
952 *
953 * See http://www.w3.org/TR/REC-xml/#AVNormalize for background,
954 * but note that we're not returning the value, but are returning
955 * XML source fragments that will be slapped into output.
956 *
957 * @param string $text
958 * @return string
959 * @private
960 */
961 private static function normalizeAttributeValue( $text ) {
962 return str_replace( '"', '&quot;',
963 self::normalizeWhitespace(
964 Sanitizer::normalizeCharReferences( $text ) ) );
965 }
966
967 private static function normalizeWhitespace( $text ) {
968 return preg_replace(
969 '/\r\n|[\x20\x0d\x0a\x09]/',
970 ' ',
971 $text );
972 }
973
974 /**
975 * Ensure that any entities and character references are legal
976 * for XML and XHTML specifically. Any stray bits will be
977 * &amp;-escaped to result in a valid text fragment.
978 *
979 * a. any named char refs must be known in XHTML
980 * b. any numeric char refs must be legal chars, not invalid or forbidden
981 * c. use &#x, not &#X
982 * d. fix or reject non-valid attributes
983 *
984 * @param string $text
985 * @return string
986 * @private
987 */
988 static function normalizeCharReferences( $text ) {
989 return preg_replace_callback(
990 MW_CHAR_REFS_REGEX,
991 array( 'Sanitizer', 'normalizeCharReferencesCallback' ),
992 $text );
993 }
994 /**
995 * @param string $matches
996 * @return string
997 */
998 static function normalizeCharReferencesCallback( $matches ) {
999 $ret = null;
1000 if( $matches[1] != '' ) {
1001 $ret = Sanitizer::normalizeEntity( $matches[1] );
1002 } elseif( $matches[2] != '' ) {
1003 $ret = Sanitizer::decCharReference( $matches[2] );
1004 } elseif( $matches[3] != '' ) {
1005 $ret = Sanitizer::hexCharReference( $matches[3] );
1006 } elseif( $matches[4] != '' ) {
1007 $ret = Sanitizer::hexCharReference( $matches[4] );
1008 }
1009 if( is_null( $ret ) ) {
1010 return htmlspecialchars( $matches[0] );
1011 } else {
1012 return $ret;
1013 }
1014 }
1015
1016 /**
1017 * If the named entity is defined in the HTML 4.0/XHTML 1.0 DTD,
1018 * return the named entity reference as is. If the entity is a
1019 * MediaWiki-specific alias, returns the HTML equivalent. Otherwise,
1020 * returns HTML-escaped text of pseudo-entity source (eg &amp;foo;)
1021 *
1022 * @param string $name
1023 * @return string
1024 * @static
1025 */
1026 static function normalizeEntity( $name ) {
1027 global $wgHtmlEntities, $wgHtmlEntityAliases;
1028 if ( isset( $wgHtmlEntityAliases[$name] ) ) {
1029 return "&{$wgHtmlEntityAliases[$name]};";
1030 } elseif( isset( $wgHtmlEntities[$name] ) ) {
1031 return "&$name;";
1032 } else {
1033 return "&amp;$name;";
1034 }
1035 }
1036
1037 static function decCharReference( $codepoint ) {
1038 $point = intval( $codepoint );
1039 if( Sanitizer::validateCodepoint( $point ) ) {
1040 return sprintf( '&#%d;', $point );
1041 } else {
1042 return null;
1043 }
1044 }
1045
1046 static function hexCharReference( $codepoint ) {
1047 $point = hexdec( $codepoint );
1048 if( Sanitizer::validateCodepoint( $point ) ) {
1049 return sprintf( '&#x%x;', $point );
1050 } else {
1051 return null;
1052 }
1053 }
1054
1055 /**
1056 * Returns true if a given Unicode codepoint is a valid character in XML.
1057 * @param int $codepoint
1058 * @return bool
1059 */
1060 private static function validateCodepoint( $codepoint ) {
1061 return ($codepoint == 0x09)
1062 || ($codepoint == 0x0a)
1063 || ($codepoint == 0x0d)
1064 || ($codepoint >= 0x20 && $codepoint <= 0xd7ff)
1065 || ($codepoint >= 0xe000 && $codepoint <= 0xfffd)
1066 || ($codepoint >= 0x10000 && $codepoint <= 0x10ffff);
1067 }
1068
1069 /**
1070 * Decode any character references, numeric or named entities,
1071 * in the text and return a UTF-8 string.
1072 *
1073 * @param string $text
1074 * @return string
1075 * @public
1076 * @static
1077 */
1078 public static function decodeCharReferences( $text ) {
1079 return preg_replace_callback(
1080 MW_CHAR_REFS_REGEX,
1081 array( 'Sanitizer', 'decodeCharReferencesCallback' ),
1082 $text );
1083 }
1084
1085 /**
1086 * @param string $matches
1087 * @return string
1088 */
1089 static function decodeCharReferencesCallback( $matches ) {
1090 if( $matches[1] != '' ) {
1091 return Sanitizer::decodeEntity( $matches[1] );
1092 } elseif( $matches[2] != '' ) {
1093 return Sanitizer::decodeChar( intval( $matches[2] ) );
1094 } elseif( $matches[3] != '' ) {
1095 return Sanitizer::decodeChar( hexdec( $matches[3] ) );
1096 } elseif( $matches[4] != '' ) {
1097 return Sanitizer::decodeChar( hexdec( $matches[4] ) );
1098 }
1099 # Last case should be an ampersand by itself
1100 return $matches[0];
1101 }
1102
1103 /**
1104 * Return UTF-8 string for a codepoint if that is a valid
1105 * character reference, otherwise U+FFFD REPLACEMENT CHARACTER.
1106 * @param int $codepoint
1107 * @return string
1108 * @private
1109 */
1110 static function decodeChar( $codepoint ) {
1111 if( Sanitizer::validateCodepoint( $codepoint ) ) {
1112 return codepointToUtf8( $codepoint );
1113 } else {
1114 return UTF8_REPLACEMENT;
1115 }
1116 }
1117
1118 /**
1119 * If the named entity is defined in the HTML 4.0/XHTML 1.0 DTD,
1120 * return the UTF-8 encoding of that character. Otherwise, returns
1121 * pseudo-entity source (eg &foo;)
1122 *
1123 * @param string $name
1124 * @return string
1125 */
1126 static function decodeEntity( $name ) {
1127 global $wgHtmlEntities, $wgHtmlEntityAliases;
1128 if ( isset( $wgHtmlEntityAliases[$name] ) ) {
1129 $name = $wgHtmlEntityAliases[$name];
1130 }
1131 if( isset( $wgHtmlEntities[$name] ) ) {
1132 return codepointToUtf8( $wgHtmlEntities[$name] );
1133 } else {
1134 return "&$name;";
1135 }
1136 }
1137
1138 /**
1139 * Fetch the whitelist of acceptable attributes for a given
1140 * element name.
1141 *
1142 * @param string $element
1143 * @return array
1144 */
1145 static function attributeWhitelist( $element ) {
1146 static $list;
1147 if( !isset( $list ) ) {
1148 $list = Sanitizer::setupAttributeWhitelist();
1149 }
1150 return isset( $list[$element] )
1151 ? $list[$element]
1152 : array();
1153 }
1154
1155 /**
1156 * Foreach array key (an allowed HTML element), return an array
1157 * of allowed attributes
1158 * @return array
1159 */
1160 static function setupAttributeWhitelist() {
1161 $common = array( 'id', 'class', 'lang', 'dir', 'title', 'style' );
1162 $block = array_merge( $common, array( 'align' ) );
1163 $tablealign = array( 'align', 'char', 'charoff', 'valign' );
1164 $tablecell = array( 'abbr',
1165 'axis',
1166 'headers',
1167 'scope',
1168 'rowspan',
1169 'colspan',
1170 'nowrap', # deprecated
1171 'width', # deprecated
1172 'height', # deprecated
1173 'bgcolor' # deprecated
1174 );
1175
1176 # Numbers refer to sections in HTML 4.01 standard describing the element.
1177 # See: http://www.w3.org/TR/html4/
1178 $whitelist = array (
1179 # 7.5.4
1180 'div' => $block,
1181 'center' => $common, # deprecated
1182 'span' => $block, # ??
1183
1184 # 7.5.5
1185 'h1' => $block,
1186 'h2' => $block,
1187 'h3' => $block,
1188 'h4' => $block,
1189 'h5' => $block,
1190 'h6' => $block,
1191
1192 # 7.5.6
1193 # address
1194
1195 # 8.2.4
1196 # bdo
1197
1198 # 9.2.1
1199 'em' => $common,
1200 'strong' => $common,
1201 'cite' => $common,
1202 # dfn
1203 'code' => $common,
1204 # samp
1205 # kbd
1206 'var' => $common,
1207 # abbr
1208 # acronym
1209
1210 # 9.2.2
1211 'blockquote' => array_merge( $common, array( 'cite' ) ),
1212 # q
1213
1214 # 9.2.3
1215 'sub' => $common,
1216 'sup' => $common,
1217
1218 # 9.3.1
1219 'p' => $block,
1220
1221 # 9.3.2
1222 'br' => array( 'id', 'class', 'title', 'style', 'clear' ),
1223
1224 # 9.3.4
1225 'pre' => array_merge( $common, array( 'width' ) ),
1226
1227 # 9.4
1228 'ins' => array_merge( $common, array( 'cite', 'datetime' ) ),
1229 'del' => array_merge( $common, array( 'cite', 'datetime' ) ),
1230
1231 # 10.2
1232 'ul' => array_merge( $common, array( 'type' ) ),
1233 'ol' => array_merge( $common, array( 'type', 'start' ) ),
1234 'li' => array_merge( $common, array( 'type', 'value' ) ),
1235
1236 # 10.3
1237 'dl' => $common,
1238 'dd' => $common,
1239 'dt' => $common,
1240
1241 # 11.2.1
1242 'table' => array_merge( $common,
1243 array( 'summary', 'width', 'border', 'frame',
1244 'rules', 'cellspacing', 'cellpadding',
1245 'align', 'bgcolor',
1246 ) ),
1247
1248 # 11.2.2
1249 'caption' => array_merge( $common, array( 'align' ) ),
1250
1251 # 11.2.3
1252 'thead' => array_merge( $common, $tablealign ),
1253 'tfoot' => array_merge( $common, $tablealign ),
1254 'tbody' => array_merge( $common, $tablealign ),
1255
1256 # 11.2.4
1257 'colgroup' => array_merge( $common, array( 'span', 'width' ), $tablealign ),
1258 'col' => array_merge( $common, array( 'span', 'width' ), $tablealign ),
1259
1260 # 11.2.5
1261 'tr' => array_merge( $common, array( 'bgcolor' ), $tablealign ),
1262
1263 # 11.2.6
1264 'td' => array_merge( $common, $tablecell, $tablealign ),
1265 'th' => array_merge( $common, $tablecell, $tablealign ),
1266
1267 # 13.2
1268 # Not usually allowed, but may be used for extension-style hooks
1269 # such as <math> when it is rasterized
1270 'img' => array_merge( $common, array( 'alt' ) ),
1271
1272 # 15.2.1
1273 'tt' => $common,
1274 'b' => $common,
1275 'i' => $common,
1276 'big' => $common,
1277 'small' => $common,
1278 'strike' => $common,
1279 's' => $common,
1280 'u' => $common,
1281
1282 # 15.2.2
1283 'font' => array_merge( $common, array( 'size', 'color', 'face' ) ),
1284 # basefont
1285
1286 # 15.3
1287 'hr' => array_merge( $common, array( 'noshade', 'size', 'width' ) ),
1288
1289 # XHTML Ruby annotation text module, simple ruby only.
1290 # http://www.w3c.org/TR/ruby/
1291 'ruby' => $common,
1292 # rbc
1293 # rtc
1294 'rb' => $common,
1295 'rt' => $common, #array_merge( $common, array( 'rbspan' ) ),
1296 'rp' => $common,
1297
1298 # MathML root element, where used for extensions
1299 # 'title' may not be 100% valid here; it's XHTML
1300 # http://www.w3.org/TR/REC-MathML/
1301 'math' => array( 'class', 'style', 'id', 'title' ),
1302 );
1303 return $whitelist;
1304 }
1305
1306 /**
1307 * Take a fragment of (potentially invalid) HTML and return
1308 * a version with any tags removed, encoded as plain text.
1309 *
1310 * Warning: this return value must be further escaped for literal
1311 * inclusion in HTML output as of 1.10!
1312 *
1313 * @param string $text HTML fragment
1314 * @return string
1315 */
1316 static function stripAllTags( $text ) {
1317 # Actual <tags>
1318 $text = StringUtils::delimiterReplace( '<', '>', '', $text );
1319
1320 # Normalize &entities and whitespace
1321 $text = self::decodeCharReferences( $text );
1322 $text = self::normalizeWhitespace( $text );
1323
1324 return $text;
1325 }
1326
1327 /**
1328 * Hack up a private DOCTYPE with HTML's standard entity declarations.
1329 * PHP 4 seemed to know these if you gave it an HTML doctype, but
1330 * PHP 5.1 doesn't.
1331 *
1332 * Use for passing XHTML fragments to PHP's XML parsing functions
1333 *
1334 * @return string
1335 * @static
1336 */
1337 static function hackDocType() {
1338 global $wgHtmlEntities;
1339 $out = "<!DOCTYPE html [\n";
1340 foreach( $wgHtmlEntities as $entity => $codepoint ) {
1341 $out .= "<!ENTITY $entity \"&#$codepoint;\">";
1342 }
1343 $out .= "]>\n";
1344 return $out;
1345 }
1346
1347 static function cleanUrl( $url ) {
1348 # Normalize any HTML entities in input. They will be
1349 # re-escaped by makeExternalLink().
1350 $url = Sanitizer::decodeCharReferences( $url );
1351
1352 # Escape any control characters introduced by the above step
1353 $url = preg_replace( '/[\][<>"\\x00-\\x20\\x7F]/e', "urlencode('\\0')", $url );
1354
1355 # Validate hostname portion
1356 $matches = array();
1357 if( preg_match( '!^([^:]+:)(//[^/]+)?(.*)$!iD', $url, $matches ) ) {
1358 list( /* $whole */, $protocol, $host, $rest ) = $matches;
1359
1360 // Characters that will be ignored in IDNs.
1361 // http://tools.ietf.org/html/3454#section-3.1
1362 // Strip them before further processing so blacklists and such work.
1363 $strip = "/
1364 \\s| # general whitespace
1365 \xc2\xad| # 00ad SOFT HYPHEN
1366 \xe1\xa0\x86| # 1806 MONGOLIAN TODO SOFT HYPHEN
1367 \xe2\x80\x8b| # 200b ZERO WIDTH SPACE
1368 \xe2\x81\xa0| # 2060 WORD JOINER
1369 \xef\xbb\xbf| # feff ZERO WIDTH NO-BREAK SPACE
1370 \xcd\x8f| # 034f COMBINING GRAPHEME JOINER
1371 \xe1\xa0\x8b| # 180b MONGOLIAN FREE VARIATION SELECTOR ONE
1372 \xe1\xa0\x8c| # 180c MONGOLIAN FREE VARIATION SELECTOR TWO
1373 \xe1\xa0\x8d| # 180d MONGOLIAN FREE VARIATION SELECTOR THREE
1374 \xe2\x80\x8c| # 200c ZERO WIDTH NON-JOINER
1375 \xe2\x80\x8d| # 200d ZERO WIDTH JOINER
1376 [\xef\xb8\x80-\xef\xb8\x8f] # fe00-fe00f VARIATION SELECTOR-1-16
1377 /xuD";
1378
1379 $host = preg_replace( $strip, '', $host );
1380
1381 // @fixme: validate hostnames here
1382
1383 return $protocol . $host . $rest;
1384 } else {
1385 return $url;
1386 }
1387 }
1388
1389 }