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