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