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