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