Polish up r45109 (changes to header id generation)
[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, Sanitizer::NONE );
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 * Foreach array key (an allowed HTML element), return an array
1126 * of allowed attributes
1127 * @return array
1128 */
1129 static function setupAttributeWhitelist() {
1130 $common = array( 'id', 'class', 'lang', 'dir', 'title', 'style' );
1131 $block = array_merge( $common, array( 'align' ) );
1132 $tablealign = array( 'align', 'char', 'charoff', 'valign' );
1133 $tablecell = array( 'abbr',
1134 'axis',
1135 'headers',
1136 'scope',
1137 'rowspan',
1138 'colspan',
1139 'nowrap', # deprecated
1140 'width', # deprecated
1141 'height', # deprecated
1142 'bgcolor' # deprecated
1143 );
1144
1145 # Numbers refer to sections in HTML 4.01 standard describing the element.
1146 # See: http://www.w3.org/TR/html4/
1147 $whitelist = array (
1148 # 7.5.4
1149 'div' => $block,
1150 'center' => $common, # deprecated
1151 'span' => $block, # ??
1152
1153 # 7.5.5
1154 'h1' => $block,
1155 'h2' => $block,
1156 'h3' => $block,
1157 'h4' => $block,
1158 'h5' => $block,
1159 'h6' => $block,
1160
1161 # 7.5.6
1162 # address
1163
1164 # 8.2.4
1165 # bdo
1166
1167 # 9.2.1
1168 'em' => $common,
1169 'strong' => $common,
1170 'cite' => $common,
1171 # dfn
1172 'code' => $common,
1173 # samp
1174 # kbd
1175 'var' => $common,
1176 # abbr
1177 # acronym
1178
1179 # 9.2.2
1180 'blockquote' => array_merge( $common, array( 'cite' ) ),
1181 # q
1182
1183 # 9.2.3
1184 'sub' => $common,
1185 'sup' => $common,
1186
1187 # 9.3.1
1188 'p' => $block,
1189
1190 # 9.3.2
1191 'br' => array( 'id', 'class', 'title', 'style', 'clear' ),
1192
1193 # 9.3.4
1194 'pre' => array_merge( $common, array( 'width' ) ),
1195
1196 # 9.4
1197 'ins' => array_merge( $common, array( 'cite', 'datetime' ) ),
1198 'del' => array_merge( $common, array( 'cite', 'datetime' ) ),
1199
1200 # 10.2
1201 'ul' => array_merge( $common, array( 'type' ) ),
1202 'ol' => array_merge( $common, array( 'type', 'start' ) ),
1203 'li' => array_merge( $common, array( 'type', 'value' ) ),
1204
1205 # 10.3
1206 'dl' => $common,
1207 'dd' => $common,
1208 'dt' => $common,
1209
1210 # 11.2.1
1211 'table' => array_merge( $common,
1212 array( 'summary', 'width', 'border', 'frame',
1213 'rules', 'cellspacing', 'cellpadding',
1214 'align', 'bgcolor',
1215 ) ),
1216
1217 # 11.2.2
1218 'caption' => array_merge( $common, array( 'align' ) ),
1219
1220 # 11.2.3
1221 'thead' => array_merge( $common, $tablealign ),
1222 'tfoot' => array_merge( $common, $tablealign ),
1223 'tbody' => array_merge( $common, $tablealign ),
1224
1225 # 11.2.4
1226 'colgroup' => array_merge( $common, array( 'span', 'width' ), $tablealign ),
1227 'col' => array_merge( $common, array( 'span', 'width' ), $tablealign ),
1228
1229 # 11.2.5
1230 'tr' => array_merge( $common, array( 'bgcolor' ), $tablealign ),
1231
1232 # 11.2.6
1233 'td' => array_merge( $common, $tablecell, $tablealign ),
1234 'th' => array_merge( $common, $tablecell, $tablealign ),
1235
1236 # 13.2
1237 # Not usually allowed, but may be used for extension-style hooks
1238 # such as <math> when it is rasterized
1239 'img' => array_merge( $common, array( 'alt' ) ),
1240
1241 # 15.2.1
1242 'tt' => $common,
1243 'b' => $common,
1244 'i' => $common,
1245 'big' => $common,
1246 'small' => $common,
1247 'strike' => $common,
1248 's' => $common,
1249 'u' => $common,
1250
1251 # 15.2.2
1252 'font' => array_merge( $common, array( 'size', 'color', 'face' ) ),
1253 # basefont
1254
1255 # 15.3
1256 'hr' => array_merge( $common, array( 'noshade', 'size', 'width' ) ),
1257
1258 # XHTML Ruby annotation text module, simple ruby only.
1259 # http://www.w3c.org/TR/ruby/
1260 'ruby' => $common,
1261 # rbc
1262 # rtc
1263 'rb' => $common,
1264 'rt' => $common, #array_merge( $common, array( 'rbspan' ) ),
1265 'rp' => $common,
1266
1267 # MathML root element, where used for extensions
1268 # 'title' may not be 100% valid here; it's XHTML
1269 # http://www.w3.org/TR/REC-MathML/
1270 'math' => array( 'class', 'style', 'id', 'title' ),
1271 );
1272 return $whitelist;
1273 }
1274
1275 /**
1276 * Take a fragment of (potentially invalid) HTML and return
1277 * a version with any tags removed, encoded as plain text.
1278 *
1279 * Warning: this return value must be further escaped for literal
1280 * inclusion in HTML output as of 1.10!
1281 *
1282 * @param string $text HTML fragment
1283 * @return string
1284 */
1285 static function stripAllTags( $text ) {
1286 # Actual <tags>
1287 $text = StringUtils::delimiterReplace( '<', '>', '', $text );
1288
1289 # Normalize &entities and whitespace
1290 $text = self::decodeCharReferences( $text );
1291 $text = self::normalizeWhitespace( $text );
1292
1293 return $text;
1294 }
1295
1296 /**
1297 * Hack up a private DOCTYPE with HTML's standard entity declarations.
1298 * PHP 4 seemed to know these if you gave it an HTML doctype, but
1299 * PHP 5.1 doesn't.
1300 *
1301 * Use for passing XHTML fragments to PHP's XML parsing functions
1302 *
1303 * @return string
1304 * @static
1305 */
1306 static function hackDocType() {
1307 global $wgHtmlEntities;
1308 $out = "<!DOCTYPE html [\n";
1309 foreach( $wgHtmlEntities as $entity => $codepoint ) {
1310 $out .= "<!ENTITY $entity \"&#$codepoint;\">";
1311 }
1312 $out .= "]>\n";
1313 return $out;
1314 }
1315
1316 static function cleanUrl( $url ) {
1317 # Normalize any HTML entities in input. They will be
1318 # re-escaped by makeExternalLink().
1319 $url = Sanitizer::decodeCharReferences( $url );
1320
1321 # Escape any control characters introduced by the above step
1322 $url = preg_replace( '/[\][<>"\\x00-\\x20\\x7F]/e', "urlencode('\\0')", $url );
1323
1324 # Validate hostname portion
1325 $matches = array();
1326 if( preg_match( '!^([^:]+:)(//[^/]+)?(.*)$!iD', $url, $matches ) ) {
1327 list( /* $whole */, $protocol, $host, $rest ) = $matches;
1328
1329 // Characters that will be ignored in IDNs.
1330 // http://tools.ietf.org/html/3454#section-3.1
1331 // Strip them before further processing so blacklists and such work.
1332 $strip = "/
1333 \\s| # general whitespace
1334 \xc2\xad| # 00ad SOFT HYPHEN
1335 \xe1\xa0\x86| # 1806 MONGOLIAN TODO SOFT HYPHEN
1336 \xe2\x80\x8b| # 200b ZERO WIDTH SPACE
1337 \xe2\x81\xa0| # 2060 WORD JOINER
1338 \xef\xbb\xbf| # feff ZERO WIDTH NO-BREAK SPACE
1339 \xcd\x8f| # 034f COMBINING GRAPHEME JOINER
1340 \xe1\xa0\x8b| # 180b MONGOLIAN FREE VARIATION SELECTOR ONE
1341 \xe1\xa0\x8c| # 180c MONGOLIAN FREE VARIATION SELECTOR TWO
1342 \xe1\xa0\x8d| # 180d MONGOLIAN FREE VARIATION SELECTOR THREE
1343 \xe2\x80\x8c| # 200c ZERO WIDTH NON-JOINER
1344 \xe2\x80\x8d| # 200d ZERO WIDTH JOINER
1345 [\xef\xb8\x80-\xef\xb8\x8f] # fe00-fe00f VARIATION SELECTOR-1-16
1346 /xuD";
1347
1348 $host = preg_replace( $strip, '', $host );
1349
1350 // @fixme: validate hostnames here
1351
1352 return $protocol . $host . $rest;
1353 } else {
1354 return $url;
1355 }
1356 }
1357
1358 }