Re-committing 37663 for the new release, per old Wikitech-l discussion.
[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 * Given HTML input, escape with htmlspecialchars but un-escape entites.
826 * This allows (generally harmless) entities like &nbsp; to survive.
827 *
828 * @param string $html String to escape
829 * @return string Escaped input
830 */
831 static function escapeHtmlAllowEntities( $html ) {
832 # It seems wise to escape ' as well as ", as a matter of course. Can't
833 # hurt.
834 $html = htmlspecialchars( $html, ENT_QUOTES );
835 $html = str_replace( '&amp;', '&', $html );
836 $html = Sanitizer::normalizeCharReferences( $html );
837 return $html;
838 }
839
840 /**
841 * Regex replace callback for armoring links against further processing.
842 * @param array $matches
843 * @return string
844 * @private
845 */
846 private static function armorLinksCallback( $matches ) {
847 return str_replace( ':', '&#58;', $matches[1] );
848 }
849
850 /**
851 * Return an associative array of attribute names and values from
852 * a partial tag string. Attribute names are forces to lowercase,
853 * character references are decoded to UTF-8 text.
854 *
855 * @param string
856 * @return array
857 */
858 public static function decodeTagAttributes( $text ) {
859 $attribs = array();
860
861 if( trim( $text ) == '' ) {
862 return $attribs;
863 }
864
865 $pairs = array();
866 if( !preg_match_all(
867 MW_ATTRIBS_REGEX,
868 $text,
869 $pairs,
870 PREG_SET_ORDER ) ) {
871 return $attribs;
872 }
873
874 foreach( $pairs as $set ) {
875 $attribute = strtolower( $set[1] );
876 $value = Sanitizer::getTagAttributeCallback( $set );
877
878 // Normalize whitespace
879 $value = preg_replace( '/[\t\r\n ]+/', ' ', $value );
880 $value = trim( $value );
881
882 // Decode character references
883 $attribs[$attribute] = Sanitizer::decodeCharReferences( $value );
884 }
885 return $attribs;
886 }
887
888 /**
889 * Pick the appropriate attribute value from a match set from the
890 * MW_ATTRIBS_REGEX matches.
891 *
892 * @param array $set
893 * @return string
894 * @private
895 */
896 private static function getTagAttributeCallback( $set ) {
897 if( isset( $set[6] ) ) {
898 # Illegal #XXXXXX color with no quotes.
899 return $set[6];
900 } elseif( isset( $set[5] ) ) {
901 # No quotes.
902 return $set[5];
903 } elseif( isset( $set[4] ) ) {
904 # Single-quoted
905 return $set[4];
906 } elseif( isset( $set[3] ) ) {
907 # Double-quoted
908 return $set[3];
909 } elseif( !isset( $set[2] ) ) {
910 # In XHTML, attributes must have a value.
911 # For 'reduced' form, return explicitly the attribute name here.
912 return $set[1];
913 } else {
914 throw new MWException( "Tag conditions not met. This should never happen and is a bug." );
915 }
916 }
917
918 /**
919 * Normalize whitespace and character references in an XML source-
920 * encoded text for an attribute value.
921 *
922 * See http://www.w3.org/TR/REC-xml/#AVNormalize for background,
923 * but note that we're not returning the value, but are returning
924 * XML source fragments that will be slapped into output.
925 *
926 * @param string $text
927 * @return string
928 * @private
929 */
930 private static function normalizeAttributeValue( $text ) {
931 return str_replace( '"', '&quot;',
932 self::normalizeWhitespace(
933 Sanitizer::normalizeCharReferences( $text ) ) );
934 }
935
936 private static function normalizeWhitespace( $text ) {
937 return preg_replace(
938 '/\r\n|[\x20\x0d\x0a\x09]/',
939 ' ',
940 $text );
941 }
942
943 /**
944 * Ensure that any entities and character references are legal
945 * for XML and XHTML specifically. Any stray bits will be
946 * &amp;-escaped to result in a valid text fragment.
947 *
948 * a. any named char refs must be known in XHTML
949 * b. any numeric char refs must be legal chars, not invalid or forbidden
950 * c. use &#x, not &#X
951 * d. fix or reject non-valid attributes
952 *
953 * @param string $text
954 * @return string
955 * @private
956 */
957 static function normalizeCharReferences( $text ) {
958 return preg_replace_callback(
959 MW_CHAR_REFS_REGEX,
960 array( 'Sanitizer', 'normalizeCharReferencesCallback' ),
961 $text );
962 }
963 /**
964 * @param string $matches
965 * @return string
966 */
967 static function normalizeCharReferencesCallback( $matches ) {
968 $ret = null;
969 if( $matches[1] != '' ) {
970 $ret = Sanitizer::normalizeEntity( $matches[1] );
971 } elseif( $matches[2] != '' ) {
972 $ret = Sanitizer::decCharReference( $matches[2] );
973 } elseif( $matches[3] != '' ) {
974 $ret = Sanitizer::hexCharReference( $matches[3] );
975 } elseif( $matches[4] != '' ) {
976 $ret = Sanitizer::hexCharReference( $matches[4] );
977 }
978 if( is_null( $ret ) ) {
979 return htmlspecialchars( $matches[0] );
980 } else {
981 return $ret;
982 }
983 }
984
985 /**
986 * If the named entity is defined in the HTML 4.0/XHTML 1.0 DTD,
987 * return the named entity reference as is. If the entity is a
988 * MediaWiki-specific alias, returns the HTML equivalent. Otherwise,
989 * returns HTML-escaped text of pseudo-entity source (eg &amp;foo;)
990 *
991 * @param string $name
992 * @return string
993 * @static
994 */
995 static function normalizeEntity( $name ) {
996 global $wgHtmlEntities, $wgHtmlEntityAliases;
997 if ( isset( $wgHtmlEntityAliases[$name] ) ) {
998 return "&{$wgHtmlEntityAliases[$name]};";
999 } elseif( isset( $wgHtmlEntities[$name] ) ) {
1000 return "&$name;";
1001 } else {
1002 return "&amp;$name;";
1003 }
1004 }
1005
1006 static function decCharReference( $codepoint ) {
1007 $point = intval( $codepoint );
1008 if( Sanitizer::validateCodepoint( $point ) ) {
1009 return sprintf( '&#%d;', $point );
1010 } else {
1011 return null;
1012 }
1013 }
1014
1015 static function hexCharReference( $codepoint ) {
1016 $point = hexdec( $codepoint );
1017 if( Sanitizer::validateCodepoint( $point ) ) {
1018 return sprintf( '&#x%x;', $point );
1019 } else {
1020 return null;
1021 }
1022 }
1023
1024 /**
1025 * Returns true if a given Unicode codepoint is a valid character in XML.
1026 * @param int $codepoint
1027 * @return bool
1028 */
1029 private static function validateCodepoint( $codepoint ) {
1030 return ($codepoint == 0x09)
1031 || ($codepoint == 0x0a)
1032 || ($codepoint == 0x0d)
1033 || ($codepoint >= 0x20 && $codepoint <= 0xd7ff)
1034 || ($codepoint >= 0xe000 && $codepoint <= 0xfffd)
1035 || ($codepoint >= 0x10000 && $codepoint <= 0x10ffff);
1036 }
1037
1038 /**
1039 * Decode any character references, numeric or named entities,
1040 * in the text and return a UTF-8 string.
1041 *
1042 * @param string $text
1043 * @return string
1044 * @public
1045 * @static
1046 */
1047 public static function decodeCharReferences( $text ) {
1048 return preg_replace_callback(
1049 MW_CHAR_REFS_REGEX,
1050 array( 'Sanitizer', 'decodeCharReferencesCallback' ),
1051 $text );
1052 }
1053
1054 /**
1055 * @param string $matches
1056 * @return string
1057 */
1058 static function decodeCharReferencesCallback( $matches ) {
1059 if( $matches[1] != '' ) {
1060 return Sanitizer::decodeEntity( $matches[1] );
1061 } elseif( $matches[2] != '' ) {
1062 return Sanitizer::decodeChar( intval( $matches[2] ) );
1063 } elseif( $matches[3] != '' ) {
1064 return Sanitizer::decodeChar( hexdec( $matches[3] ) );
1065 } elseif( $matches[4] != '' ) {
1066 return Sanitizer::decodeChar( hexdec( $matches[4] ) );
1067 }
1068 # Last case should be an ampersand by itself
1069 return $matches[0];
1070 }
1071
1072 /**
1073 * Return UTF-8 string for a codepoint if that is a valid
1074 * character reference, otherwise U+FFFD REPLACEMENT CHARACTER.
1075 * @param int $codepoint
1076 * @return string
1077 * @private
1078 */
1079 static function decodeChar( $codepoint ) {
1080 if( Sanitizer::validateCodepoint( $codepoint ) ) {
1081 return codepointToUtf8( $codepoint );
1082 } else {
1083 return UTF8_REPLACEMENT;
1084 }
1085 }
1086
1087 /**
1088 * If the named entity is defined in the HTML 4.0/XHTML 1.0 DTD,
1089 * return the UTF-8 encoding of that character. Otherwise, returns
1090 * pseudo-entity source (eg &foo;)
1091 *
1092 * @param string $name
1093 * @return string
1094 */
1095 static function decodeEntity( $name ) {
1096 global $wgHtmlEntities, $wgHtmlEntityAliases;
1097 if ( isset( $wgHtmlEntityAliases[$name] ) ) {
1098 $name = $wgHtmlEntityAliases[$name];
1099 }
1100 if( isset( $wgHtmlEntities[$name] ) ) {
1101 return codepointToUtf8( $wgHtmlEntities[$name] );
1102 } else {
1103 return "&$name;";
1104 }
1105 }
1106
1107 /**
1108 * Fetch the whitelist of acceptable attributes for a given
1109 * element name.
1110 *
1111 * @param string $element
1112 * @return array
1113 */
1114 static function attributeWhitelist( $element ) {
1115 static $list;
1116 if( !isset( $list ) ) {
1117 $list = Sanitizer::setupAttributeWhitelist();
1118 }
1119 return isset( $list[$element] )
1120 ? $list[$element]
1121 : array();
1122 }
1123
1124 /**
1125 * @todo Document it a bit
1126 * @return array
1127 */
1128 static function setupAttributeWhitelist() {
1129 $common = array( 'id', 'class', 'lang', 'dir', 'title', 'style' );
1130 $block = array_merge( $common, array( 'align' ) );
1131 $tablealign = array( 'align', 'char', 'charoff', 'valign' );
1132 $tablecell = array( 'abbr',
1133 'axis',
1134 'headers',
1135 'scope',
1136 'rowspan',
1137 'colspan',
1138 'nowrap', # deprecated
1139 'width', # deprecated
1140 'height', # deprecated
1141 'bgcolor' # deprecated
1142 );
1143
1144 # Numbers refer to sections in HTML 4.01 standard describing the element.
1145 # See: http://www.w3.org/TR/html4/
1146 $whitelist = array (
1147 # 7.5.4
1148 'div' => $block,
1149 'center' => $common, # deprecated
1150 'span' => $block, # ??
1151
1152 # 7.5.5
1153 'h1' => $block,
1154 'h2' => $block,
1155 'h3' => $block,
1156 'h4' => $block,
1157 'h5' => $block,
1158 'h6' => $block,
1159
1160 # 7.5.6
1161 # address
1162
1163 # 8.2.4
1164 # bdo
1165
1166 # 9.2.1
1167 'em' => $common,
1168 'strong' => $common,
1169 'cite' => $common,
1170 # dfn
1171 'code' => $common,
1172 # samp
1173 # kbd
1174 'var' => $common,
1175 # abbr
1176 # acronym
1177
1178 # 9.2.2
1179 'blockquote' => array_merge( $common, array( 'cite' ) ),
1180 # q
1181
1182 # 9.2.3
1183 'sub' => $common,
1184 'sup' => $common,
1185
1186 # 9.3.1
1187 'p' => $block,
1188
1189 # 9.3.2
1190 'br' => array( 'id', 'class', 'title', 'style', 'clear' ),
1191
1192 # 9.3.4
1193 'pre' => array_merge( $common, array( 'width' ) ),
1194
1195 # 9.4
1196 'ins' => array_merge( $common, array( 'cite', 'datetime' ) ),
1197 'del' => array_merge( $common, array( 'cite', 'datetime' ) ),
1198
1199 # 10.2
1200 'ul' => array_merge( $common, array( 'type' ) ),
1201 'ol' => array_merge( $common, array( 'type', 'start' ) ),
1202 'li' => array_merge( $common, array( 'type', 'value' ) ),
1203
1204 # 10.3
1205 'dl' => $common,
1206 'dd' => $common,
1207 'dt' => $common,
1208
1209 # 11.2.1
1210 'table' => array_merge( $common,
1211 array( 'summary', 'width', 'border', 'frame',
1212 'rules', 'cellspacing', 'cellpadding',
1213 'align', 'bgcolor',
1214 ) ),
1215
1216 # 11.2.2
1217 'caption' => array_merge( $common, array( 'align' ) ),
1218
1219 # 11.2.3
1220 'thead' => array_merge( $common, $tablealign ),
1221 'tfoot' => array_merge( $common, $tablealign ),
1222 'tbody' => array_merge( $common, $tablealign ),
1223
1224 # 11.2.4
1225 'colgroup' => array_merge( $common, array( 'span', 'width' ), $tablealign ),
1226 'col' => array_merge( $common, array( 'span', 'width' ), $tablealign ),
1227
1228 # 11.2.5
1229 'tr' => array_merge( $common, array( 'bgcolor' ), $tablealign ),
1230
1231 # 11.2.6
1232 'td' => array_merge( $common, $tablecell, $tablealign ),
1233 'th' => array_merge( $common, $tablecell, $tablealign ),
1234
1235 # 13.2
1236 # Not usually allowed, but may be used for extension-style hooks
1237 # such as <math> when it is rasterized
1238 'img' => array_merge( $common, array( 'alt' ) ),
1239
1240 # 15.2.1
1241 'tt' => $common,
1242 'b' => $common,
1243 'i' => $common,
1244 'big' => $common,
1245 'small' => $common,
1246 'strike' => $common,
1247 's' => $common,
1248 'u' => $common,
1249
1250 # 15.2.2
1251 'font' => array_merge( $common, array( 'size', 'color', 'face' ) ),
1252 # basefont
1253
1254 # 15.3
1255 'hr' => array_merge( $common, array( 'noshade', 'size', 'width' ) ),
1256
1257 # XHTML Ruby annotation text module, simple ruby only.
1258 # http://www.w3c.org/TR/ruby/
1259 'ruby' => $common,
1260 # rbc
1261 # rtc
1262 'rb' => $common,
1263 'rt' => $common, #array_merge( $common, array( 'rbspan' ) ),
1264 'rp' => $common,
1265
1266 # MathML root element, where used for extensions
1267 # 'title' may not be 100% valid here; it's XHTML
1268 # http://www.w3.org/TR/REC-MathML/
1269 'math' => array( 'class', 'style', 'id', 'title' ),
1270 );
1271 return $whitelist;
1272 }
1273
1274 /**
1275 * Take a fragment of (potentially invalid) HTML and return
1276 * a version with any tags removed, encoded as plain text.
1277 *
1278 * Warning: this return value must be further escaped for literal
1279 * inclusion in HTML output as of 1.10!
1280 *
1281 * @param string $text HTML fragment
1282 * @return string
1283 */
1284 static function stripAllTags( $text ) {
1285 # Actual <tags>
1286 $text = StringUtils::delimiterReplace( '<', '>', '', $text );
1287
1288 # Normalize &entities and whitespace
1289 $text = self::decodeCharReferences( $text );
1290 $text = self::normalizeWhitespace( $text );
1291
1292 return $text;
1293 }
1294
1295 /**
1296 * Hack up a private DOCTYPE with HTML's standard entity declarations.
1297 * PHP 4 seemed to know these if you gave it an HTML doctype, but
1298 * PHP 5.1 doesn't.
1299 *
1300 * Use for passing XHTML fragments to PHP's XML parsing functions
1301 *
1302 * @return string
1303 * @static
1304 */
1305 static function hackDocType() {
1306 global $wgHtmlEntities;
1307 $out = "<!DOCTYPE html [\n";
1308 foreach( $wgHtmlEntities as $entity => $codepoint ) {
1309 $out .= "<!ENTITY $entity \"&#$codepoint;\">";
1310 }
1311 $out .= "]>\n";
1312 return $out;
1313 }
1314
1315 static function cleanUrl( $url ) {
1316 # Normalize any HTML entities in input. They will be
1317 # re-escaped by makeExternalLink().
1318 $url = Sanitizer::decodeCharReferences( $url );
1319
1320 # Escape any control characters introduced by the above step
1321 $url = preg_replace( '/[\][<>"\\x00-\\x20\\x7F]/e', "urlencode('\\0')", $url );
1322
1323 # Validate hostname portion
1324 $matches = array();
1325 if( preg_match( '!^([^:]+:)(//[^/]+)?(.*)$!iD', $url, $matches ) ) {
1326 list( /* $whole */, $protocol, $host, $rest ) = $matches;
1327
1328 // Characters that will be ignored in IDNs.
1329 // http://tools.ietf.org/html/3454#section-3.1
1330 // Strip them before further processing so blacklists and such work.
1331 $strip = "/
1332 \\s| # general whitespace
1333 \xc2\xad| # 00ad SOFT HYPHEN
1334 \xe1\xa0\x86| # 1806 MONGOLIAN TODO SOFT HYPHEN
1335 \xe2\x80\x8b| # 200b ZERO WIDTH SPACE
1336 \xe2\x81\xa0| # 2060 WORD JOINER
1337 \xef\xbb\xbf| # feff ZERO WIDTH NO-BREAK SPACE
1338 \xcd\x8f| # 034f COMBINING GRAPHEME JOINER
1339 \xe1\xa0\x8b| # 180b MONGOLIAN FREE VARIATION SELECTOR ONE
1340 \xe1\xa0\x8c| # 180c MONGOLIAN FREE VARIATION SELECTOR TWO
1341 \xe1\xa0\x8d| # 180d MONGOLIAN FREE VARIATION SELECTOR THREE
1342 \xe2\x80\x8c| # 200c ZERO WIDTH NON-JOINER
1343 \xe2\x80\x8d| # 200d ZERO WIDTH JOINER
1344 [\xef\xb8\x80-\xef\xb8\x8f] # fe00-fe00f VARIATION SELECTOR-1-16
1345 /xuD";
1346
1347 $host = preg_replace( $strip, '', $host );
1348
1349 // @fixme: validate hostnames here
1350
1351 return $protocol . $host . $rest;
1352 } else {
1353 return $url;
1354 }
1355 }
1356
1357 }