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