f79e94d459cba8dd19807a14ab933a0810664c4a
[lhc/web/wiklou.git] / includes / Sanitizer.php
1 <?php
2 /**
3 * HTML sanitizer for %MediaWiki.
4 *
5 * Copyright © 2002-2005 Brion Vibber <brion@pobox.com> et al
6 * https://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 * HTML sanitizer for MediaWiki
29 * @ingroup Parser
30 */
31 class Sanitizer {
32 /**
33 * Regular expression to match various types of character references in
34 * Sanitizer::normalizeCharReferences and Sanitizer::decodeCharReferences
35 */
36 const CHAR_REFS_REGEX =
37 '/&([A-Za-z0-9\x80-\xff]+);
38 |&\#([0-9]+);
39 |&\#[xX]([0-9A-Fa-f]+);
40 |(&)/x';
41
42 /**
43 * Blacklist for evil uris like javascript:
44 * WARNING: DO NOT use this in any place that actually requires blacklisting
45 * for security reasons. There are NUMEROUS[1] ways to bypass blacklisting, the
46 * only way to be secure from javascript: uri based xss vectors is to whitelist
47 * things that you know are safe and deny everything else.
48 * [1]: http://ha.ckers.org/xss.html
49 */
50 const EVIL_URI_PATTERN = '!(^|\s|\*/\s*)(javascript|vbscript)([^\w]|$)!i';
51 const XMLNS_ATTRIBUTE_PATTERN = "/^xmlns:[:A-Z_a-z-.0-9]+$/";
52
53 /**
54 * List of all named character entities defined in HTML 4.01
55 * http://www.w3.org/TR/html4/sgml/entities.html
56 * As well as &apos; which is only defined starting in XHTML1.
57 */
58 private static $htmlEntities = array(
59 'Aacute' => 193,
60 'aacute' => 225,
61 'Acirc' => 194,
62 'acirc' => 226,
63 'acute' => 180,
64 'AElig' => 198,
65 'aelig' => 230,
66 'Agrave' => 192,
67 'agrave' => 224,
68 'alefsym' => 8501,
69 'Alpha' => 913,
70 'alpha' => 945,
71 'amp' => 38,
72 'and' => 8743,
73 'ang' => 8736,
74 'apos' => 39, // New in XHTML & HTML 5; avoid in output for compatibility with IE.
75 'Aring' => 197,
76 'aring' => 229,
77 'asymp' => 8776,
78 'Atilde' => 195,
79 'atilde' => 227,
80 'Auml' => 196,
81 'auml' => 228,
82 'bdquo' => 8222,
83 'Beta' => 914,
84 'beta' => 946,
85 'brvbar' => 166,
86 'bull' => 8226,
87 'cap' => 8745,
88 'Ccedil' => 199,
89 'ccedil' => 231,
90 'cedil' => 184,
91 'cent' => 162,
92 'Chi' => 935,
93 'chi' => 967,
94 'circ' => 710,
95 'clubs' => 9827,
96 'cong' => 8773,
97 'copy' => 169,
98 'crarr' => 8629,
99 'cup' => 8746,
100 'curren' => 164,
101 'dagger' => 8224,
102 'Dagger' => 8225,
103 'darr' => 8595,
104 'dArr' => 8659,
105 'deg' => 176,
106 'Delta' => 916,
107 'delta' => 948,
108 'diams' => 9830,
109 'divide' => 247,
110 'Eacute' => 201,
111 'eacute' => 233,
112 'Ecirc' => 202,
113 'ecirc' => 234,
114 'Egrave' => 200,
115 'egrave' => 232,
116 'empty' => 8709,
117 'emsp' => 8195,
118 'ensp' => 8194,
119 'Epsilon' => 917,
120 'epsilon' => 949,
121 'equiv' => 8801,
122 'Eta' => 919,
123 'eta' => 951,
124 'ETH' => 208,
125 'eth' => 240,
126 'Euml' => 203,
127 'euml' => 235,
128 'euro' => 8364,
129 'exist' => 8707,
130 'fnof' => 402,
131 'forall' => 8704,
132 'frac12' => 189,
133 'frac14' => 188,
134 'frac34' => 190,
135 'frasl' => 8260,
136 'Gamma' => 915,
137 'gamma' => 947,
138 'ge' => 8805,
139 'gt' => 62,
140 'harr' => 8596,
141 'hArr' => 8660,
142 'hearts' => 9829,
143 'hellip' => 8230,
144 'Iacute' => 205,
145 'iacute' => 237,
146 'Icirc' => 206,
147 'icirc' => 238,
148 'iexcl' => 161,
149 'Igrave' => 204,
150 'igrave' => 236,
151 'image' => 8465,
152 'infin' => 8734,
153 'int' => 8747,
154 'Iota' => 921,
155 'iota' => 953,
156 'iquest' => 191,
157 'isin' => 8712,
158 'Iuml' => 207,
159 'iuml' => 239,
160 'Kappa' => 922,
161 'kappa' => 954,
162 'Lambda' => 923,
163 'lambda' => 955,
164 'lang' => 9001,
165 'laquo' => 171,
166 'larr' => 8592,
167 'lArr' => 8656,
168 'lceil' => 8968,
169 'ldquo' => 8220,
170 'le' => 8804,
171 'lfloor' => 8970,
172 'lowast' => 8727,
173 'loz' => 9674,
174 'lrm' => 8206,
175 'lsaquo' => 8249,
176 'lsquo' => 8216,
177 'lt' => 60,
178 'macr' => 175,
179 'mdash' => 8212,
180 'micro' => 181,
181 'middot' => 183,
182 'minus' => 8722,
183 'Mu' => 924,
184 'mu' => 956,
185 'nabla' => 8711,
186 'nbsp' => 160,
187 'ndash' => 8211,
188 'ne' => 8800,
189 'ni' => 8715,
190 'not' => 172,
191 'notin' => 8713,
192 'nsub' => 8836,
193 'Ntilde' => 209,
194 'ntilde' => 241,
195 'Nu' => 925,
196 'nu' => 957,
197 'Oacute' => 211,
198 'oacute' => 243,
199 'Ocirc' => 212,
200 'ocirc' => 244,
201 'OElig' => 338,
202 'oelig' => 339,
203 'Ograve' => 210,
204 'ograve' => 242,
205 'oline' => 8254,
206 'Omega' => 937,
207 'omega' => 969,
208 'Omicron' => 927,
209 'omicron' => 959,
210 'oplus' => 8853,
211 'or' => 8744,
212 'ordf' => 170,
213 'ordm' => 186,
214 'Oslash' => 216,
215 'oslash' => 248,
216 'Otilde' => 213,
217 'otilde' => 245,
218 'otimes' => 8855,
219 'Ouml' => 214,
220 'ouml' => 246,
221 'para' => 182,
222 'part' => 8706,
223 'permil' => 8240,
224 'perp' => 8869,
225 'Phi' => 934,
226 'phi' => 966,
227 'Pi' => 928,
228 'pi' => 960,
229 'piv' => 982,
230 'plusmn' => 177,
231 'pound' => 163,
232 'prime' => 8242,
233 'Prime' => 8243,
234 'prod' => 8719,
235 'prop' => 8733,
236 'Psi' => 936,
237 'psi' => 968,
238 'quot' => 34,
239 'radic' => 8730,
240 'rang' => 9002,
241 'raquo' => 187,
242 'rarr' => 8594,
243 'rArr' => 8658,
244 'rceil' => 8969,
245 'rdquo' => 8221,
246 'real' => 8476,
247 'reg' => 174,
248 'rfloor' => 8971,
249 'Rho' => 929,
250 'rho' => 961,
251 'rlm' => 8207,
252 'rsaquo' => 8250,
253 'rsquo' => 8217,
254 'sbquo' => 8218,
255 'Scaron' => 352,
256 'scaron' => 353,
257 'sdot' => 8901,
258 'sect' => 167,
259 'shy' => 173,
260 'Sigma' => 931,
261 'sigma' => 963,
262 'sigmaf' => 962,
263 'sim' => 8764,
264 'spades' => 9824,
265 'sub' => 8834,
266 'sube' => 8838,
267 'sum' => 8721,
268 'sup' => 8835,
269 'sup1' => 185,
270 'sup2' => 178,
271 'sup3' => 179,
272 'supe' => 8839,
273 'szlig' => 223,
274 'Tau' => 932,
275 'tau' => 964,
276 'there4' => 8756,
277 'Theta' => 920,
278 'theta' => 952,
279 'thetasym' => 977,
280 'thinsp' => 8201,
281 'THORN' => 222,
282 'thorn' => 254,
283 'tilde' => 732,
284 'times' => 215,
285 'trade' => 8482,
286 'Uacute' => 218,
287 'uacute' => 250,
288 'uarr' => 8593,
289 'uArr' => 8657,
290 'Ucirc' => 219,
291 'ucirc' => 251,
292 'Ugrave' => 217,
293 'ugrave' => 249,
294 'uml' => 168,
295 'upsih' => 978,
296 'Upsilon' => 933,
297 'upsilon' => 965,
298 'Uuml' => 220,
299 'uuml' => 252,
300 'weierp' => 8472,
301 'Xi' => 926,
302 'xi' => 958,
303 'Yacute' => 221,
304 'yacute' => 253,
305 'yen' => 165,
306 'Yuml' => 376,
307 'yuml' => 255,
308 'Zeta' => 918,
309 'zeta' => 950,
310 'zwj' => 8205,
311 'zwnj' => 8204
312 );
313
314 /**
315 * Character entity aliases accepted by MediaWiki
316 */
317 private static $htmlEntityAliases = array(
318 'רלמ' => 'rlm',
319 'رلم' => 'rlm',
320 );
321
322 /**
323 * Lazy-initialised attributes regex, see getAttribsRegex()
324 */
325 private static $attribsRegex;
326
327 /**
328 * Regular expression to match HTML/XML attribute pairs within a tag.
329 * Allows some... latitude.
330 * Used in Sanitizer::fixTagAttributes and Sanitizer::decodeTagAttributes
331 * @return string
332 */
333 static function getAttribsRegex() {
334 if ( self::$attribsRegex === null ) {
335 $attribFirst = '[:A-Z_a-z0-9]';
336 $attrib = '[:A-Z_a-z-.0-9]';
337 $space = '[\x09\x0a\x0d\x20]';
338 self::$attribsRegex =
339 "/(?:^|$space)({$attribFirst}{$attrib}*)
340 ($space*=$space*
341 (?:
342 # The attribute value: quoted or alone
343 \"([^<\"]*)\"
344 | '([^<']*)'
345 | ([a-zA-Z0-9!#$%&()*,\\-.\\/:;<>?@[\\]^_`{|}~]+)
346 | (\#[0-9a-fA-F]+) # Technically wrong, but lots of
347 # colors are specified like this.
348 # We'll be normalizing it.
349 )
350 )?(?=$space|\$)/sx";
351 }
352 return self::$attribsRegex;
353 }
354
355 /**
356 * Cleans up HTML, removes dangerous tags and attributes, and
357 * removes HTML comments
358 * @param string $text
359 * @param callable $processCallback Callback to do any variable or parameter
360 * replacements in HTML attribute values
361 * @param array|bool $args Arguments for the processing callback
362 * @param array $extratags For any extra tags to include
363 * @param array $removetags For any tags (default or extra) to exclude
364 * @return string
365 */
366 public static function removeHTMLtags( $text, $processCallback = null,
367 $args = array(), $extratags = array(), $removetags = array()
368 ) {
369 global $wgUseTidy, $wgAllowMicrodataAttributes, $wgAllowImageTag;
370
371 static $htmlpairsStatic, $htmlsingle, $htmlsingleonly, $htmlnest, $tabletags,
372 $htmllist, $listtags, $htmlsingleallowed, $htmlelementsStatic, $staticInitialised;
373
374 // Base our staticInitialised variable off of the global config state so that if the globals
375 // are changed (like in the screwed up test system) we will re-initialise the settings.
376 $globalContext = implode( '-', compact( 'wgAllowMicrodataAttributes', 'wgAllowImageTag' ) );
377 if ( !$staticInitialised || $staticInitialised != $globalContext ) {
378
379 $htmlpairsStatic = array( # Tags that must be closed
380 'b', 'bdi', 'del', 'i', 'ins', 'u', 'font', 'big', 'small', 'sub', 'sup', 'h1',
381 'h2', 'h3', 'h4', 'h5', 'h6', 'cite', 'code', 'em', 's',
382 'strike', 'strong', 'tt', 'var', 'div', 'center',
383 'blockquote', 'ol', 'ul', 'dl', 'table', 'caption', 'pre',
384 'ruby', 'rb', 'rp', 'rt', 'rtc', 'p', 'span', 'abbr', 'dfn',
385 'kbd', 'samp', 'data', 'time', 'mark'
386 );
387 $htmlsingle = array(
388 'br', 'wbr', 'hr', 'li', 'dt', 'dd'
389 );
390 $htmlsingleonly = array( # Elements that cannot have close tags
391 'br', 'wbr', 'hr'
392 );
393 if ( $wgAllowMicrodataAttributes ) {
394 $htmlsingle[] = $htmlsingleonly[] = 'meta';
395 $htmlsingle[] = $htmlsingleonly[] = 'link';
396 }
397 $htmlnest = array( # Tags that can be nested--??
398 'table', 'tr', 'td', 'th', 'div', 'blockquote', 'ol', 'ul',
399 'li', 'dl', 'dt', 'dd', 'font', 'big', 'small', 'sub', 'sup', 'span',
400 'var', 'kbd', 'samp', 'em', 'strong', 'q', 'ruby', 'bdo'
401 );
402 $tabletags = array( # Can only appear inside table, we will close them
403 'td', 'th', 'tr',
404 );
405 $htmllist = array( # Tags used by list
406 'ul', 'ol',
407 );
408 $listtags = array( # Tags that can appear in a list
409 'li',
410 );
411
412 if ( $wgAllowImageTag ) {
413 $htmlsingle[] = 'img';
414 $htmlsingleonly[] = 'img';
415 }
416
417 $htmlsingleallowed = array_unique( array_merge( $htmlsingle, $tabletags ) );
418 $htmlelementsStatic = array_unique( array_merge( $htmlsingle, $htmlpairsStatic, $htmlnest ) );
419
420 # Convert them all to hashtables for faster lookup
421 $vars = array( 'htmlpairsStatic', 'htmlsingle', 'htmlsingleonly', 'htmlnest', 'tabletags',
422 'htmllist', 'listtags', 'htmlsingleallowed', 'htmlelementsStatic' );
423 foreach ( $vars as $var ) {
424 $$var = array_flip( $$var );
425 }
426 $staticInitialised = $globalContext;
427 }
428 # Populate $htmlpairs and $htmlelements with the $extratags and $removetags arrays
429 $extratags = array_flip( $extratags );
430 $removetags = array_flip( $removetags );
431 $htmlpairs = array_merge( $extratags, $htmlpairsStatic );
432 $htmlelements = array_diff_key( array_merge( $extratags, $htmlelementsStatic ), $removetags );
433
434 # Remove HTML comments
435 $text = Sanitizer::removeHTMLcomments( $text );
436 $bits = explode( '<', $text );
437 $text = str_replace( '>', '&gt;', array_shift( $bits ) );
438 if ( !$wgUseTidy ) {
439 $tagstack = $tablestack = array();
440 foreach ( $bits as $x ) {
441 $regs = array();
442 # $slash: Does the current element start with a '/'?
443 # $t: Current element name
444 # $params: String between element name and >
445 # $brace: Ending '>' or '/>'
446 # $rest: Everything until the next element of $bits
447 if ( preg_match( '!^(/?)([^\\s/>]+)([^>]*?)(/{0,1}>)([^<]*)$!', $x, $regs ) ) {
448 list( /* $qbar */, $slash, $t, $params, $brace, $rest ) = $regs;
449 } else {
450 $slash = $t = $params = $brace = $rest = null;
451 }
452
453 $badtag = false;
454 if ( isset( $htmlelements[$t = strtolower( $t )] ) ) {
455 # Check our stack
456 if ( $slash && isset( $htmlsingleonly[$t] ) ) {
457 $badtag = true;
458 } elseif ( $slash ) {
459 # Closing a tag... is it the one we just opened?
460 wfSuppressWarnings();
461 $ot = array_pop( $tagstack );
462 wfRestoreWarnings();
463
464 if ( $ot != $t ) {
465 if ( isset( $htmlsingleallowed[$ot] ) ) {
466 # Pop all elements with an optional close tag
467 # and see if we find a match below them
468 $optstack = array();
469 array_push( $optstack, $ot );
470 wfSuppressWarnings();
471 $ot = array_pop( $tagstack );
472 wfRestoreWarnings();
473 while ( $ot != $t && isset( $htmlsingleallowed[$ot] ) ) {
474 array_push( $optstack, $ot );
475 wfSuppressWarnings();
476 $ot = array_pop( $tagstack );
477 wfRestoreWarnings();
478 }
479 if ( $t != $ot ) {
480 # No match. Push the optional elements back again
481 $badtag = true;
482 wfSuppressWarnings();
483 $ot = array_pop( $optstack );
484 wfRestoreWarnings();
485 while ( $ot ) {
486 array_push( $tagstack, $ot );
487 wfSuppressWarnings();
488 $ot = array_pop( $optstack );
489 wfRestoreWarnings();
490 }
491 }
492 } else {
493 wfSuppressWarnings();
494 array_push( $tagstack, $ot );
495 wfRestoreWarnings();
496
497 # <li> can be nested in <ul> or <ol>, skip those cases:
498 if ( !isset( $htmllist[$ot] ) || !isset( $listtags[$t] ) ) {
499 $badtag = true;
500 }
501 }
502 } else {
503 if ( $t == 'table' ) {
504 $tagstack = array_pop( $tablestack );
505 }
506 }
507 $newparams = '';
508 } else {
509 # Keep track for later
510 if ( isset( $tabletags[$t] ) && !in_array( 'table', $tagstack ) ) {
511 $badtag = true;
512 } elseif ( in_array( $t, $tagstack ) && !isset( $htmlnest[$t] ) ) {
513 $badtag = true;
514 # Is it a self closed htmlpair ? (bug 5487)
515 } elseif ( $brace == '/>' && isset( $htmlpairs[$t] ) ) {
516 $badtag = true;
517 } elseif ( isset( $htmlsingleonly[$t] ) ) {
518 # Hack to force empty tag for unclosable elements
519 $brace = '/>';
520 } elseif ( isset( $htmlsingle[$t] ) ) {
521 # Hack to not close $htmlsingle tags
522 $brace = null;
523 # Still need to push this optionally-closed tag to
524 # the tag stack so that we can match end tags
525 # instead of marking them as bad.
526 array_push( $tagstack, $t );
527 } elseif ( isset( $tabletags[$t] ) && in_array( $t, $tagstack ) ) {
528 // New table tag but forgot to close the previous one
529 $text .= "</$t>";
530 } else {
531 if ( $t == 'table' ) {
532 array_push( $tablestack, $tagstack );
533 $tagstack = array();
534 }
535 array_push( $tagstack, $t );
536 }
537
538 # Replace any variables or template parameters with
539 # plaintext results.
540 if ( is_callable( $processCallback ) ) {
541 call_user_func_array( $processCallback, array( &$params, $args ) );
542 }
543
544 if ( !Sanitizer::validateTag( $params, $t ) ) {
545 $badtag = true;
546 }
547
548 # Strip non-approved attributes from the tag
549 $newparams = Sanitizer::fixTagAttributes( $params, $t );
550 }
551 if ( !$badtag ) {
552 $rest = str_replace( '>', '&gt;', $rest );
553 $close = ( $brace == '/>' && !$slash ) ? ' /' : '';
554 $text .= "<$slash$t$newparams$close>$rest";
555 continue;
556 }
557 }
558 $text .= '&lt;' . str_replace( '>', '&gt;', $x );
559 }
560 # Close off any remaining tags
561 while ( is_array( $tagstack ) && ( $t = array_pop( $tagstack ) ) ) {
562 $text .= "</$t>\n";
563 if ( $t == 'table' ) {
564 $tagstack = array_pop( $tablestack );
565 }
566 }
567 } else {
568 # this might be possible using tidy itself
569 foreach ( $bits as $x ) {
570 preg_match(
571 '/^(\\/?)(\\w+)([^>]*?)(\\/{0,1}>)([^<]*)$/',
572 $x,
573 $regs
574 );
575
576 wfSuppressWarnings();
577 list( /* $qbar */, $slash, $t, $params, $brace, $rest ) = $regs;
578 wfRestoreWarnings();
579
580 $badtag = false;
581 if ( isset( $htmlelements[$t = strtolower( $t )] ) ) {
582 if ( is_callable( $processCallback ) ) {
583 call_user_func_array( $processCallback, array( &$params, $args ) );
584 }
585
586 if ( !Sanitizer::validateTag( $params, $t ) ) {
587 $badtag = true;
588 }
589
590 $newparams = Sanitizer::fixTagAttributes( $params, $t );
591 if ( !$badtag ) {
592 $rest = str_replace( '>', '&gt;', $rest );
593 $text .= "<$slash$t$newparams$brace$rest";
594 continue;
595 }
596 }
597 $text .= '&lt;' . str_replace( '>', '&gt;', $x );
598 }
599 }
600 return $text;
601 }
602
603 /**
604 * Remove '<!--', '-->', and everything between.
605 * To avoid leaving blank lines, when a comment is both preceded
606 * and followed by a newline (ignoring spaces), trim leading and
607 * trailing spaces and one of the newlines.
608 *
609 * @param string $text
610 * @return string
611 */
612 public static function removeHTMLcomments( $text ) {
613 while ( ( $start = strpos( $text, '<!--' ) ) !== false ) {
614 $end = strpos( $text, '-->', $start + 4 );
615 if ( $end === false ) {
616 # Unterminated comment; bail out
617 break;
618 }
619
620 $end += 3;
621
622 # Trim space and newline if the comment is both
623 # preceded and followed by a newline
624 $spaceStart = max( $start - 1, 0 );
625 $spaceLen = $end - $spaceStart;
626 while ( substr( $text, $spaceStart, 1 ) === ' ' && $spaceStart > 0 ) {
627 $spaceStart--;
628 $spaceLen++;
629 }
630 while ( substr( $text, $spaceStart + $spaceLen, 1 ) === ' ' ) {
631 $spaceLen++;
632 }
633 if ( substr( $text, $spaceStart, 1 ) === "\n"
634 && substr( $text, $spaceStart + $spaceLen, 1 ) === "\n" ) {
635 # Remove the comment, leading and trailing
636 # spaces, and leave only one newline.
637 $text = substr_replace( $text, "\n", $spaceStart, $spaceLen + 1 );
638 } else {
639 # Remove just the comment.
640 $text = substr_replace( $text, '', $start, $end - $start );
641 }
642 }
643 return $text;
644 }
645
646 /**
647 * Takes attribute names and values for a tag and the tag name and
648 * validates that the tag is allowed to be present.
649 * This DOES NOT validate the attributes, nor does it validate the
650 * tags themselves. This method only handles the special circumstances
651 * where we may want to allow a tag within content but ONLY when it has
652 * specific attributes set.
653 *
654 * @param string $params
655 * @param string $element
656 * @return bool
657 */
658 static function validateTag( $params, $element ) {
659 $params = Sanitizer::decodeTagAttributes( $params );
660
661 if ( $element == 'meta' || $element == 'link' ) {
662 if ( !isset( $params['itemprop'] ) ) {
663 // <meta> and <link> must have an itemprop="" otherwise they are not valid or safe in content
664 return false;
665 }
666 if ( $element == 'meta' && !isset( $params['content'] ) ) {
667 // <meta> must have a content="" for the itemprop
668 return false;
669 }
670 if ( $element == 'link' && !isset( $params['href'] ) ) {
671 // <link> must have an associated href=""
672 return false;
673 }
674 }
675
676 return true;
677 }
678
679 /**
680 * Take an array of attribute names and values and normalize or discard
681 * illegal values for the given element type.
682 *
683 * - Discards attributes not on a whitelist for the given element
684 * - Unsafe style attributes are discarded
685 * - Invalid id attributes are re-encoded
686 *
687 * @param array $attribs
688 * @param string $element
689 * @return array
690 *
691 * @todo Check for legal values where the DTD limits things.
692 * @todo Check for unique id attribute :P
693 */
694 static function validateTagAttributes( $attribs, $element ) {
695 return Sanitizer::validateAttributes( $attribs,
696 Sanitizer::attributeWhitelist( $element ) );
697 }
698
699 /**
700 * Take an array of attribute names and values and normalize or discard
701 * illegal values for the given whitelist.
702 *
703 * - Discards attributes not the given whitelist
704 * - Unsafe style attributes are discarded
705 * - Invalid id attributes are re-encoded
706 *
707 * @param array $attribs
708 * @param array $whitelist List of allowed attribute names
709 * @return array
710 *
711 * @todo Check for legal values where the DTD limits things.
712 * @todo Check for unique id attribute :P
713 */
714 static function validateAttributes( $attribs, $whitelist ) {
715 global $wgAllowRdfaAttributes, $wgAllowMicrodataAttributes;
716
717 $whitelist = array_flip( $whitelist );
718 $hrefExp = '/^(' . wfUrlProtocols() . ')[^\s]+$/';
719
720 $out = array();
721 foreach ( $attribs as $attribute => $value ) {
722 #allow XML namespace declaration if RDFa is enabled
723 if ( $wgAllowRdfaAttributes && preg_match( self::XMLNS_ATTRIBUTE_PATTERN, $attribute ) ) {
724 if ( !preg_match( self::EVIL_URI_PATTERN, $value ) ) {
725 $out[$attribute] = $value;
726 }
727
728 continue;
729 }
730
731 # Allow any attribute beginning with "data-"
732 if ( !preg_match( '/^data-/i', $attribute ) && !isset( $whitelist[$attribute] ) ) {
733 continue;
734 }
735
736 # Strip javascript "expression" from stylesheets.
737 # http://msdn.microsoft.com/workshop/author/dhtml/overview/recalc.asp
738 if ( $attribute == 'style' ) {
739 $value = Sanitizer::checkCss( $value );
740 }
741
742 if ( $attribute === 'id' ) {
743 $value = Sanitizer::escapeId( $value, 'noninitial' );
744 }
745
746 # WAI-ARIA
747 # http://www.w3.org/TR/wai-aria/
748 # http://www.whatwg.org/html/elements.html#wai-aria
749 # For now we only support role="presentation" until we work out what roles should be
750 # usable by content and we ensure that our code explicitly rejects patterns that
751 # violate HTML5's ARIA restrictions.
752 if ( $attribute === 'role' && $value !== 'presentation' ) {
753 continue;
754 }
755
756 // RDFa and microdata properties allow URLs, URIs and/or CURIs.
757 // Check them for sanity.
758 if ( $attribute === 'rel' || $attribute === 'rev'
759 # RDFa
760 || $attribute === 'about' || $attribute === 'property'
761 || $attribute === 'resource' || $attribute === 'datatype'
762 || $attribute === 'typeof'
763 # HTML5 microdata
764 || $attribute === 'itemid' || $attribute === 'itemprop'
765 || $attribute === 'itemref' || $attribute === 'itemscope'
766 || $attribute === 'itemtype'
767 ) {
768 //Paranoia. Allow "simple" values but suppress javascript
769 if ( preg_match( self::EVIL_URI_PATTERN, $value ) ) {
770 continue;
771 }
772 }
773
774 # NOTE: even though elements using href/src are not allowed directly, supply
775 # validation code that can be used by tag hook handlers, etc
776 if ( $attribute === 'href' || $attribute === 'src' ) {
777 if ( !preg_match( $hrefExp, $value ) ) {
778 continue; //drop any href or src attributes not using an allowed protocol.
779 // NOTE: this also drops all relative URLs
780 }
781 }
782
783 // If this attribute was previously set, override it.
784 // Output should only have one attribute of each name.
785 $out[$attribute] = $value;
786 }
787
788 if ( $wgAllowMicrodataAttributes ) {
789 # itemtype, itemid, itemref don't make sense without itemscope
790 if ( !array_key_exists( 'itemscope', $out ) ) {
791 unset( $out['itemtype'] );
792 unset( $out['itemid'] );
793 unset( $out['itemref'] );
794 }
795 # TODO: Strip itemprop if we aren't descendants of an itemscope or pointed to by an itemref.
796 }
797 return $out;
798 }
799
800 /**
801 * Merge two sets of HTML attributes. Conflicting items in the second set
802 * will override those in the first, except for 'class' attributes which
803 * will be combined (if they're both strings).
804 *
805 * @todo implement merging for other attributes such as style
806 * @param array $a
807 * @param array $b
808 * @return array
809 */
810 static function mergeAttributes( $a, $b ) {
811 $out = array_merge( $a, $b );
812 if ( isset( $a['class'] ) && isset( $b['class'] )
813 && is_string( $a['class'] ) && is_string( $b['class'] )
814 && $a['class'] !== $b['class']
815 ) {
816 $classes = preg_split( '/\s+/', "{$a['class']} {$b['class']}",
817 -1, PREG_SPLIT_NO_EMPTY );
818 $out['class'] = implode( ' ', array_unique( $classes ) );
819 }
820 return $out;
821 }
822
823 /**
824 * Normalize CSS into a format we can easily search for hostile input
825 * - decode character references
826 * - decode escape sequences
827 * - convert characters that IE6 interprets into ascii
828 * - remove comments, unless the entire value is one single comment
829 * @param string $value the css string
830 * @return string normalized css
831 */
832 public static function normalizeCss( $value ) {
833
834 // Decode character references like &#123;
835 $value = Sanitizer::decodeCharReferences( $value );
836
837 // Decode escape sequences and line continuation
838 // See the grammar in the CSS 2 spec, appendix D.
839 // This has to be done AFTER decoding character references.
840 // This means it isn't possible for this function to return
841 // unsanitized escape sequences. It is possible to manufacture
842 // input that contains character references that decode to
843 // escape sequences that decode to character references, but
844 // it's OK for the return value to contain character references
845 // because the caller is supposed to escape those anyway.
846 static $decodeRegex;
847 if ( !$decodeRegex ) {
848 $space = '[\\x20\\t\\r\\n\\f]';
849 $nl = '(?:\\n|\\r\\n|\\r|\\f)';
850 $backslash = '\\\\';
851 $decodeRegex = "/ $backslash
852 (?:
853 ($nl) | # 1. Line continuation
854 ([0-9A-Fa-f]{1,6})$space? | # 2. character number
855 (.) | # 3. backslash cancelling special meaning
856 () | # 4. backslash at end of string
857 )/xu";
858 }
859 $value = preg_replace_callback( $decodeRegex,
860 array( __CLASS__, 'cssDecodeCallback' ), $value );
861
862 // Normalize Halfwidth and Fullwidth Unicode block that IE6 might treat as ascii
863 $value = preg_replace_callback(
864 '/[!-[]-z]/u', // U+FF01 to U+FF5A, excluding U+FF3C (bug 58088)
865 function ( $matches ) {
866 $cp = utf8ToCodepoint( $matches[0] );
867 if ( $cp === false ) {
868 return '';
869 }
870 return chr( $cp - 65248 ); // ASCII range \x21-\x7A
871 },
872 $value
873 );
874
875 // Convert more characters IE6 might treat as ascii
876 // U+0280, U+0274, U+207F, U+029F, U+026A, U+207D, U+208D
877 $value = str_replace(
878 array( 'ʀ', 'ɴ', 'ⁿ', 'ʟ', 'ɪ', '⁽', '₍' ),
879 array( 'r', 'n', 'n', 'l', 'i', '(', '(' ),
880 $value
881 );
882
883 // Let the value through if it's nothing but a single comment, to
884 // allow other functions which may reject it to pass some error
885 // message through.
886 if ( !preg_match( '! ^ \s* /\* [^*\\/]* \*/ \s* $ !x', $value ) ) {
887 // Remove any comments; IE gets token splitting wrong
888 // This must be done AFTER decoding character references and
889 // escape sequences, because those steps can introduce comments
890 // This step cannot introduce character references or escape
891 // sequences, because it replaces comments with spaces rather
892 // than removing them completely.
893 $value = StringUtils::delimiterReplace( '/*', '*/', ' ', $value );
894
895 // Remove anything after a comment-start token, to guard against
896 // incorrect client implementations.
897 $commentPos = strpos( $value, '/*' );
898 if ( $commentPos !== false ) {
899 $value = substr( $value, 0, $commentPos );
900 }
901 }
902
903 // S followed by repeat, iteration, or prolonged sound marks,
904 // which IE will treat as "ss"
905 $value = preg_replace(
906 '/s(?:
907 \xE3\x80\xB1 | # U+3031
908 \xE3\x82\x9D | # U+309D
909 \xE3\x83\xBC | # U+30FC
910 \xE3\x83\xBD | # U+30FD
911 \xEF\xB9\xBC | # U+FE7C
912 \xEF\xB9\xBD | # U+FE7D
913 \xEF\xBD\xB0 # U+FF70
914 )/ix',
915 'ss',
916 $value
917 );
918
919 return $value;
920 }
921
922
923 /**
924 * Pick apart some CSS and check it for forbidden or unsafe structures.
925 * Returns a sanitized string. This sanitized string will have
926 * character references and escape sequences decoded and comments
927 * stripped (unless it is itself one valid comment, in which case the value
928 * will be passed through). If the input is just too evil, only a comment
929 * complaining about evilness will be returned.
930 *
931 * Currently URL references, 'expression', 'tps' are forbidden.
932 *
933 * NOTE: Despite the fact that character references are decoded, the
934 * returned string may contain character references given certain
935 * clever input strings. These character references must
936 * be escaped before the return value is embedded in HTML.
937 *
938 * @param string $value
939 * @return string
940 */
941 static function checkCss( $value ) {
942 $value = self::normalizeCss( $value );
943
944 // Reject problematic keywords and control characters
945 if ( preg_match( '/[\000-\010\013\016-\037\177]/', $value ) ) {
946 return '/* invalid control char */';
947 } elseif ( preg_match(
948 '! expression
949 | filter\s*:
950 | accelerator\s*:
951 | -o-link\s*:
952 | -o-link-source\s*:
953 | -o-replace\s*:
954 | url\s*\(
955 | image\s*\(
956 | image-set\s*\(
957 !ix', $value ) ) {
958 return '/* insecure input */';
959 }
960 return $value;
961 }
962
963 /**
964 * @param array $matches
965 * @return string
966 */
967 static function cssDecodeCallback( $matches ) {
968 if ( $matches[1] !== '' ) {
969 // Line continuation
970 return '';
971 } elseif ( $matches[2] !== '' ) {
972 $char = codepointToUtf8( hexdec( $matches[2] ) );
973 } elseif ( $matches[3] !== '' ) {
974 $char = $matches[3];
975 } else {
976 $char = '\\';
977 }
978 if ( $char == "\n" || $char == '"' || $char == "'" || $char == '\\' ) {
979 // These characters need to be escaped in strings
980 // Clean up the escape sequence to avoid parsing errors by clients
981 return '\\' . dechex( ord( $char ) ) . ' ';
982 } else {
983 // Decode unnecessary escape
984 return $char;
985 }
986 }
987
988 /**
989 * Take a tag soup fragment listing an HTML element's attributes
990 * and normalize it to well-formed XML, discarding unwanted attributes.
991 * Output is safe for further wikitext processing, with escaping of
992 * values that could trigger problems.
993 *
994 * - Normalizes attribute names to lowercase
995 * - Discards attributes not on a whitelist for the given element
996 * - Turns broken or invalid entities into plaintext
997 * - Double-quotes all attribute values
998 * - Attributes without values are given the name as attribute
999 * - Double attributes are discarded
1000 * - Unsafe style attributes are discarded
1001 * - Prepends space if there are attributes.
1002 *
1003 * @param string $text
1004 * @param string $element
1005 * @return string
1006 */
1007 static function fixTagAttributes( $text, $element ) {
1008 if ( trim( $text ) == '' ) {
1009 return '';
1010 }
1011
1012 $decoded = Sanitizer::decodeTagAttributes( $text );
1013 $stripped = Sanitizer::validateTagAttributes( $decoded, $element );
1014
1015 return Sanitizer::safeEncodeTagAttributes( $stripped );
1016 }
1017
1018 /**
1019 * Encode an attribute value for HTML output.
1020 * @param string $text
1021 * @return string HTML-encoded text fragment
1022 */
1023 static function encodeAttribute( $text ) {
1024 $encValue = htmlspecialchars( $text, ENT_QUOTES );
1025
1026 // Whitespace is normalized during attribute decoding,
1027 // so if we've been passed non-spaces we must encode them
1028 // ahead of time or they won't be preserved.
1029 $encValue = strtr( $encValue, array(
1030 "\n" => '&#10;',
1031 "\r" => '&#13;',
1032 "\t" => '&#9;',
1033 ) );
1034
1035 return $encValue;
1036 }
1037
1038 /**
1039 * Encode an attribute value for HTML tags, with extra armoring
1040 * against further wiki processing.
1041 * @param string $text
1042 * @return string HTML-encoded text fragment
1043 */
1044 static function safeEncodeAttribute( $text ) {
1045 $encValue = Sanitizer::encodeAttribute( $text );
1046
1047 # Templates and links may be expanded in later parsing,
1048 # creating invalid or dangerous output. Suppress this.
1049 $encValue = strtr( $encValue, array(
1050 '<' => '&lt;', // This should never happen,
1051 '>' => '&gt;', // we've received invalid input
1052 '"' => '&quot;', // which should have been escaped.
1053 '{' => '&#123;',
1054 '[' => '&#91;',
1055 "''" => '&#39;&#39;',
1056 'ISBN' => '&#73;SBN',
1057 'RFC' => '&#82;FC',
1058 'PMID' => '&#80;MID',
1059 '|' => '&#124;',
1060 '__' => '&#95;_',
1061 ) );
1062
1063 # Stupid hack
1064 $encValue = preg_replace_callback(
1065 '/((?i)' . wfUrlProtocols() . ')/',
1066 array( 'Sanitizer', 'armorLinksCallback' ),
1067 $encValue );
1068 return $encValue;
1069 }
1070
1071 /**
1072 * Given a value, escape it so that it can be used in an id attribute and
1073 * return it. This will use HTML5 validation if $wgExperimentalHtmlIds is
1074 * true, allowing anything but ASCII whitespace. Otherwise it will use
1075 * HTML 4 rules, which means a narrow subset of ASCII, with bad characters
1076 * escaped with lots of dots.
1077 *
1078 * To ensure we don't have to bother escaping anything, we also strip ', ",
1079 * & even if $wgExperimentalIds is true. TODO: Is this the best tactic?
1080 * We also strip # because it upsets IE, and % because it could be
1081 * ambiguous if it's part of something that looks like a percent escape
1082 * (which don't work reliably in fragments cross-browser).
1083 *
1084 * @see http://www.w3.org/TR/html401/types.html#type-name Valid characters
1085 * in the id and name attributes
1086 * @see http://www.w3.org/TR/html401/struct/links.html#h-12.2.3 Anchors with
1087 * the id attribute
1088 * @see http://www.whatwg.org/html/elements.html#the-id-attribute
1089 * HTML5 definition of id attribute
1090 *
1091 * @param string $id Id to escape
1092 * @param string|array $options String or array of strings (default is array()):
1093 * 'noninitial': This is a non-initial fragment of an id, not a full id,
1094 * so don't pay attention if the first character isn't valid at the
1095 * beginning of an id. Only matters if $wgExperimentalHtmlIds is
1096 * false.
1097 * 'legacy': Behave the way the old HTML 4-based ID escaping worked even
1098 * if $wgExperimentalHtmlIds is used, so we can generate extra
1099 * anchors and links won't break.
1100 * @return string
1101 */
1102 static function escapeId( $id, $options = array() ) {
1103 global $wgExperimentalHtmlIds;
1104 $options = (array)$options;
1105
1106 $id = Sanitizer::decodeCharReferences( $id );
1107
1108 if ( $wgExperimentalHtmlIds && !in_array( 'legacy', $options ) ) {
1109 $id = preg_replace( '/[ \t\n\r\f_\'"&#%]+/', '_', $id );
1110 $id = trim( $id, '_' );
1111 if ( $id === '' ) {
1112 // Must have been all whitespace to start with.
1113 return '_';
1114 } else {
1115 return $id;
1116 }
1117 }
1118
1119 // HTML4-style escaping
1120 static $replace = array(
1121 '%3A' => ':',
1122 '%' => '.'
1123 );
1124
1125 $id = urlencode( strtr( $id, ' ', '_' ) );
1126 $id = str_replace( array_keys( $replace ), array_values( $replace ), $id );
1127
1128 if ( !preg_match( '/^[a-zA-Z]/', $id ) && !in_array( 'noninitial', $options ) ) {
1129 // Initial character must be a letter!
1130 $id = "x$id";
1131 }
1132 return $id;
1133 }
1134
1135 /**
1136 * Given a value, escape it so that it can be used as a CSS class and
1137 * return it.
1138 *
1139 * @todo For extra validity, input should be validated UTF-8.
1140 *
1141 * @see http://www.w3.org/TR/CSS21/syndata.html Valid characters/format
1142 *
1143 * @param string $class
1144 * @return string
1145 */
1146 static function escapeClass( $class ) {
1147 // Convert ugly stuff to underscores and kill underscores in ugly places
1148 return rtrim( preg_replace(
1149 array( '/(^[0-9\\-])|[\\x00-\\x20!"#$%&\'()*+,.\\/:;<=>?@[\\]^`{|}~]|\\xC2\\xA0/', '/_+/' ),
1150 '_',
1151 $class ), '_' );
1152 }
1153
1154 /**
1155 * Given HTML input, escape with htmlspecialchars but un-escape entities.
1156 * This allows (generally harmless) entities like &#160; to survive.
1157 *
1158 * @param string $html HTML to escape
1159 * @return string Escaped input
1160 */
1161 static function escapeHtmlAllowEntities( $html ) {
1162 $html = Sanitizer::decodeCharReferences( $html );
1163 # It seems wise to escape ' as well as ", as a matter of course. Can't
1164 # hurt.
1165 $html = htmlspecialchars( $html, ENT_QUOTES );
1166 return $html;
1167 }
1168
1169 /**
1170 * Regex replace callback for armoring links against further processing.
1171 * @param array $matches
1172 * @return string
1173 */
1174 private static function armorLinksCallback( $matches ) {
1175 return str_replace( ':', '&#58;', $matches[1] );
1176 }
1177
1178 /**
1179 * Return an associative array of attribute names and values from
1180 * a partial tag string. Attribute names are forces to lowercase,
1181 * character references are decoded to UTF-8 text.
1182 *
1183 * @param string $text
1184 * @return array
1185 */
1186 public static function decodeTagAttributes( $text ) {
1187 if ( trim( $text ) == '' ) {
1188 return array();
1189 }
1190
1191 $attribs = array();
1192 $pairs = array();
1193 if ( !preg_match_all(
1194 self::getAttribsRegex(),
1195 $text,
1196 $pairs,
1197 PREG_SET_ORDER ) ) {
1198 return $attribs;
1199 }
1200
1201 foreach ( $pairs as $set ) {
1202 $attribute = strtolower( $set[1] );
1203 $value = Sanitizer::getTagAttributeCallback( $set );
1204
1205 // Normalize whitespace
1206 $value = preg_replace( '/[\t\r\n ]+/', ' ', $value );
1207 $value = trim( $value );
1208
1209 // Decode character references
1210 $attribs[$attribute] = Sanitizer::decodeCharReferences( $value );
1211 }
1212 return $attribs;
1213 }
1214
1215 /**
1216 * Build a partial tag string from an associative array of attribute
1217 * names and values as returned by decodeTagAttributes.
1218 *
1219 * @param array $assoc_array
1220 * @return string
1221 */
1222 public static function safeEncodeTagAttributes( $assoc_array ) {
1223 $attribs = array();
1224 foreach ( $assoc_array as $attribute => $value ) {
1225 $encAttribute = htmlspecialchars( $attribute );
1226 $encValue = Sanitizer::safeEncodeAttribute( $value );
1227
1228 $attribs[] = "$encAttribute=\"$encValue\"";
1229 }
1230 return count( $attribs ) ? ' ' . implode( ' ', $attribs ) : '';
1231 }
1232
1233 /**
1234 * Pick the appropriate attribute value from a match set from the
1235 * attribs regex matches.
1236 *
1237 * @param array $set
1238 * @throws MWException When tag conditions are not met.
1239 * @return string
1240 */
1241 private static function getTagAttributeCallback( $set ) {
1242 if ( isset( $set[6] ) ) {
1243 # Illegal #XXXXXX color with no quotes.
1244 return $set[6];
1245 } elseif ( isset( $set[5] ) ) {
1246 # No quotes.
1247 return $set[5];
1248 } elseif ( isset( $set[4] ) ) {
1249 # Single-quoted
1250 return $set[4];
1251 } elseif ( isset( $set[3] ) ) {
1252 # Double-quoted
1253 return $set[3];
1254 } elseif ( !isset( $set[2] ) ) {
1255 # In XHTML, attributes must have a value.
1256 # For 'reduced' form, return explicitly the attribute name here.
1257 return $set[1];
1258 } else {
1259 throw new MWException( "Tag conditions not met. This should never happen and is a bug." );
1260 }
1261 }
1262
1263 /**
1264 * @param string $text
1265 * @return string
1266 */
1267 private static function normalizeWhitespace( $text ) {
1268 return preg_replace(
1269 '/\r\n|[\x20\x0d\x0a\x09]/',
1270 ' ',
1271 $text );
1272 }
1273
1274 /**
1275 * Normalizes whitespace in a section name, such as might be returned
1276 * by Parser::stripSectionName(), for use in the id's that are used for
1277 * section links.
1278 *
1279 * @param string $section
1280 * @return string
1281 */
1282 static function normalizeSectionNameWhitespace( $section ) {
1283 return trim( preg_replace( '/[ _]+/', ' ', $section ) );
1284 }
1285
1286 /**
1287 * Ensure that any entities and character references are legal
1288 * for XML and XHTML specifically. Any stray bits will be
1289 * &amp;-escaped to result in a valid text fragment.
1290 *
1291 * a. named char refs can only be &lt; &gt; &amp; &quot;, others are
1292 * numericized (this way we're well-formed even without a DTD)
1293 * b. any numeric char refs must be legal chars, not invalid or forbidden
1294 * c. use lower cased "&#x", not "&#X"
1295 * d. fix or reject non-valid attributes
1296 *
1297 * @param string $text
1298 * @return string
1299 * @private
1300 */
1301 static function normalizeCharReferences( $text ) {
1302 return preg_replace_callback(
1303 self::CHAR_REFS_REGEX,
1304 array( 'Sanitizer', 'normalizeCharReferencesCallback' ),
1305 $text );
1306 }
1307
1308 /**
1309 * @param string $matches
1310 * @return string
1311 */
1312 static function normalizeCharReferencesCallback( $matches ) {
1313 $ret = null;
1314 if ( $matches[1] != '' ) {
1315 $ret = Sanitizer::normalizeEntity( $matches[1] );
1316 } elseif ( $matches[2] != '' ) {
1317 $ret = Sanitizer::decCharReference( $matches[2] );
1318 } elseif ( $matches[3] != '' ) {
1319 $ret = Sanitizer::hexCharReference( $matches[3] );
1320 }
1321 if ( is_null( $ret ) ) {
1322 return htmlspecialchars( $matches[0] );
1323 } else {
1324 return $ret;
1325 }
1326 }
1327
1328 /**
1329 * If the named entity is defined in the HTML 4.0/XHTML 1.0 DTD,
1330 * return the equivalent numeric entity reference (except for the core &lt;
1331 * &gt; &amp; &quot;). If the entity is a MediaWiki-specific alias, returns
1332 * the HTML equivalent. Otherwise, returns HTML-escaped text of
1333 * pseudo-entity source (eg &amp;foo;)
1334 *
1335 * @param string $name
1336 * @return string
1337 */
1338 static function normalizeEntity( $name ) {
1339 if ( isset( self::$htmlEntityAliases[$name] ) ) {
1340 return '&' . self::$htmlEntityAliases[$name] . ';';
1341 } elseif ( in_array( $name, array( 'lt', 'gt', 'amp', 'quot' ) ) ) {
1342 return "&$name;";
1343 } elseif ( isset( self::$htmlEntities[$name] ) ) {
1344 return '&#' . self::$htmlEntities[$name] . ';';
1345 } else {
1346 return "&amp;$name;";
1347 }
1348 }
1349
1350 /**
1351 * @param int $codepoint
1352 * @return null|string
1353 */
1354 static function decCharReference( $codepoint ) {
1355 $point = intval( $codepoint );
1356 if ( Sanitizer::validateCodepoint( $point ) ) {
1357 return sprintf( '&#%d;', $point );
1358 } else {
1359 return null;
1360 }
1361 }
1362
1363 /**
1364 * @param int $codepoint
1365 * @return null|string
1366 */
1367 static function hexCharReference( $codepoint ) {
1368 $point = hexdec( $codepoint );
1369 if ( Sanitizer::validateCodepoint( $point ) ) {
1370 return sprintf( '&#x%x;', $point );
1371 } else {
1372 return null;
1373 }
1374 }
1375
1376 /**
1377 * Returns true if a given Unicode codepoint is a valid character in XML.
1378 * @param int $codepoint
1379 * @return bool
1380 */
1381 private static function validateCodepoint( $codepoint ) {
1382 return $codepoint == 0x09
1383 || $codepoint == 0x0a
1384 || $codepoint == 0x0d
1385 || ( $codepoint >= 0x20 && $codepoint <= 0xd7ff )
1386 || ( $codepoint >= 0xe000 && $codepoint <= 0xfffd )
1387 || ( $codepoint >= 0x10000 && $codepoint <= 0x10ffff );
1388 }
1389
1390 /**
1391 * Decode any character references, numeric or named entities,
1392 * in the text and return a UTF-8 string.
1393 *
1394 * @param string $text
1395 * @return string
1396 */
1397 public static function decodeCharReferences( $text ) {
1398 return preg_replace_callback(
1399 self::CHAR_REFS_REGEX,
1400 array( 'Sanitizer', 'decodeCharReferencesCallback' ),
1401 $text );
1402 }
1403
1404 /**
1405 * Decode any character references, numeric or named entities,
1406 * in the next and normalize the resulting string. (bug 14952)
1407 *
1408 * This is useful for page titles, not for text to be displayed,
1409 * MediaWiki allows HTML entities to escape normalization as a feature.
1410 *
1411 * @param string $text Already normalized, containing entities
1412 * @return string Still normalized, without entities
1413 */
1414 public static function decodeCharReferencesAndNormalize( $text ) {
1415 global $wgContLang;
1416 $text = preg_replace_callback(
1417 self::CHAR_REFS_REGEX,
1418 array( 'Sanitizer', 'decodeCharReferencesCallback' ),
1419 $text, /* limit */ -1, $count );
1420
1421 if ( $count ) {
1422 return $wgContLang->normalize( $text );
1423 } else {
1424 return $text;
1425 }
1426 }
1427
1428 /**
1429 * @param string $matches
1430 * @return string
1431 */
1432 static function decodeCharReferencesCallback( $matches ) {
1433 if ( $matches[1] != '' ) {
1434 return Sanitizer::decodeEntity( $matches[1] );
1435 } elseif ( $matches[2] != '' ) {
1436 return Sanitizer::decodeChar( intval( $matches[2] ) );
1437 } elseif ( $matches[3] != '' ) {
1438 return Sanitizer::decodeChar( hexdec( $matches[3] ) );
1439 }
1440 # Last case should be an ampersand by itself
1441 return $matches[0];
1442 }
1443
1444 /**
1445 * Return UTF-8 string for a codepoint if that is a valid
1446 * character reference, otherwise U+FFFD REPLACEMENT CHARACTER.
1447 * @param int $codepoint
1448 * @return string
1449 * @private
1450 */
1451 static function decodeChar( $codepoint ) {
1452 if ( Sanitizer::validateCodepoint( $codepoint ) ) {
1453 return codepointToUtf8( $codepoint );
1454 } else {
1455 return UTF8_REPLACEMENT;
1456 }
1457 }
1458
1459 /**
1460 * If the named entity is defined in the HTML 4.0/XHTML 1.0 DTD,
1461 * return the UTF-8 encoding of that character. Otherwise, returns
1462 * pseudo-entity source (eg "&foo;")
1463 *
1464 * @param string $name
1465 * @return string
1466 */
1467 static function decodeEntity( $name ) {
1468 if ( isset( self::$htmlEntityAliases[$name] ) ) {
1469 $name = self::$htmlEntityAliases[$name];
1470 }
1471 if ( isset( self::$htmlEntities[$name] ) ) {
1472 return codepointToUtf8( self::$htmlEntities[$name] );
1473 } else {
1474 return "&$name;";
1475 }
1476 }
1477
1478 /**
1479 * Fetch the whitelist of acceptable attributes for a given element name.
1480 *
1481 * @param string $element
1482 * @return array
1483 */
1484 static function attributeWhitelist( $element ) {
1485 $list = Sanitizer::setupAttributeWhitelist();
1486 return isset( $list[$element] )
1487 ? $list[$element]
1488 : array();
1489 }
1490
1491 /**
1492 * Foreach array key (an allowed HTML element), return an array
1493 * of allowed attributes
1494 * @return array
1495 */
1496 static function setupAttributeWhitelist() {
1497 global $wgAllowRdfaAttributes, $wgAllowMicrodataAttributes;
1498 static $whitelist, $staticInitialised;
1499
1500 $globalContext = implode( '-', compact( 'wgAllowRdfaAttributes', 'wgAllowMicrodataAttributes' ) );
1501
1502 if ( $whitelist !== null && $staticInitialised == $globalContext ) {
1503 return $whitelist;
1504 }
1505
1506 $common = array(
1507 # HTML
1508 'id',
1509 'class',
1510 'style',
1511 'lang',
1512 'dir',
1513 'title',
1514
1515 # WAI-ARIA
1516 'role',
1517 );
1518
1519 if ( $wgAllowRdfaAttributes ) {
1520 # RDFa attributes as specified in section 9 of
1521 # http://www.w3.org/TR/2008/REC-rdfa-syntax-20081014
1522 $common = array_merge( $common, array(
1523 'about', 'property', 'resource', 'datatype', 'typeof',
1524 ) );
1525 }
1526
1527 if ( $wgAllowMicrodataAttributes ) {
1528 # add HTML5 microdata tags as specified by
1529 # http://www.whatwg.org/html/microdata.html#the-microdata-model
1530 $common = array_merge( $common, array(
1531 'itemid', 'itemprop', 'itemref', 'itemscope', 'itemtype'
1532 ) );
1533 }
1534
1535 $block = array_merge( $common, array( 'align' ) );
1536 $tablealign = array( 'align', 'valign' );
1537 $tablecell = array(
1538 'abbr',
1539 'axis',
1540 'headers',
1541 'scope',
1542 'rowspan',
1543 'colspan',
1544 'nowrap', # deprecated
1545 'width', # deprecated
1546 'height', # deprecated
1547 'bgcolor', # deprecated
1548 );
1549
1550 # Numbers refer to sections in HTML 4.01 standard describing the element.
1551 # See: http://www.w3.org/TR/html4/
1552 $whitelist = array(
1553 # 7.5.4
1554 'div' => $block,
1555 'center' => $common, # deprecated
1556 'span' => $common,
1557
1558 # 7.5.5
1559 'h1' => $block,
1560 'h2' => $block,
1561 'h3' => $block,
1562 'h4' => $block,
1563 'h5' => $block,
1564 'h6' => $block,
1565
1566 # 7.5.6
1567 # address
1568
1569 # 8.2.4
1570 'bdo' => $common,
1571
1572 # 9.2.1
1573 'em' => $common,
1574 'strong' => $common,
1575 'cite' => $common,
1576 'dfn' => $common,
1577 'code' => $common,
1578 'samp' => $common,
1579 'kbd' => $common,
1580 'var' => $common,
1581 'abbr' => $common,
1582 # acronym
1583
1584 # 9.2.2
1585 'blockquote' => array_merge( $common, array( 'cite' ) ),
1586 'q' => array_merge( $common, array( 'cite' ) ),
1587
1588 # 9.2.3
1589 'sub' => $common,
1590 'sup' => $common,
1591
1592 # 9.3.1
1593 'p' => $block,
1594
1595 # 9.3.2
1596 'br' => array_merge( $common, array( 'clear' ) ),
1597
1598 # http://www.whatwg.org/html/text-level-semantics.html#the-wbr-element
1599 'wbr' => $common,
1600
1601 # 9.3.4
1602 'pre' => array_merge( $common, array( 'width' ) ),
1603
1604 # 9.4
1605 'ins' => array_merge( $common, array( 'cite', 'datetime' ) ),
1606 'del' => array_merge( $common, array( 'cite', 'datetime' ) ),
1607
1608 # 10.2
1609 'ul' => array_merge( $common, array( 'type' ) ),
1610 'ol' => array_merge( $common, array( 'type', 'start' ) ),
1611 'li' => array_merge( $common, array( 'type', 'value' ) ),
1612
1613 # 10.3
1614 'dl' => $common,
1615 'dd' => $common,
1616 'dt' => $common,
1617
1618 # 11.2.1
1619 'table' => array_merge( $common,
1620 array( 'summary', 'width', 'border', 'frame',
1621 'rules', 'cellspacing', 'cellpadding',
1622 'align', 'bgcolor',
1623 ) ),
1624
1625 # 11.2.2
1626 'caption' => $block,
1627
1628 # 11.2.3
1629 'thead' => $common,
1630 'tfoot' => $common,
1631 'tbody' => $common,
1632
1633 # 11.2.4
1634 'colgroup' => array_merge( $common, array( 'span' ) ),
1635 'col' => array_merge( $common, array( 'span' ) ),
1636
1637 # 11.2.5
1638 'tr' => array_merge( $common, array( 'bgcolor' ), $tablealign ),
1639
1640 # 11.2.6
1641 'td' => array_merge( $common, $tablecell, $tablealign ),
1642 'th' => array_merge( $common, $tablecell, $tablealign ),
1643
1644 # 12.2
1645 # NOTE: <a> is not allowed directly, but the attrib
1646 # whitelist is used from the Parser object
1647 'a' => array_merge( $common, array( 'href', 'rel', 'rev' ) ), # rel/rev esp. for RDFa
1648
1649 # 13.2
1650 # Not usually allowed, but may be used for extension-style hooks
1651 # such as <math> when it is rasterized, or if $wgAllowImageTag is
1652 # true
1653 'img' => array_merge( $common, array( 'alt', 'src', 'width', 'height' ) ),
1654
1655 # 15.2.1
1656 'tt' => $common,
1657 'b' => $common,
1658 'i' => $common,
1659 'big' => $common,
1660 'small' => $common,
1661 'strike' => $common,
1662 's' => $common,
1663 'u' => $common,
1664
1665 # 15.2.2
1666 'font' => array_merge( $common, array( 'size', 'color', 'face' ) ),
1667 # basefont
1668
1669 # 15.3
1670 'hr' => array_merge( $common, array( 'width' ) ),
1671
1672 # HTML Ruby annotation text module, simple ruby only.
1673 # http://www.whatwg.org/html/text-level-semantics.html#the-ruby-element
1674 'ruby' => $common,
1675 # rbc
1676 'rb' => $common,
1677 'rp' => $common,
1678 'rt' => $common, #array_merge( $common, array( 'rbspan' ) ),
1679 'rtc' => $common,
1680
1681 # MathML root element, where used for extensions
1682 # 'title' may not be 100% valid here; it's XHTML
1683 # http://www.w3.org/TR/REC-MathML/
1684 'math' => array( 'class', 'style', 'id', 'title' ),
1685
1686 # HTML 5 section 4.6
1687 'bdi' => $common,
1688
1689 # HTML5 elements, defined by:
1690 # http://www.whatwg.org/html/
1691 'data' => array_merge( $common, array( 'value' ) ),
1692 'time' => array_merge( $common, array( 'datetime' ) ),
1693 'mark' => $common,
1694
1695 // meta and link are only permitted by removeHTMLtags when Microdata
1696 // is enabled so we don't bother adding a conditional to hide these
1697 // Also meta and link are only valid in WikiText as Microdata elements
1698 // (ie: validateTag rejects tags missing the attributes needed for Microdata)
1699 // So we don't bother including $common attributes that have no purpose.
1700 'meta' => array( 'itemprop', 'content' ),
1701 'link' => array( 'itemprop', 'href' ),
1702 );
1703
1704 $staticInitialised = $globalContext;
1705
1706 return $whitelist;
1707 }
1708
1709 /**
1710 * Take a fragment of (potentially invalid) HTML and return
1711 * a version with any tags removed, encoded as plain text.
1712 *
1713 * Warning: this return value must be further escaped for literal
1714 * inclusion in HTML output as of 1.10!
1715 *
1716 * @param string $text HTML fragment
1717 * @return string
1718 */
1719 static function stripAllTags( $text ) {
1720 # Actual <tags>
1721 $text = StringUtils::delimiterReplace( '<', '>', '', $text );
1722
1723 # Normalize &entities and whitespace
1724 $text = self::decodeCharReferences( $text );
1725 $text = self::normalizeWhitespace( $text );
1726
1727 return $text;
1728 }
1729
1730 /**
1731 * Hack up a private DOCTYPE with HTML's standard entity declarations.
1732 * PHP 4 seemed to know these if you gave it an HTML doctype, but
1733 * PHP 5.1 doesn't.
1734 *
1735 * Use for passing XHTML fragments to PHP's XML parsing functions
1736 *
1737 * @return string
1738 */
1739 static function hackDocType() {
1740 $out = "<!DOCTYPE html [\n";
1741 foreach ( self::$htmlEntities as $entity => $codepoint ) {
1742 $out .= "<!ENTITY $entity \"&#$codepoint;\">";
1743 }
1744 $out .= "]>\n";
1745 return $out;
1746 }
1747
1748 /**
1749 * @param string $url
1750 * @return mixed|string
1751 */
1752 static function cleanUrl( $url ) {
1753 # Normalize any HTML entities in input. They will be
1754 # re-escaped by makeExternalLink().
1755 $url = Sanitizer::decodeCharReferences( $url );
1756
1757 # Escape any control characters introduced by the above step
1758 $url = preg_replace_callback( '/[\][<>"\\x00-\\x20\\x7F\|]/',
1759 array( __CLASS__, 'cleanUrlCallback' ), $url );
1760
1761 # Validate hostname portion
1762 $matches = array();
1763 if ( preg_match( '!^([^:]+:)(//[^/]+)?(.*)$!iD', $url, $matches ) ) {
1764 list( /* $whole */, $protocol, $host, $rest ) = $matches;
1765
1766 // Characters that will be ignored in IDNs.
1767 // http://tools.ietf.org/html/3454#section-3.1
1768 // Strip them before further processing so blacklists and such work.
1769 $strip = "/
1770 \\s| # general whitespace
1771 \xc2\xad| # 00ad SOFT HYPHEN
1772 \xe1\xa0\x86| # 1806 MONGOLIAN TODO SOFT HYPHEN
1773 \xe2\x80\x8b| # 200b ZERO WIDTH SPACE
1774 \xe2\x81\xa0| # 2060 WORD JOINER
1775 \xef\xbb\xbf| # feff ZERO WIDTH NO-BREAK SPACE
1776 \xcd\x8f| # 034f COMBINING GRAPHEME JOINER
1777 \xe1\xa0\x8b| # 180b MONGOLIAN FREE VARIATION SELECTOR ONE
1778 \xe1\xa0\x8c| # 180c MONGOLIAN FREE VARIATION SELECTOR TWO
1779 \xe1\xa0\x8d| # 180d MONGOLIAN FREE VARIATION SELECTOR THREE
1780 \xe2\x80\x8c| # 200c ZERO WIDTH NON-JOINER
1781 \xe2\x80\x8d| # 200d ZERO WIDTH JOINER
1782 [\xef\xb8\x80-\xef\xb8\x8f] # fe00-fe0f VARIATION SELECTOR-1-16
1783 /xuD";
1784
1785 $host = preg_replace( $strip, '', $host );
1786
1787 // @todo FIXME: Validate hostnames here
1788
1789 return $protocol . $host . $rest;
1790 } else {
1791 return $url;
1792 }
1793 }
1794
1795 /**
1796 * @param array $matches
1797 * @return string
1798 */
1799 static function cleanUrlCallback( $matches ) {
1800 return urlencode( $matches[0] );
1801 }
1802
1803 /**
1804 * Does a string look like an e-mail address?
1805 *
1806 * This validates an email address using an HTML5 specification found at:
1807 * http://www.whatwg.org/html/states-of-the-type-attribute.html#valid-e-mail-address
1808 * Which as of 2011-01-24 says:
1809 *
1810 * A valid e-mail address is a string that matches the ABNF production
1811 * 1*( atext / "." ) "@" ldh-str *( "." ldh-str ) where atext is defined
1812 * in RFC 5322 section 3.2.3, and ldh-str is defined in RFC 1034 section
1813 * 3.5.
1814 *
1815 * This function is an implementation of the specification as requested in
1816 * bug 22449.
1817 *
1818 * Client-side forms will use the same standard validation rules via JS or
1819 * HTML 5 validation; additional restrictions can be enforced server-side
1820 * by extensions via the 'isValidEmailAddr' hook.
1821 *
1822 * Note that this validation doesn't 100% match RFC 2822, but is believed
1823 * to be liberal enough for wide use. Some invalid addresses will still
1824 * pass validation here.
1825 *
1826 * @since 1.18
1827 *
1828 * @param string $addr E-mail address
1829 * @return bool
1830 */
1831 public static function validateEmail( $addr ) {
1832 $result = null;
1833 if ( !Hooks::run( 'isValidEmailAddr', array( $addr, &$result ) ) ) {
1834 return $result;
1835 }
1836
1837 // Please note strings below are enclosed in brackets [], this make the
1838 // hyphen "-" a range indicator. Hence it is double backslashed below.
1839 // See bug 26948
1840 $rfc5322_atext = "a-z0-9!#$%&'*+\\-\/=?^_`{|}~";
1841 $rfc1034_ldh_str = "a-z0-9\\-";
1842
1843 $html5_email_regexp = "/
1844 ^ # start of string
1845 [$rfc5322_atext\\.]+ # user part which is liberal :p
1846 @ # 'apostrophe'
1847 [$rfc1034_ldh_str]+ # First domain part
1848 (\\.[$rfc1034_ldh_str]+)* # Following part prefixed with a dot
1849 $ # End of string
1850 /ix"; // case Insensitive, eXtended
1851
1852 return (bool)preg_match( $html5_email_regexp, $addr );
1853 }
1854 }