(Bug 19725) Do not include suppressed edits in the "View X deleted edits" message...
[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, // New in XHTML & HTML 5; avoid in output for compatibility with IE.
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 /**
796 * @param $matches array
797 * @return String
798 */
799 static function cssDecodeCallback( $matches ) {
800 if ( $matches[1] !== '' ) {
801 // Line continuation
802 return '';
803 } elseif ( $matches[2] !== '' ) {
804 $char = codepointToUtf8( hexdec( $matches[2] ) );
805 } elseif ( $matches[3] !== '' ) {
806 $char = $matches[3];
807 } else {
808 $char = '\\';
809 }
810 if ( $char == "\n" || $char == '"' || $char == "'" || $char == '\\' ) {
811 // These characters need to be escaped in strings
812 // Clean up the escape sequence to avoid parsing errors by clients
813 return '\\' . dechex( ord( $char ) ) . ' ';
814 } else {
815 // Decode unnecessary escape
816 return $char;
817 }
818 }
819
820 /**
821 * Take a tag soup fragment listing an HTML element's attributes
822 * and normalize it to well-formed XML, discarding unwanted attributes.
823 * Output is safe for further wikitext processing, with escaping of
824 * values that could trigger problems.
825 *
826 * - Normalizes attribute names to lowercase
827 * - Discards attributes not on a whitelist for the given element
828 * - Turns broken or invalid entities into plaintext
829 * - Double-quotes all attribute values
830 * - Attributes without values are given the name as attribute
831 * - Double attributes are discarded
832 * - Unsafe style attributes are discarded
833 * - Prepends space if there are attributes.
834 *
835 * @param $text String
836 * @param $element String
837 * @return String
838 */
839 static function fixTagAttributes( $text, $element ) {
840 if( trim( $text ) == '' ) {
841 return '';
842 }
843
844 $stripped = Sanitizer::validateTagAttributes(
845 Sanitizer::decodeTagAttributes( $text ), $element );
846
847 $attribs = array();
848 foreach( $stripped as $attribute => $value ) {
849 $encAttribute = htmlspecialchars( $attribute );
850 $encValue = Sanitizer::safeEncodeAttribute( $value );
851
852 $attribs[] = "$encAttribute=\"$encValue\"";
853 }
854 return count( $attribs ) ? ' ' . implode( ' ', $attribs ) : '';
855 }
856
857 /**
858 * Encode an attribute value for HTML output.
859 * @param $text String
860 * @return HTML-encoded text fragment
861 */
862 static function encodeAttribute( $text ) {
863 $encValue = htmlspecialchars( $text, ENT_QUOTES );
864
865 // Whitespace is normalized during attribute decoding,
866 // so if we've been passed non-spaces we must encode them
867 // ahead of time or they won't be preserved.
868 $encValue = strtr( $encValue, array(
869 "\n" => '&#10;',
870 "\r" => '&#13;',
871 "\t" => '&#9;',
872 ) );
873
874 return $encValue;
875 }
876
877 /**
878 * Encode an attribute value for HTML tags, with extra armoring
879 * against further wiki processing.
880 * @param $text String
881 * @return HTML-encoded text fragment
882 */
883 static function safeEncodeAttribute( $text ) {
884 $encValue = Sanitizer::encodeAttribute( $text );
885
886 # Templates and links may be expanded in later parsing,
887 # creating invalid or dangerous output. Suppress this.
888 $encValue = strtr( $encValue, array(
889 '<' => '&lt;', // This should never happen,
890 '>' => '&gt;', // we've received invalid input
891 '"' => '&quot;', // which should have been escaped.
892 '{' => '&#123;',
893 '[' => '&#91;',
894 "''" => '&#39;&#39;',
895 'ISBN' => '&#73;SBN',
896 'RFC' => '&#82;FC',
897 'PMID' => '&#80;MID',
898 '|' => '&#124;',
899 '__' => '&#95;_',
900 ) );
901
902 # Stupid hack
903 $encValue = preg_replace_callback(
904 '/(' . wfUrlProtocols() . ')/',
905 array( 'Sanitizer', 'armorLinksCallback' ),
906 $encValue );
907 return $encValue;
908 }
909
910 /**
911 * Given a value, escape it so that it can be used in an id attribute and
912 * return it. This will use HTML5 validation if $wgExperimentalHtmlIds is
913 * true, allowing anything but ASCII whitespace. Otherwise it will use
914 * HTML 4 rules, which means a narrow subset of ASCII, with bad characters
915 * escaped with lots of dots.
916 *
917 * To ensure we don't have to bother escaping anything, we also strip ', ",
918 * & even if $wgExperimentalIds is true. TODO: Is this the best tactic?
919 * We also strip # because it upsets IE, and % because it could be
920 * ambiguous if it's part of something that looks like a percent escape
921 * (which don't work reliably in fragments cross-browser).
922 *
923 * @see http://www.w3.org/TR/html401/types.html#type-name Valid characters
924 * in the id and
925 * name attributes
926 * @see http://www.w3.org/TR/html401/struct/links.html#h-12.2.3 Anchors with the id attribute
927 * @see http://www.whatwg.org/specs/web-apps/current-work/multipage/elements.html#the-id-attribute
928 * HTML5 definition of id attribute
929 *
930 * @param $id String: id to escape
931 * @param $options Mixed: string or array of strings (default is array()):
932 * 'noninitial': This is a non-initial fragment of an id, not a full id,
933 * so don't pay attention if the first character isn't valid at the
934 * beginning of an id. Only matters if $wgExperimentalHtmlIds is
935 * false.
936 * 'legacy': Behave the way the old HTML 4-based ID escaping worked even
937 * if $wgExperimentalHtmlIds is used, so we can generate extra
938 * anchors and links won't break.
939 * @return String
940 */
941 static function escapeId( $id, $options = array() ) {
942 global $wgHtml5, $wgExperimentalHtmlIds;
943 $options = (array)$options;
944
945 if ( $wgHtml5 && $wgExperimentalHtmlIds && !in_array( 'legacy', $options ) ) {
946 $id = Sanitizer::decodeCharReferences( $id );
947 $id = preg_replace( '/[ \t\n\r\f_\'"&#%]+/', '_', $id );
948 $id = trim( $id, '_' );
949 if ( $id === '' ) {
950 # Must have been all whitespace to start with.
951 return '_';
952 } else {
953 return $id;
954 }
955 }
956
957 # HTML4-style escaping
958 static $replace = array(
959 '%3A' => ':',
960 '%' => '.'
961 );
962
963 $id = urlencode( Sanitizer::decodeCharReferences( strtr( $id, ' ', '_' ) ) );
964 $id = str_replace( array_keys( $replace ), array_values( $replace ), $id );
965
966 if ( !preg_match( '/^[a-zA-Z]/', $id )
967 && !in_array( 'noninitial', $options ) ) {
968 // Initial character must be a letter!
969 $id = "x$id";
970 }
971 return $id;
972 }
973
974 /**
975 * Given a value, escape it so that it can be used as a CSS class and
976 * return it.
977 *
978 * @todo For extra validity, input should be validated UTF-8.
979 *
980 * @see http://www.w3.org/TR/CSS21/syndata.html Valid characters/format
981 *
982 * @param $class String
983 * @return String
984 */
985 static function escapeClass( $class ) {
986 // Convert ugly stuff to underscores and kill underscores in ugly places
987 return rtrim(preg_replace(
988 array('/(^[0-9\\-])|[\\x00-\\x20!"#$%&\'()*+,.\\/:;<=>?@[\\]^`{|}~]|\\xC2\\xA0/','/_+/'),
989 '_',
990 $class ), '_');
991 }
992
993 /**
994 * Given HTML input, escape with htmlspecialchars but un-escape entites.
995 * This allows (generally harmless) entities like &#160; to survive.
996 *
997 * @param $html String to escape
998 * @return String: escaped input
999 */
1000 static function escapeHtmlAllowEntities( $html ) {
1001 $html = Sanitizer::decodeCharReferences( $html );
1002 # It seems wise to escape ' as well as ", as a matter of course. Can't
1003 # hurt.
1004 $html = htmlspecialchars( $html, ENT_QUOTES );
1005 return $html;
1006 }
1007
1008 /**
1009 * Regex replace callback for armoring links against further processing.
1010 * @param $matches Array
1011 * @return string
1012 */
1013 private static function armorLinksCallback( $matches ) {
1014 return str_replace( ':', '&#58;', $matches[1] );
1015 }
1016
1017 /**
1018 * Return an associative array of attribute names and values from
1019 * a partial tag string. Attribute names are forces to lowercase,
1020 * character references are decoded to UTF-8 text.
1021 *
1022 * @param $text String
1023 * @return Array
1024 */
1025 public static function decodeTagAttributes( $text ) {
1026 if( trim( $text ) == '' ) {
1027 return array();
1028 }
1029
1030 $attribs = array();
1031 $pairs = array();
1032 if( !preg_match_all(
1033 self::getAttribsRegex(),
1034 $text,
1035 $pairs,
1036 PREG_SET_ORDER ) ) {
1037 return $attribs;
1038 }
1039
1040 foreach( $pairs as $set ) {
1041 $attribute = strtolower( $set[1] );
1042 $value = Sanitizer::getTagAttributeCallback( $set );
1043
1044 // Normalize whitespace
1045 $value = preg_replace( '/[\t\r\n ]+/', ' ', $value );
1046 $value = trim( $value );
1047
1048 // Decode character references
1049 $attribs[$attribute] = Sanitizer::decodeCharReferences( $value );
1050 }
1051 return $attribs;
1052 }
1053
1054 /**
1055 * Pick the appropriate attribute value from a match set from the
1056 * attribs regex matches.
1057 *
1058 * @param $set Array
1059 * @return String
1060 */
1061 private static function getTagAttributeCallback( $set ) {
1062 if( isset( $set[6] ) ) {
1063 # Illegal #XXXXXX color with no quotes.
1064 return $set[6];
1065 } elseif( isset( $set[5] ) ) {
1066 # No quotes.
1067 return $set[5];
1068 } elseif( isset( $set[4] ) ) {
1069 # Single-quoted
1070 return $set[4];
1071 } elseif( isset( $set[3] ) ) {
1072 # Double-quoted
1073 return $set[3];
1074 } elseif( !isset( $set[2] ) ) {
1075 # In XHTML, attributes must have a value.
1076 # For 'reduced' form, return explicitly the attribute name here.
1077 return $set[1];
1078 } else {
1079 throw new MWException( "Tag conditions not met. This should never happen and is a bug." );
1080 }
1081 }
1082
1083 /**
1084 * Normalize whitespace and character references in an XML source-
1085 * encoded text for an attribute value.
1086 *
1087 * See http://www.w3.org/TR/REC-xml/#AVNormalize for background,
1088 * but note that we're not returning the value, but are returning
1089 * XML source fragments that will be slapped into output.
1090 *
1091 * @param $text String
1092 * @return String
1093 */
1094 private static function normalizeAttributeValue( $text ) {
1095 return str_replace( '"', '&quot;',
1096 self::normalizeWhitespace(
1097 Sanitizer::normalizeCharReferences( $text ) ) );
1098 }
1099
1100 /**
1101 * @param $text string
1102 * @return mixed
1103 */
1104 private static function normalizeWhitespace( $text ) {
1105 return preg_replace(
1106 '/\r\n|[\x20\x0d\x0a\x09]/',
1107 ' ',
1108 $text );
1109 }
1110
1111 /**
1112 * Normalizes whitespace in a section name, such as might be returned
1113 * by Parser::stripSectionName(), for use in the id's that are used for
1114 * section links.
1115 *
1116 * @param $section String
1117 * @return String
1118 */
1119 static function normalizeSectionNameWhitespace( $section ) {
1120 return trim( preg_replace( '/[ _]+/', ' ', $section ) );
1121 }
1122
1123 /**
1124 * Ensure that any entities and character references are legal
1125 * for XML and XHTML specifically. Any stray bits will be
1126 * &amp;-escaped to result in a valid text fragment.
1127 *
1128 * a. named char refs can only be &lt; &gt; &amp; &quot;, others are
1129 * numericized (this way we're well-formed even without a DTD)
1130 * b. any numeric char refs must be legal chars, not invalid or forbidden
1131 * c. use &#x, not &#X
1132 * d. fix or reject non-valid attributes
1133 *
1134 * @param $text String
1135 * @return String
1136 * @private
1137 */
1138 static function normalizeCharReferences( $text ) {
1139 return preg_replace_callback(
1140 self::CHAR_REFS_REGEX,
1141 array( 'Sanitizer', 'normalizeCharReferencesCallback' ),
1142 $text );
1143 }
1144 /**
1145 * @param $matches String
1146 * @return String
1147 */
1148 static function normalizeCharReferencesCallback( $matches ) {
1149 $ret = null;
1150 if( $matches[1] != '' ) {
1151 $ret = Sanitizer::normalizeEntity( $matches[1] );
1152 } elseif( $matches[2] != '' ) {
1153 $ret = Sanitizer::decCharReference( $matches[2] );
1154 } elseif( $matches[3] != '' ) {
1155 $ret = Sanitizer::hexCharReference( $matches[3] );
1156 }
1157 if( is_null( $ret ) ) {
1158 return htmlspecialchars( $matches[0] );
1159 } else {
1160 return $ret;
1161 }
1162 }
1163
1164 /**
1165 * If the named entity is defined in the HTML 4.0/XHTML 1.0 DTD,
1166 * return the equivalent numeric entity reference (except for the core &lt;
1167 * &gt; &amp; &quot;). If the entity is a MediaWiki-specific alias, returns
1168 * the HTML equivalent. Otherwise, returns HTML-escaped text of
1169 * pseudo-entity source (eg &amp;foo;)
1170 *
1171 * @param $name String
1172 * @return String
1173 */
1174 static function normalizeEntity( $name ) {
1175 if ( isset( self::$htmlEntityAliases[$name] ) ) {
1176 return '&' . self::$htmlEntityAliases[$name] . ';';
1177 } elseif ( in_array( $name,
1178 array( 'lt', 'gt', 'amp', 'quot' ) ) ) {
1179 return "&$name;";
1180 } elseif ( isset( self::$htmlEntities[$name] ) ) {
1181 return '&#' . self::$htmlEntities[$name] . ';';
1182 } else {
1183 return "&amp;$name;";
1184 }
1185 }
1186
1187 /**
1188 * @param $codepoint
1189 * @return null|string
1190 */
1191 static function decCharReference( $codepoint ) {
1192 $point = intval( $codepoint );
1193 if( Sanitizer::validateCodepoint( $point ) ) {
1194 return sprintf( '&#%d;', $point );
1195 } else {
1196 return null;
1197 }
1198 }
1199
1200 /**
1201 * @param $codepoint
1202 * @return null|string
1203 */
1204 static function hexCharReference( $codepoint ) {
1205 $point = hexdec( $codepoint );
1206 if( Sanitizer::validateCodepoint( $point ) ) {
1207 return sprintf( '&#x%x;', $point );
1208 } else {
1209 return null;
1210 }
1211 }
1212
1213 /**
1214 * Returns true if a given Unicode codepoint is a valid character in XML.
1215 * @param $codepoint Integer
1216 * @return Boolean
1217 */
1218 private static function validateCodepoint( $codepoint ) {
1219 return ($codepoint == 0x09)
1220 || ($codepoint == 0x0a)
1221 || ($codepoint == 0x0d)
1222 || ($codepoint >= 0x20 && $codepoint <= 0xd7ff)
1223 || ($codepoint >= 0xe000 && $codepoint <= 0xfffd)
1224 || ($codepoint >= 0x10000 && $codepoint <= 0x10ffff);
1225 }
1226
1227 /**
1228 * Decode any character references, numeric or named entities,
1229 * in the text and return a UTF-8 string.
1230 *
1231 * @param $text String
1232 * @return String
1233 */
1234 public static function decodeCharReferences( $text ) {
1235 return preg_replace_callback(
1236 self::CHAR_REFS_REGEX,
1237 array( 'Sanitizer', 'decodeCharReferencesCallback' ),
1238 $text );
1239 }
1240
1241 /**
1242 * Decode any character references, numeric or named entities,
1243 * in the next and normalize the resulting string. (bug 14952)
1244 *
1245 * This is useful for page titles, not for text to be displayed,
1246 * MediaWiki allows HTML entities to escape normalization as a feature.
1247 *
1248 * @param $text String (already normalized, containing entities)
1249 * @return String (still normalized, without entities)
1250 */
1251 public static function decodeCharReferencesAndNormalize( $text ) {
1252 global $wgContLang;
1253 $text = preg_replace_callback(
1254 self::CHAR_REFS_REGEX,
1255 array( 'Sanitizer', 'decodeCharReferencesCallback' ),
1256 $text, /* limit */ -1, $count );
1257
1258 if ( $count ) {
1259 return $wgContLang->normalize( $text );
1260 } else {
1261 return $text;
1262 }
1263 }
1264
1265 /**
1266 * @param $matches String
1267 * @return String
1268 */
1269 static function decodeCharReferencesCallback( $matches ) {
1270 if( $matches[1] != '' ) {
1271 return Sanitizer::decodeEntity( $matches[1] );
1272 } elseif( $matches[2] != '' ) {
1273 return Sanitizer::decodeChar( intval( $matches[2] ) );
1274 } elseif( $matches[3] != '' ) {
1275 return Sanitizer::decodeChar( hexdec( $matches[3] ) );
1276 }
1277 # Last case should be an ampersand by itself
1278 return $matches[0];
1279 }
1280
1281 /**
1282 * Return UTF-8 string for a codepoint if that is a valid
1283 * character reference, otherwise U+FFFD REPLACEMENT CHARACTER.
1284 * @param $codepoint Integer
1285 * @return String
1286 * @private
1287 */
1288 static function decodeChar( $codepoint ) {
1289 if( Sanitizer::validateCodepoint( $codepoint ) ) {
1290 return codepointToUtf8( $codepoint );
1291 } else {
1292 return UTF8_REPLACEMENT;
1293 }
1294 }
1295
1296 /**
1297 * If the named entity is defined in the HTML 4.0/XHTML 1.0 DTD,
1298 * return the UTF-8 encoding of that character. Otherwise, returns
1299 * pseudo-entity source (eg &foo;)
1300 *
1301 * @param $name String
1302 * @return String
1303 */
1304 static function decodeEntity( $name ) {
1305 if ( isset( self::$htmlEntityAliases[$name] ) ) {
1306 $name = self::$htmlEntityAliases[$name];
1307 }
1308 if( isset( self::$htmlEntities[$name] ) ) {
1309 return codepointToUtf8( self::$htmlEntities[$name] );
1310 } else {
1311 return "&$name;";
1312 }
1313 }
1314
1315 /**
1316 * Fetch the whitelist of acceptable attributes for a given element name.
1317 *
1318 * @param $element String
1319 * @return Array
1320 */
1321 static function attributeWhitelist( $element ) {
1322 static $list;
1323 if( !isset( $list ) ) {
1324 $list = Sanitizer::setupAttributeWhitelist();
1325 }
1326 return isset( $list[$element] )
1327 ? $list[$element]
1328 : array();
1329 }
1330
1331 /**
1332 * Foreach array key (an allowed HTML element), return an array
1333 * of allowed attributes
1334 * @return Array
1335 */
1336 static function setupAttributeWhitelist() {
1337 global $wgAllowRdfaAttributes, $wgHtml5, $wgAllowMicrodataAttributes;
1338
1339 $common = array( 'id', 'class', 'lang', 'dir', 'title', 'style' );
1340
1341 if ( $wgAllowRdfaAttributes ) {
1342 #RDFa attributes as specified in section 9 of http://www.w3.org/TR/2008/REC-rdfa-syntax-20081014
1343 $common = array_merge( $common, array(
1344 'about', 'property', 'resource', 'datatype', 'typeof',
1345 ) );
1346 }
1347
1348 if ( $wgHtml5 && $wgAllowMicrodataAttributes ) {
1349 # add HTML5 microdata tages as pecified by http://www.whatwg.org/specs/web-apps/current-work/multipage/microdata.html#the-microdata-model
1350 $common = array_merge( $common, array(
1351 'itemid', 'itemprop', 'itemref', 'itemscope', 'itemtype'
1352 ) );
1353 }
1354
1355 $block = array_merge( $common, array( 'align' ) );
1356 $tablealign = array( 'align', 'char', 'charoff', 'valign' );
1357 $tablecell = array( 'abbr',
1358 'axis',
1359 'headers',
1360 'scope',
1361 'rowspan',
1362 'colspan',
1363 'nowrap', # deprecated
1364 'width', # deprecated
1365 'height', # deprecated
1366 'bgcolor' # deprecated
1367 );
1368
1369 # Numbers refer to sections in HTML 4.01 standard describing the element.
1370 # See: http://www.w3.org/TR/html4/
1371 $whitelist = array (
1372 # 7.5.4
1373 'div' => $block,
1374 'center' => $common, # deprecated
1375 'span' => $block, # ??
1376
1377 # 7.5.5
1378 'h1' => $block,
1379 'h2' => $block,
1380 'h3' => $block,
1381 'h4' => $block,
1382 'h5' => $block,
1383 'h6' => $block,
1384
1385 # 7.5.6
1386 # address
1387
1388 # 8.2.4
1389 # bdo
1390
1391 # 9.2.1
1392 'em' => $common,
1393 'strong' => $common,
1394 'cite' => $common,
1395 'dfn' => $common,
1396 'code' => $common,
1397 'samp' => $common,
1398 'kbd' => $common,
1399 'var' => $common,
1400 'abbr' => $common,
1401 # acronym
1402
1403 # 9.2.2
1404 'blockquote' => array_merge( $common, array( 'cite' ) ),
1405 # q
1406
1407 # 9.2.3
1408 'sub' => $common,
1409 'sup' => $common,
1410
1411 # 9.3.1
1412 'p' => $block,
1413
1414 # 9.3.2
1415 'br' => array( 'id', 'class', 'title', 'style', 'clear' ),
1416
1417 # 9.3.4
1418 'pre' => array_merge( $common, array( 'width' ) ),
1419
1420 # 9.4
1421 'ins' => array_merge( $common, array( 'cite', 'datetime' ) ),
1422 'del' => array_merge( $common, array( 'cite', 'datetime' ) ),
1423
1424 # 10.2
1425 'ul' => array_merge( $common, array( 'type' ) ),
1426 'ol' => array_merge( $common, array( 'type', 'start' ) ),
1427 'li' => array_merge( $common, array( 'type', 'value' ) ),
1428
1429 # 10.3
1430 'dl' => $common,
1431 'dd' => $common,
1432 'dt' => $common,
1433
1434 # 11.2.1
1435 'table' => array_merge( $common,
1436 array( 'summary', 'width', 'border', 'frame',
1437 'rules', 'cellspacing', 'cellpadding',
1438 'align', 'bgcolor',
1439 ) ),
1440
1441 # 11.2.2
1442 'caption' => array_merge( $common, array( 'align' ) ),
1443
1444 # 11.2.3
1445 'thead' => array_merge( $common, $tablealign ),
1446 'tfoot' => array_merge( $common, $tablealign ),
1447 'tbody' => array_merge( $common, $tablealign ),
1448
1449 # 11.2.4
1450 'colgroup' => array_merge( $common, array( 'span', 'width' ), $tablealign ),
1451 'col' => array_merge( $common, array( 'span', 'width' ), $tablealign ),
1452
1453 # 11.2.5
1454 'tr' => array_merge( $common, array( 'bgcolor' ), $tablealign ),
1455
1456 # 11.2.6
1457 'td' => array_merge( $common, $tablecell, $tablealign ),
1458 'th' => array_merge( $common, $tablecell, $tablealign ),
1459
1460 # 12.2 # NOTE: <a> is not allowed directly, but the attrib whitelist is used from the Parser object
1461 'a' => array_merge( $common, array( 'href', 'rel', 'rev' ) ), # rel/rev esp. for RDFa
1462
1463 # 13.2
1464 # Not usually allowed, but may be used for extension-style hooks
1465 # such as <math> when it is rasterized, or if $wgAllowImageTag is
1466 # true
1467 'img' => array_merge( $common, array( 'alt', 'src', 'width', 'height' ) ),
1468
1469 # 15.2.1
1470 'tt' => $common,
1471 'b' => $common,
1472 'i' => $common,
1473 'big' => $common,
1474 'small' => $common,
1475 'strike' => $common,
1476 's' => $common,
1477 'u' => $common,
1478
1479 # 15.2.2
1480 'font' => array_merge( $common, array( 'size', 'color', 'face' ) ),
1481 # basefont
1482
1483 # 15.3
1484 'hr' => array_merge( $common, array( 'noshade', 'size', 'width' ) ),
1485
1486 # XHTML Ruby annotation text module, simple ruby only.
1487 # http://www.w3c.org/TR/ruby/
1488 'ruby' => $common,
1489 # rbc
1490 # rtc
1491 'rb' => $common,
1492 'rt' => $common, #array_merge( $common, array( 'rbspan' ) ),
1493 'rp' => $common,
1494
1495 # MathML root element, where used for extensions
1496 # 'title' may not be 100% valid here; it's XHTML
1497 # http://www.w3.org/TR/REC-MathML/
1498 'math' => array( 'class', 'style', 'id', 'title' ),
1499 );
1500 return $whitelist;
1501 }
1502
1503 /**
1504 * Take a fragment of (potentially invalid) HTML and return
1505 * a version with any tags removed, encoded as plain text.
1506 *
1507 * Warning: this return value must be further escaped for literal
1508 * inclusion in HTML output as of 1.10!
1509 *
1510 * @param $text String: HTML fragment
1511 * @return String
1512 */
1513 static function stripAllTags( $text ) {
1514 # Actual <tags>
1515 $text = StringUtils::delimiterReplace( '<', '>', '', $text );
1516
1517 # Normalize &entities and whitespace
1518 $text = self::decodeCharReferences( $text );
1519 $text = self::normalizeWhitespace( $text );
1520
1521 return $text;
1522 }
1523
1524 /**
1525 * Hack up a private DOCTYPE with HTML's standard entity declarations.
1526 * PHP 4 seemed to know these if you gave it an HTML doctype, but
1527 * PHP 5.1 doesn't.
1528 *
1529 * Use for passing XHTML fragments to PHP's XML parsing functions
1530 *
1531 * @return String
1532 */
1533 static function hackDocType() {
1534 $out = "<!DOCTYPE html [\n";
1535 foreach( self::$htmlEntities as $entity => $codepoint ) {
1536 $out .= "<!ENTITY $entity \"&#$codepoint;\">";
1537 }
1538 $out .= "]>\n";
1539 return $out;
1540 }
1541
1542 /**
1543 * @param $url string
1544 * @return mixed|string
1545 */
1546 static function cleanUrl( $url ) {
1547 # Normalize any HTML entities in input. They will be
1548 # re-escaped by makeExternalLink().
1549 $url = Sanitizer::decodeCharReferences( $url );
1550
1551 # Escape any control characters introduced by the above step
1552 $url = preg_replace_callback( '/[\][<>"\\x00-\\x20\\x7F\|]/',
1553 array( __CLASS__, 'cleanUrlCallback' ), $url );
1554
1555 # Validate hostname portion
1556 $matches = array();
1557 if( preg_match( '!^([^:]+:)(//[^/]+)?(.*)$!iD', $url, $matches ) ) {
1558 list( /* $whole */, $protocol, $host, $rest ) = $matches;
1559
1560 // Characters that will be ignored in IDNs.
1561 // http://tools.ietf.org/html/3454#section-3.1
1562 // Strip them before further processing so blacklists and such work.
1563 $strip = "/
1564 \\s| # general whitespace
1565 \xc2\xad| # 00ad SOFT HYPHEN
1566 \xe1\xa0\x86| # 1806 MONGOLIAN TODO SOFT HYPHEN
1567 \xe2\x80\x8b| # 200b ZERO WIDTH SPACE
1568 \xe2\x81\xa0| # 2060 WORD JOINER
1569 \xef\xbb\xbf| # feff ZERO WIDTH NO-BREAK SPACE
1570 \xcd\x8f| # 034f COMBINING GRAPHEME JOINER
1571 \xe1\xa0\x8b| # 180b MONGOLIAN FREE VARIATION SELECTOR ONE
1572 \xe1\xa0\x8c| # 180c MONGOLIAN FREE VARIATION SELECTOR TWO
1573 \xe1\xa0\x8d| # 180d MONGOLIAN FREE VARIATION SELECTOR THREE
1574 \xe2\x80\x8c| # 200c ZERO WIDTH NON-JOINER
1575 \xe2\x80\x8d| # 200d ZERO WIDTH JOINER
1576 [\xef\xb8\x80-\xef\xb8\x8f] # fe00-fe00f VARIATION SELECTOR-1-16
1577 /xuD";
1578
1579 $host = preg_replace( $strip, '', $host );
1580
1581 // @todo FIXME: Validate hostnames here
1582
1583 return $protocol . $host . $rest;
1584 } else {
1585 return $url;
1586 }
1587 }
1588
1589 /**
1590 * @param $matches array
1591 * @return string
1592 */
1593 static function cleanUrlCallback( $matches ) {
1594 return urlencode( $matches[0] );
1595 }
1596
1597 /**
1598 * Does a string look like an e-mail address?
1599 *
1600 * This validates an email address using an HTML5 specification found at:
1601 * http://www.whatwg.org/specs/web-apps/current-work/multipage/states-of-the-type-attribute.html#valid-e-mail-address
1602 * Which as of 2011-01-24 says:
1603 *
1604 * A valid e-mail address is a string that matches the ABNF production
1605 * 1*( atext / "." ) "@" ldh-str *( "." ldh-str ) where atext is defined
1606 * in RFC 5322 section 3.2.3, and ldh-str is defined in RFC 1034 section
1607 * 3.5.
1608 *
1609 * This function is an implementation of the specification as requested in
1610 * bug 22449.
1611 *
1612 * Client-side forms will use the same standard validation rules via JS or
1613 * HTML 5 validation; additional restrictions can be enforced server-side
1614 * by extensions via the 'isValidEmailAddr' hook.
1615 *
1616 * Note that this validation doesn't 100% match RFC 2822, but is believed
1617 * to be liberal enough for wide use. Some invalid addresses will still
1618 * pass validation here.
1619 *
1620 * @param $addr String E-mail address
1621 * @return Bool
1622 */
1623 public static function validateEmail( $addr ) {
1624 $result = null;
1625 if( !wfRunHooks( 'isValidEmailAddr', array( $addr, &$result ) ) ) {
1626 return $result;
1627 }
1628
1629 // Please note strings below are enclosed in brackets [], this make the
1630 // hyphen "-" a range indicator. Hence it is double backslashed below.
1631 // See bug 26948
1632 $rfc5322_atext = "a-z0-9!#$%&'*+\\-\/=?^_`{|}~" ;
1633 $rfc1034_ldh_str = "a-z0-9\\-" ;
1634
1635 $HTML5_email_regexp = "/
1636 ^ # start of string
1637 [$rfc5322_atext\\.]+ # user part which is liberal :p
1638 @ # 'apostrophe'
1639 [$rfc1034_ldh_str]+ # First domain part
1640 (\\.[$rfc1034_ldh_str]+)* # Following part prefixed with a dot
1641 $ # End of string
1642 /ix" ; // case Insensitive, eXtended
1643
1644 return (bool) preg_match( $HTML5_email_regexp, $addr );
1645 }
1646 }