]> scripts.mit.edu Git - autoinstallsdev/mediawiki.git/blob - includes/Sanitizer.php
MediaWiki 1.16.0
[autoinstallsdev/mediawiki.git] / includes / Sanitizer.php
1 <?php
2 /**
3  * XHTML sanitizer for MediaWiki
4  *
5  * Copyright (C) 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          |&\#x([0-9A-Za-z]+);
35          |&\#X([0-9A-Za-z]+);
36          |(&)/x' );
37
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
42  */
43 $attrib = '[A-Za-z0-9]';
44 $space = '[\x09\x0a\x0d\x20]';
45 define( 'MW_ATTRIBS_REGEX',
46         "/(?:^|$space)((?:xml:|xmlns:)?$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', 'u', 'abbr'
371                         );
372                         $htmlsingle = array(
373                                 'br', 'hr', 'li', 'dt', 'dd'
374                         );
375                         $htmlsingleonly = array( # Elements that cannot have close tags
376                                 'br', 'hr'
377                         );
378                         $htmlnest = array( # Tags that can be nested--??
379                                 'table', 'tr', 'td', 'th', 'div', 'blockquote', 'ol', 'ul',
380                                 'dl', 'font', 'big', 'small', 'sub', 'sup', 'span'
381                         );
382                         $tabletags = array( # Can only appear inside table, we will close them
383                                 'td', 'th', 'tr',
384                         );
385                         $htmllist = array( # Tags used by list
386                                 'ul','ol',
387                         );
388                         $listtags = array( # Tags that can appear in a list
389                                 'li',
390                         );
391
392                         $htmlsingleallowed = array_unique( array_merge( $htmlsingle, $tabletags ) );
393                         $htmlelementsStatic = array_unique( array_merge( $htmlsingle, $htmlpairsStatic, $htmlnest ) );
394
395                         # Convert them all to hashtables for faster lookup
396                         $vars = array( 'htmlpairsStatic', 'htmlsingle', 'htmlsingleonly', 'htmlnest', 'tabletags',
397                                 'htmllist', 'listtags', 'htmlsingleallowed', 'htmlelementsStatic' );
398                         foreach ( $vars as $var ) {
399                                 $$var = array_flip( $$var );
400                         }
401                         $staticInitialised = true;
402                 }
403                 # Populate $htmlpairs and $htmlelements with the $extratags and $removetags arrays
404                 $extratags = array_flip( $extratags );
405                 $removetags = array_flip( $removetags );
406                 $htmlpairs = array_merge( $extratags, $htmlpairsStatic );
407                 $htmlelements = array_diff_key( array_merge( $extratags, $htmlelementsStatic ) , $removetags );
408
409                 # Remove HTML comments
410                 $text = Sanitizer::removeHTMLcomments( $text );
411                 $bits = explode( '<', $text );
412                 $text = str_replace( '>', '&gt;', array_shift( $bits ) );
413                 if ( !$wgUseTidy ) {
414                         $tagstack = $tablestack = array();
415                         foreach ( $bits as $x ) {
416                                 $regs = array();
417                                 # $slash: Does the current element start with a '/'?
418                                 # $t: Current element name
419                                 # $params: String between element name and >
420                                 # $brace: Ending '>' or '/>'
421                                 # $rest: Everything until the next element of $bits
422                                 if( preg_match( '!^(/?)(\\w+)([^>]*?)(/{0,1}>)([^<]*)$!', $x, $regs ) ) {
423                                         list( /* $qbar */, $slash, $t, $params, $brace, $rest ) = $regs;
424                                 } else {
425                                         $slash = $t = $params = $brace = $rest = null;
426                                 }
427
428                                 $badtag = false;
429                                 if ( isset( $htmlelements[$t = strtolower( $t )] ) ) {
430                                         # Check our stack
431                                         if ( $slash && isset( $htmlsingleonly[$t] ) ) {
432                                                 $badtag = true;
433                                         } elseif ( $slash ) {
434                                                 # Closing a tag... is it the one we just opened?
435                                                 $ot = @array_pop( $tagstack );
436                                                 if ( $ot != $t ) {
437                                                         if ( isset( $htmlsingleallowed[$ot] ) ) {
438                                                                 # Pop all elements with an optional close tag
439                                                                 # and see if we find a match below them
440                                                                 $optstack = array();
441                                                                 array_push( $optstack, $ot );
442                                                                 $ot = @array_pop( $tagstack );
443                                                                 while ( $ot != $t && isset( $htmlsingleallowed[$ot] ) ) {
444                                                                         array_push( $optstack, $ot );
445                                                                         $ot = @array_pop( $tagstack );
446                                                                 }
447                                                                 if ( $t != $ot ) {
448                                                                         # No match. Push the optional elements back again
449                                                                         $badtag = true;
450                                                                         while ( $ot = @array_pop( $optstack ) ) {
451                                                                                 array_push( $tagstack, $ot );
452                                                                         }
453                                                                 }
454                                                         } else {
455                                                                 @array_push( $tagstack, $ot );
456                                                                 # <li> can be nested in <ul> or <ol>, skip those cases:
457                                                                 if ( !isset( $htmllist[$ot] ) || !isset( $listtags[$t] ) ) {
458                                                                         $badtag = true;
459                                                                 }
460                                                         }
461                                                 } else {
462                                                         if ( $t == 'table' ) {
463                                                                 $tagstack = array_pop( $tablestack );
464                                                         }
465                                                 }
466                                                 $newparams = '';
467                                         } else {
468                                                 # Keep track for later
469                                                 if ( isset( $tabletags[$t] ) &&
470                                                 !in_array( 'table', $tagstack ) ) {
471                                                         $badtag = true;
472                                                 } elseif ( in_array( $t, $tagstack ) &&
473                                                 !isset( $htmlnest [$t ] ) ) {
474                                                         $badtag = true;
475                                                 # Is it a self closed htmlpair ? (bug 5487)
476                                                 } elseif ( $brace == '/>' &&
477                                                 isset( $htmlpairs[$t] ) ) {
478                                                         $badtag = true;
479                                                 } elseif ( isset( $htmlsingleonly[$t] ) ) {
480                                                         # Hack to force empty tag for uncloseable elements
481                                                         $brace = '/>';
482                                                 } elseif ( isset( $htmlsingle[$t] ) ) {
483                                                         # Hack to not close $htmlsingle tags
484                                                         $brace = null;
485                                                 } elseif ( isset( $tabletags[$t] )
486                                                 && in_array( $t, $tagstack ) ) {
487                                                         // New table tag but forgot to close the previous one
488                                                         $text .= "</$t>";
489                                                 } else {
490                                                         if ( $t == 'table' ) {
491                                                                 array_push( $tablestack, $tagstack );
492                                                                 $tagstack = array();
493                                                         }
494                                                         array_push( $tagstack, $t );
495                                                 }
496
497                                                 # Replace any variables or template parameters with
498                                                 # plaintext results.
499                                                 if( is_callable( $processCallback ) ) {
500                                                         call_user_func_array( $processCallback, array( &$params, $args ) );
501                                                 }
502
503                                                 # Strip non-approved attributes from the tag
504                                                 $newparams = Sanitizer::fixTagAttributes( $params, $t );
505                                         }
506                                         if ( !$badtag ) {
507                                                 $rest = str_replace( '>', '&gt;', $rest );
508                                                 $close = ( $brace == '/>' && !$slash ) ? ' /' : '';
509                                                 $text .= "<$slash$t$newparams$close>$rest";
510                                                 continue;
511                                         }
512                                 }
513                                 $text .= '&lt;' . str_replace( '>', '&gt;', $x);
514                         }
515                         # Close off any remaining tags
516                         while ( is_array( $tagstack ) && ($t = array_pop( $tagstack )) ) {
517                                 $text .= "</$t>\n";
518                                 if ( $t == 'table' ) { $tagstack = array_pop( $tablestack ); }
519                         }
520                 } else {
521                         # this might be possible using tidy itself
522                         foreach ( $bits as $x ) {
523                                 preg_match( '/^(\\/?)(\\w+)([^>]*?)(\\/{0,1}>)([^<]*)$/',
524                                 $x, $regs );
525                                 @list( /* $qbar */, $slash, $t, $params, $brace, $rest ) = $regs;
526                                 if ( isset( $htmlelements[$t = strtolower( $t )] ) ) {
527                                         if( is_callable( $processCallback ) ) {
528                                                 call_user_func_array( $processCallback, array( &$params, $args ) );
529                                         }
530                                         $newparams = Sanitizer::fixTagAttributes( $params, $t );
531                                         $rest = str_replace( '>', '&gt;', $rest );
532                                         $text .= "<$slash$t$newparams$brace$rest";
533                                 } else {
534                                         $text .= '&lt;' . str_replace( '>', '&gt;', $x);
535                                 }
536                         }
537                 }
538                 wfProfileOut( __METHOD__ );
539                 return $text;
540         }
541
542         /**
543          * Remove '<!--', '-->', and everything between.
544          * To avoid leaving blank lines, when a comment is both preceded
545          * and followed by a newline (ignoring spaces), trim leading and
546          * trailing spaces and one of the newlines.
547          *
548          * @private
549          * @param $text String
550          * @return string
551          */
552         static function removeHTMLcomments( $text ) {
553                 wfProfileIn( __METHOD__ );
554                 while (($start = strpos($text, '<!--')) !== false) {
555                         $end = strpos($text, '-->', $start + 4);
556                         if ($end === false) {
557                                 # Unterminated comment; bail out
558                                 break;
559                         }
560
561                         $end += 3;
562
563                         # Trim space and newline if the comment is both
564                         # preceded and followed by a newline
565                         $spaceStart = max($start - 1, 0);
566                         $spaceLen = $end - $spaceStart;
567                         while (substr($text, $spaceStart, 1) === ' ' && $spaceStart > 0) {
568                                 $spaceStart--;
569                                 $spaceLen++;
570                         }
571                         while (substr($text, $spaceStart + $spaceLen, 1) === ' ')
572                                 $spaceLen++;
573                         if (substr($text, $spaceStart, 1) === "\n" and substr($text, $spaceStart + $spaceLen, 1) === "\n") {
574                                 # Remove the comment, leading and trailing
575                                 # spaces, and leave only one newline.
576                                 $text = substr_replace($text, "\n", $spaceStart, $spaceLen + 1);
577                         }
578                         else {
579                                 # Remove just the comment.
580                                 $text = substr_replace($text, '', $start, $end - $start);
581                         }
582                 }
583                 wfProfileOut( __METHOD__ );
584                 return $text;
585         }
586
587         /**
588          * Take an array of attribute names and values and normalize or discard
589          * illegal values for the given element type.
590          *
591          * - Discards attributes not on a whitelist for the given element
592          * - Unsafe style attributes are discarded
593          * - Invalid id attributes are reencoded
594          *
595          * @param $attribs Array
596          * @param $element String
597          * @return Array
598          *
599          * @todo Check for legal values where the DTD limits things.
600          * @todo Check for unique id attribute :P
601          */
602         static function validateTagAttributes( $attribs, $element ) {
603                 return Sanitizer::validateAttributes( $attribs,
604                         Sanitizer::attributeWhitelist( $element ) );
605         }
606
607         /**
608          * Take an array of attribute names and values and normalize or discard
609          * illegal values for the given whitelist.
610          *
611          * - Discards attributes not the given whitelist
612          * - Unsafe style attributes are discarded
613          * - Invalid id attributes are reencoded
614          *
615          * @param $attribs Array
616          * @param $whitelist Array: list of allowed attribute names
617          * @return Array
618          *
619          * @todo Check for legal values where the DTD limits things.
620          * @todo Check for unique id attribute :P
621          */
622         static function validateAttributes( $attribs, $whitelist ) {
623                 global $wgAllowRdfaAttributes, $wgAllowMicrodataAttributes;
624
625                 $whitelist = array_flip( $whitelist );
626                 $hrefExp = '/^(' . wfUrlProtocols() . ')[^\s]+$/';
627
628                 $out = array();
629                 foreach( $attribs as $attribute => $value ) {
630                         #allow XML namespace declaration if RDFa is enabled
631                         if ( $wgAllowRdfaAttributes && preg_match( MW_XMLNS_ATTRIBUTE_PATTRN, $attribute ) ) {
632                                 if ( !preg_match( MW_EVIL_URI_PATTERN, $value ) ) {
633                                         $out[$attribute] = $value;
634                                 }
635
636                                 continue;
637                         }
638
639                         if( !isset( $whitelist[$attribute] ) ) {
640                                 continue;
641                         }
642
643                         # Strip javascript "expression" from stylesheets.
644                         # http://msdn.microsoft.com/workshop/author/dhtml/overview/recalc.asp
645                         if( $attribute == 'style' ) {
646                                 $value = Sanitizer::checkCss( $value );
647                         }
648
649                         if ( $attribute === 'id' ) {
650                                 $value = Sanitizer::escapeId( $value, 'noninitial' );
651                         }
652
653                         //RDFa and microdata properties allow URLs, URIs and/or CURIs. check them for sanity
654                         if ( $attribute === 'rel' || $attribute === 'rev' || 
655                                 $attribute === 'about' || $attribute === 'property' || $attribute === 'resource' || #RDFa
656                                 $attribute === 'datatype' || $attribute === 'typeof' ||                             #RDFa
657                                 $attribute === 'itemid' || $attribute === 'itemprop' || $attribute === 'itemref' || #HTML5 microdata
658                                 $attribute === 'itemscope' || $attribute === 'itemtype' ) {                         #HTML5 microdata
659
660                                 //Paranoia. Allow "simple" values but suppress javascript
661                                 if ( preg_match( MW_EVIL_URI_PATTERN, $value ) ) {
662                                         continue; 
663                                 }
664                         }
665
666                         # NOTE: even though elements using href/src are not allowed directly, supply
667                         #       validation code that can be used by tag hook handlers, etc
668                         if ( $attribute === 'href' || $attribute === 'src' ) {
669                                 if ( !preg_match( $hrefExp, $value ) ) {
670                                         continue; //drop any href or src attributes not using an allowed protocol.
671                                                   //NOTE: this also drops all relative URLs
672                                 }
673                         }
674
675                         // If this attribute was previously set, override it.
676                         // Output should only have one attribute of each name.
677                         $out[$attribute] = $value;
678                 }
679
680                 if ( $wgAllowMicrodataAttributes ) {
681                         # There are some complicated validity constraints we need to
682                         # enforce here.  First of all, we don't want to allow non-standard
683                         # itemtypes.
684                         $allowedTypes = array(
685                                 'http://microformats.org/profile/hcard',
686                                 'http://microformats.org/profile/hcalendar#vevent',
687                                 'http://n.whatwg.org/work',
688                         );
689                         if ( isset( $out['itemtype'] ) && !in_array( $out['itemtype'],
690                         $allowedTypes ) ) {
691                                 # Kill everything
692                                 unset( $out['itemscope'] );
693                         }
694                         # itemtype, itemid, itemref don't make sense without itemscope
695                         if ( !array_key_exists( 'itemscope', $out ) ) {
696                                 unset( $out['itemtype'] );
697                                 unset( $out['itemid'] );
698                                 unset( $out['itemref'] );
699                         }
700                         # TODO: Strip itemprop if we aren't descendants of an itemscope.
701                 }
702                 return $out;
703         }
704
705         /**
706          * Merge two sets of HTML attributes.  Conflicting items in the second set
707          * will override those in the first, except for 'class' attributes which
708          * will be combined (if they're both strings).
709          *
710          * @todo implement merging for other attributes such as style
711          * @param $a Array
712          * @param $b Array
713          * @return array
714          */
715         static function mergeAttributes( $a, $b ) {
716                 $out = array_merge( $a, $b );
717                 if( isset( $a['class'] ) && isset( $b['class'] )
718                 && is_string( $a['class'] ) && is_string( $b['class'] )
719                 && $a['class'] !== $b['class'] ) {
720                         $classes = preg_split( '/\s+/', "{$a['class']} {$b['class']}",
721                                 -1, PREG_SPLIT_NO_EMPTY );
722                         $out['class'] = implode( ' ', array_unique( $classes ) );
723                 }
724                 return $out;
725         }
726
727         /**
728          * Pick apart some CSS and check it for forbidden or unsafe structures.
729          * Returns a sanitized string, or false if it was just too evil.
730          *
731          * Currently URL references, 'expression', 'tps' are forbidden.
732          *
733          * @param $value String
734          * @return Mixed
735          */
736         static function checkCss( $value ) {
737                 $value = Sanitizer::decodeCharReferences( $value );
738
739                 // Remove any comments; IE gets token splitting wrong
740                 $value = StringUtils::delimiterReplace( '/*', '*/', ' ', $value );
741
742                 // Decode escape sequences and line continuation
743                 // See the grammar in the CSS 2 spec, appendix D.
744                 static $decodeRegex, $reencodeTable;
745                 if ( !$decodeRegex ) {
746                         $space = '[\\x20\\t\\r\\n\\f]';
747                         $nl = '(?:\\n|\\r\\n|\\r|\\f)';
748                         $backslash = '\\\\';
749                         $decodeRegex = "/ $backslash 
750                                 (?:
751                                         ($nl) |  # 1. Line continuation
752                                         ([0-9A-Fa-f]{1,6})$space? |  # 2. character number
753                                         (.) | # 3. backslash cancelling special meaning
754                                         () | # 4. backslash at end of string
755                                 )/xu";
756                 }
757                 $value = preg_replace_callback( $decodeRegex,
758                         array( __CLASS__, 'cssDecodeCallback' ), $value );
759
760                 // Reject problematic keywords and control characters
761                 if ( preg_match( '/[\000-\010\016-\037\177]/', $value ) ) {
762                         return '/* invalid control char */';
763                 } elseif ( preg_match( '! expression | filter\s*: | accelerator\s*: | url\s*\( !ix', $value ) ) {
764                         return '/* insecure input */';
765                 }
766                 return $value;
767         }
768
769         static function cssDecodeCallback( $matches ) {
770                 if ( $matches[1] !== '' ) {
771                         // Line continuation
772                         return '';
773                 } elseif ( $matches[2] !== '' ) {
774                         $char = codepointToUtf8( hexdec( $matches[2] ) );
775                 } elseif ( $matches[3] !== '' ) {
776                         $char = $matches[3];
777                 } else {
778                         $char = '\\';
779                 }
780                 if ( $char == "\n" || $char == '"' || $char == "'" || $char == '\\' ) {
781                         // These characters need to be escaped in strings
782                         // Clean up the escape sequence to avoid parsing errors by clients
783                         return '\\' . dechex( ord( $char ) ) . ' ';
784                 } else {
785                         // Decode unnecessary escape
786                         return $char;
787                 }
788         }
789
790         /**
791          * Take a tag soup fragment listing an HTML element's attributes
792          * and normalize it to well-formed XML, discarding unwanted attributes.
793          * Output is safe for further wikitext processing, with escaping of
794          * values that could trigger problems.
795          *
796          * - Normalizes attribute names to lowercase
797          * - Discards attributes not on a whitelist for the given element
798          * - Turns broken or invalid entities into plaintext
799          * - Double-quotes all attribute values
800          * - Attributes without values are given the name as attribute
801          * - Double attributes are discarded
802          * - Unsafe style attributes are discarded
803          * - Prepends space if there are attributes.
804          *
805          * @param $text String
806          * @param $element String
807          * @return String
808          */
809         static function fixTagAttributes( $text, $element ) {
810                 if( trim( $text ) == '' ) {
811                         return '';
812                 }
813
814                 $stripped = Sanitizer::validateTagAttributes(
815                         Sanitizer::decodeTagAttributes( $text ), $element );
816
817                 $attribs = array();
818                 foreach( $stripped as $attribute => $value ) {
819                         $encAttribute = htmlspecialchars( $attribute );
820                         $encValue = Sanitizer::safeEncodeAttribute( $value );
821
822                         $attribs[] = "$encAttribute=\"$encValue\"";
823                 }
824                 return count( $attribs ) ? ' ' . implode( ' ', $attribs ) : '';
825         }
826
827         /**
828          * Encode an attribute value for HTML output.
829          * @param $text String
830          * @return HTML-encoded text fragment
831          */
832         static function encodeAttribute( $text ) {
833                 $encValue = htmlspecialchars( $text, ENT_QUOTES );
834
835                 // Whitespace is normalized during attribute decoding,
836                 // so if we've been passed non-spaces we must encode them
837                 // ahead of time or they won't be preserved.
838                 $encValue = strtr( $encValue, array(
839                         "\n" => '&#10;',
840                         "\r" => '&#13;',
841                         "\t" => '&#9;',
842                 ) );
843
844                 return $encValue;
845         }
846
847         /**
848          * Encode an attribute value for HTML tags, with extra armoring
849          * against further wiki processing.
850          * @param $text String
851          * @return HTML-encoded text fragment
852          */
853         static function safeEncodeAttribute( $text ) {
854                 $encValue = Sanitizer::encodeAttribute( $text );
855
856                 # Templates and links may be expanded in later parsing,
857                 # creating invalid or dangerous output. Suppress this.
858                 $encValue = strtr( $encValue, array(
859                         '<'    => '&lt;',   // This should never happen,
860                         '>'    => '&gt;',   // we've received invalid input
861                         '"'    => '&quot;', // which should have been escaped.
862                         '{'    => '&#123;',
863                         '['    => '&#91;',
864                         "''"   => '&#39;&#39;',
865                         'ISBN' => '&#73;SBN',
866                         'RFC'  => '&#82;FC',
867                         'PMID' => '&#80;MID',
868                         '|'    => '&#124;',
869                         '__'   => '&#95;_',
870                 ) );
871
872                 # Stupid hack
873                 $encValue = preg_replace_callback(
874                         '/(' . wfUrlProtocols() . ')/',
875                         array( 'Sanitizer', 'armorLinksCallback' ),
876                         $encValue );
877                 return $encValue;
878         }
879
880         /**
881          * Given a value, escape it so that it can be used in an id attribute and
882          * return it.  This will use HTML5 validation if $wgExperimentalHtmlIds is
883          * true, allowing anything but ASCII whitespace.  Otherwise it will use
884          * HTML 4 rules, which means a narrow subset of ASCII, with bad characters
885          * escaped with lots of dots.
886          *
887          * To ensure we don't have to bother escaping anything, we also strip ', ",
888          * & even if $wgExperimentalIds is true.  TODO: Is this the best tactic?
889          * We also strip # because it upsets IE6.
890          *
891          * @see http://www.w3.org/TR/html401/types.html#type-name Valid characters
892          *                                                          in the id and
893          *                                                          name attributes
894          * @see http://www.w3.org/TR/html401/struct/links.html#h-12.2.3 Anchors with the id attribute
895          * @see http://www.whatwg.org/specs/web-apps/current-work/multipage/elements.html#the-id-attribute
896          *   HTML5 definition of id attribute
897          *
898          * @param $id String: id to escape
899          * @param $options Mixed: string or array of strings (default is array()):
900          *   'noninitial': This is a non-initial fragment of an id, not a full id,
901          *       so don't pay attention if the first character isn't valid at the
902          *       beginning of an id.  Only matters if $wgExperimentalHtmlIds is
903          *       false.
904          *   'legacy': Behave the way the old HTML 4-based ID escaping worked even
905          *       if $wgExperimentalHtmlIds is used, so we can generate extra
906          *       anchors and links won't break.
907          * @return String
908          */
909         static function escapeId( $id, $options = array() ) {
910                 global $wgHtml5, $wgExperimentalHtmlIds;
911                 $options = (array)$options;
912
913                 if ( $wgHtml5 && $wgExperimentalHtmlIds && !in_array( 'legacy', $options ) ) {
914                         $id = Sanitizer::decodeCharReferences( $id );
915                         $id = preg_replace( '/[ \t\n\r\f_\'"&#]+/', '_', $id );
916                         $id = trim( $id, '_' );
917                         if ( $id === '' ) {
918                                 # Must have been all whitespace to start with.
919                                 return '_';
920                         } else {
921                                 return $id;
922                         }
923                 }
924
925                 # HTML4-style escaping
926                 static $replace = array(
927                         '%3A' => ':',
928                         '%' => '.'
929                 );
930
931                 $id = urlencode( Sanitizer::decodeCharReferences( strtr( $id, ' ', '_' ) ) );
932                 $id = str_replace( array_keys( $replace ), array_values( $replace ), $id );
933
934                 if ( !preg_match( '/^[a-zA-Z]/', $id )
935                 && !in_array( 'noninitial', $options ) )  {
936                         // Initial character must be a letter!
937                         $id = "x$id";
938                 }
939                 return $id;
940         }
941
942         /**
943          * Given a value, escape it so that it can be used as a CSS class and
944          * return it.
945          *
946          * @todo For extra validity, input should be validated UTF-8.
947          *
948          * @see http://www.w3.org/TR/CSS21/syndata.html Valid characters/format
949          *
950          * @param $class String
951          * @return String
952          */
953         static function escapeClass( $class ) {
954                 // Convert ugly stuff to underscores and kill underscores in ugly places
955                 return rtrim(preg_replace(
956                         array('/(^[0-9\\-])|[\\x00-\\x20!"#$%&\'()*+,.\\/:;<=>?@[\\]^`{|}~]|\\xC2\\xA0/','/_+/'),
957                         '_',
958                         $class ), '_');
959         }
960
961         /**
962          * Given HTML input, escape with htmlspecialchars but un-escape entites.
963          * This allows (generally harmless) entities like &nbsp; to survive.
964          *
965          * @param $html String to escape
966          * @return String: escaped input
967          */
968         static function escapeHtmlAllowEntities( $html ) {
969                 # It seems wise to escape ' as well as ", as a matter of course.  Can't
970                 # hurt.
971                 $html = htmlspecialchars( $html, ENT_QUOTES );
972                 $html = str_replace( '&amp;', '&', $html );
973                 $html = Sanitizer::normalizeCharReferences( $html );
974                 return $html;
975         }
976
977         /**
978          * Regex replace callback for armoring links against further processing.
979          * @param $matches Array
980          * @return string
981          */
982         private static function armorLinksCallback( $matches ) {
983                 return str_replace( ':', '&#58;', $matches[1] );
984         }
985
986         /**
987          * Return an associative array of attribute names and values from
988          * a partial tag string. Attribute names are forces to lowercase,
989          * character references are decoded to UTF-8 text.
990          *
991          * @param $text String
992          * @return Array
993          */
994         public static function decodeTagAttributes( $text ) {
995                 if( trim( $text ) == '' ) {
996                         return array();
997                 }
998
999                 $attribs = array();
1000                 $pairs = array();
1001                 if( !preg_match_all(
1002                         MW_ATTRIBS_REGEX,
1003                         $text,
1004                         $pairs,
1005                         PREG_SET_ORDER ) ) {
1006                         return $attribs;
1007                 }
1008
1009                 foreach( $pairs as $set ) {
1010                         $attribute = strtolower( $set[1] );
1011                         $value = Sanitizer::getTagAttributeCallback( $set );
1012
1013                         // Normalize whitespace
1014                         $value = preg_replace( '/[\t\r\n ]+/', ' ', $value );
1015                         $value = trim( $value );
1016
1017                         // Decode character references
1018                         $attribs[$attribute] = Sanitizer::decodeCharReferences( $value );
1019                 }
1020                 return $attribs;
1021         }
1022
1023         /**
1024          * Pick the appropriate attribute value from a match set from the
1025          * MW_ATTRIBS_REGEX matches.
1026          *
1027          * @param $set Array
1028          * @return String
1029          */
1030         private static function getTagAttributeCallback( $set ) {
1031                 if( isset( $set[6] ) ) {
1032                         # Illegal #XXXXXX color with no quotes.
1033                         return $set[6];
1034                 } elseif( isset( $set[5] ) ) {
1035                         # No quotes.
1036                         return $set[5];
1037                 } elseif( isset( $set[4] ) ) {
1038                         # Single-quoted
1039                         return $set[4];
1040                 } elseif( isset( $set[3] ) ) {
1041                         # Double-quoted
1042                         return $set[3];
1043                 } elseif( !isset( $set[2] ) ) {
1044                         # In XHTML, attributes must have a value.
1045                         # For 'reduced' form, return explicitly the attribute name here.
1046                         return $set[1];
1047                 } else {
1048                         throw new MWException( "Tag conditions not met. This should never happen and is a bug." );
1049                 }
1050         }
1051
1052         /**
1053          * Normalize whitespace and character references in an XML source-
1054          * encoded text for an attribute value.
1055          *
1056          * See http://www.w3.org/TR/REC-xml/#AVNormalize for background,
1057          * but note that we're not returning the value, but are returning
1058          * XML source fragments that will be slapped into output.
1059          *
1060          * @param $text String
1061          * @return String
1062          */
1063         private static function normalizeAttributeValue( $text ) {
1064                 return str_replace( '"', '&quot;',
1065                         self::normalizeWhitespace(
1066                                 Sanitizer::normalizeCharReferences( $text ) ) );
1067         }
1068
1069         private static function normalizeWhitespace( $text ) {
1070                 return preg_replace(
1071                         '/\r\n|[\x20\x0d\x0a\x09]/',
1072                         ' ',
1073                         $text );
1074         }
1075
1076         /**
1077          * Ensure that any entities and character references are legal
1078          * for XML and XHTML specifically. Any stray bits will be
1079          * &amp;-escaped to result in a valid text fragment.
1080          *
1081          * a. any named char refs must be known in XHTML
1082          * b. any numeric char refs must be legal chars, not invalid or forbidden
1083          * c. use &#x, not &#X
1084          * d. fix or reject non-valid attributes
1085          *
1086          * @param $text String
1087          * @return String
1088          * @private
1089          */
1090         static function normalizeCharReferences( $text ) {
1091                 return preg_replace_callback(
1092                         MW_CHAR_REFS_REGEX,
1093                         array( 'Sanitizer', 'normalizeCharReferencesCallback' ),
1094                         $text );
1095         }
1096         /**
1097          * @param $matches String
1098          * @return String
1099          */
1100         static function normalizeCharReferencesCallback( $matches ) {
1101                 $ret = null;
1102                 if( $matches[1] != '' ) {
1103                         $ret = Sanitizer::normalizeEntity( $matches[1] );
1104                 } elseif( $matches[2] != '' ) {
1105                         $ret = Sanitizer::decCharReference( $matches[2] );
1106                 } elseif( $matches[3] != ''  ) {
1107                         $ret = Sanitizer::hexCharReference( $matches[3] );
1108                 } elseif( $matches[4] != '' ) {
1109                         $ret = Sanitizer::hexCharReference( $matches[4] );
1110                 }
1111                 if( is_null( $ret ) ) {
1112                         return htmlspecialchars( $matches[0] );
1113                 } else {
1114                         return $ret;
1115                 }
1116         }
1117
1118         /**
1119          * If the named entity is defined in the HTML 4.0/XHTML 1.0 DTD,
1120          * return the named entity reference as is. If the entity is a
1121          * MediaWiki-specific alias, returns the HTML equivalent. Otherwise,
1122          * returns HTML-escaped text of pseudo-entity source (eg &amp;foo;)
1123          *
1124          * @param $name String
1125          * @return String
1126          */
1127         static function normalizeEntity( $name ) {
1128                 global $wgHtmlEntities, $wgHtmlEntityAliases;
1129                 if ( isset( $wgHtmlEntityAliases[$name] ) ) {
1130                         return "&{$wgHtmlEntityAliases[$name]};";
1131                 } elseif( isset( $wgHtmlEntities[$name] ) ) {
1132                         return "&$name;";
1133                 } else {
1134                         return "&amp;$name;";
1135                 }
1136         }
1137
1138         static function decCharReference( $codepoint ) {
1139                 $point = intval( $codepoint );
1140                 if( Sanitizer::validateCodepoint( $point ) ) {
1141                         return sprintf( '&#%d;', $point );
1142                 } else {
1143                         return null;
1144                 }
1145         }
1146
1147         static function hexCharReference( $codepoint ) {
1148                 $point = hexdec( $codepoint );
1149                 if( Sanitizer::validateCodepoint( $point ) ) {
1150                         return sprintf( '&#x%x;', $point );
1151                 } else {
1152                         return null;
1153                 }
1154         }
1155
1156         /**
1157          * Returns true if a given Unicode codepoint is a valid character in XML.
1158          * @param $codepoint Integer
1159          * @return Boolean
1160          */
1161         private static function validateCodepoint( $codepoint ) {
1162                 return ($codepoint ==    0x09)
1163                         || ($codepoint ==    0x0a)
1164                         || ($codepoint ==    0x0d)
1165                         || ($codepoint >=    0x20 && $codepoint <=   0xd7ff)
1166                         || ($codepoint >=  0xe000 && $codepoint <=   0xfffd)
1167                         || ($codepoint >= 0x10000 && $codepoint <= 0x10ffff);
1168         }
1169
1170         /**
1171          * Decode any character references, numeric or named entities,
1172          * in the text and return a UTF-8 string.
1173          *
1174          * @param $text String
1175          * @return String
1176          */
1177         public static function decodeCharReferences( $text ) {
1178                 return preg_replace_callback(
1179                         MW_CHAR_REFS_REGEX,
1180                         array( 'Sanitizer', 'decodeCharReferencesCallback' ),
1181                         $text );
1182         }
1183
1184         /**
1185          * @param $matches String
1186          * @return String
1187          */
1188         static function decodeCharReferencesCallback( $matches ) {
1189                 if( $matches[1] != '' ) {
1190                         return Sanitizer::decodeEntity( $matches[1] );
1191                 } elseif( $matches[2] != '' ) {
1192                         return  Sanitizer::decodeChar( intval( $matches[2] ) );
1193                 } elseif( $matches[3] != ''  ) {
1194                         return  Sanitizer::decodeChar( hexdec( $matches[3] ) );
1195                 } elseif( $matches[4] != '' ) {
1196                         return  Sanitizer::decodeChar( hexdec( $matches[4] ) );
1197                 }
1198                 # Last case should be an ampersand by itself
1199                 return $matches[0];
1200         }
1201
1202         /**
1203          * Return UTF-8 string for a codepoint if that is a valid
1204          * character reference, otherwise U+FFFD REPLACEMENT CHARACTER.
1205          * @param $codepoint Integer
1206          * @return String
1207          * @private
1208          */
1209         static function decodeChar( $codepoint ) {
1210                 if( Sanitizer::validateCodepoint( $codepoint ) ) {
1211                         return codepointToUtf8( $codepoint );
1212                 } else {
1213                         return UTF8_REPLACEMENT;
1214                 }
1215         }
1216
1217         /**
1218          * If the named entity is defined in the HTML 4.0/XHTML 1.0 DTD,
1219          * return the UTF-8 encoding of that character. Otherwise, returns
1220          * pseudo-entity source (eg &foo;)
1221          *
1222          * @param $name Strings
1223          * @return String
1224          */
1225         static function decodeEntity( $name ) {
1226                 global $wgHtmlEntities, $wgHtmlEntityAliases;
1227                 if ( isset( $wgHtmlEntityAliases[$name] ) ) {
1228                         $name = $wgHtmlEntityAliases[$name];
1229                 }
1230                 if( isset( $wgHtmlEntities[$name] ) ) {
1231                         return codepointToUtf8( $wgHtmlEntities[$name] );
1232                 } else {
1233                         return "&$name;";
1234                 }
1235         }
1236
1237         /**
1238          * Fetch the whitelist of acceptable attributes for a given element name.
1239          *
1240          * @param $element String
1241          * @return Array
1242          */
1243         static function attributeWhitelist( $element ) {
1244                 static $list;
1245                 if( !isset( $list ) ) {
1246                         $list = Sanitizer::setupAttributeWhitelist();
1247                 }
1248                 return isset( $list[$element] )
1249                         ? $list[$element]
1250                         : array();
1251         }
1252
1253         /**
1254          * Foreach array key (an allowed HTML element), return an array
1255          * of allowed attributes
1256          * @return Array
1257          */
1258         static function setupAttributeWhitelist() {
1259                 global $wgAllowRdfaAttributes, $wgHtml5, $wgAllowMicrodataAttributes;
1260
1261                 $common = array( 'id', 'class', 'lang', 'dir', 'title', 'style' );
1262
1263                 if ( $wgAllowRdfaAttributes ) {
1264                         #RDFa attributes as specified in section 9 of http://www.w3.org/TR/2008/REC-rdfa-syntax-20081014
1265                         $common = array_merge( $common, array(
1266                             'about', 'property', 'resource', 'datatype', 'typeof', 
1267                         ) );
1268                 }
1269
1270                 if ( $wgHtml5 && $wgAllowMicrodataAttributes ) {
1271                         # add HTML5 microdata tages as pecified by http://www.whatwg.org/specs/web-apps/current-work/multipage/microdata.html#the-microdata-model
1272                         $common = array_merge( $common, array(
1273                             'itemid', 'itemprop', 'itemref', 'itemscope', 'itemtype'
1274                         ) );
1275                 }
1276
1277                 $block = array_merge( $common, array( 'align' ) );
1278                 $tablealign = array( 'align', 'char', 'charoff', 'valign' );
1279                 $tablecell = array( 'abbr',
1280                                     'axis',
1281                                     'headers',
1282                                     'scope',
1283                                     'rowspan',
1284                                     'colspan',
1285                                     'nowrap', # deprecated
1286                                     'width',  # deprecated
1287                                     'height', # deprecated
1288                                     'bgcolor' # deprecated
1289                                     );
1290
1291                 # Numbers refer to sections in HTML 4.01 standard describing the element.
1292                 # See: http://www.w3.org/TR/html4/
1293                 $whitelist = array (
1294                         # 7.5.4
1295                         'div'        => $block,
1296                         'center'     => $common, # deprecated
1297                         'span'       => $block, # ??
1298
1299                         # 7.5.5
1300                         'h1'         => $block,
1301                         'h2'         => $block,
1302                         'h3'         => $block,
1303                         'h4'         => $block,
1304                         'h5'         => $block,
1305                         'h6'         => $block,
1306
1307                         # 7.5.6
1308                         # address
1309
1310                         # 8.2.4
1311                         # bdo
1312
1313                         # 9.2.1
1314                         'em'         => $common,
1315                         'strong'     => $common,
1316                         'cite'       => $common,
1317                         # dfn
1318                         'code'       => $common,
1319                         # samp
1320                         # kbd
1321                         'var'        => $common,
1322                         'abbr'       => $common,
1323                         # acronym
1324
1325                         # 9.2.2
1326                         'blockquote' => array_merge( $common, array( 'cite' ) ),
1327                         # q
1328
1329                         # 9.2.3
1330                         'sub'        => $common,
1331                         'sup'        => $common,
1332
1333                         # 9.3.1
1334                         'p'          => $block,
1335
1336                         # 9.3.2
1337                         'br'         => array( 'id', 'class', 'title', 'style', 'clear' ),
1338
1339                         # 9.3.4
1340                         'pre'        => array_merge( $common, array( 'width' ) ),
1341
1342                         # 9.4
1343                         'ins'        => array_merge( $common, array( 'cite', 'datetime' ) ),
1344                         'del'        => array_merge( $common, array( 'cite', 'datetime' ) ),
1345
1346                         # 10.2
1347                         'ul'         => array_merge( $common, array( 'type' ) ),
1348                         'ol'         => array_merge( $common, array( 'type', 'start' ) ),
1349                         'li'         => array_merge( $common, array( 'type', 'value' ) ),
1350
1351                         # 10.3
1352                         'dl'         => $common,
1353                         'dd'         => $common,
1354                         'dt'         => $common,
1355
1356                         # 11.2.1
1357                         'table'      => array_merge( $common,
1358                                                                 array( 'summary', 'width', 'border', 'frame',
1359                                                                                 'rules', 'cellspacing', 'cellpadding',
1360                                                                                 'align', 'bgcolor',
1361                                                                 ) ),
1362
1363                         # 11.2.2
1364                         'caption'    => array_merge( $common, array( 'align' ) ),
1365
1366                         # 11.2.3
1367                         'thead'      => array_merge( $common, $tablealign ),
1368                         'tfoot'      => array_merge( $common, $tablealign ),
1369                         'tbody'      => array_merge( $common, $tablealign ),
1370
1371                         # 11.2.4
1372                         'colgroup'   => array_merge( $common, array( 'span', 'width' ), $tablealign ),
1373                         'col'        => array_merge( $common, array( 'span', 'width' ), $tablealign ),
1374
1375                         # 11.2.5
1376                         'tr'         => array_merge( $common, array( 'bgcolor' ), $tablealign ),
1377
1378                         # 11.2.6
1379                         'td'         => array_merge( $common, $tablecell, $tablealign ),
1380                         'th'         => array_merge( $common, $tablecell, $tablealign ),
1381
1382                         # 12.2 # NOTE: <a> is not allowed directly, but the attrib whitelist is used from the Parser object
1383                         'a'          => array_merge( $common, array( 'href', 'rel', 'rev' ) ), # rel/rev esp. for RDFa 
1384
1385                         # 13.2
1386                         # Not usually allowed, but may be used for extension-style hooks
1387                         # such as <math> when it is rasterized
1388                         'img'        => array_merge( $common, array( 'alt' ) ),
1389
1390                         # 15.2.1
1391                         'tt'         => $common,
1392                         'b'          => $common,
1393                         'i'          => $common,
1394                         'big'        => $common,
1395                         'small'      => $common,
1396                         'strike'     => $common,
1397                         's'          => $common,
1398                         'u'          => $common,
1399
1400                         # 15.2.2
1401                         'font'       => array_merge( $common, array( 'size', 'color', 'face' ) ),
1402                         # basefont
1403
1404                         # 15.3
1405                         'hr'         => array_merge( $common, array( 'noshade', 'size', 'width' ) ),
1406
1407                         # XHTML Ruby annotation text module, simple ruby only.
1408                         # http://www.w3c.org/TR/ruby/
1409                         'ruby'       => $common,
1410                         # rbc
1411                         # rtc
1412                         'rb'         => $common,
1413                         'rt'         => $common, #array_merge( $common, array( 'rbspan' ) ),
1414                         'rp'         => $common,
1415
1416                         # MathML root element, where used for extensions
1417                         # 'title' may not be 100% valid here; it's XHTML
1418                         # http://www.w3.org/TR/REC-MathML/
1419                         'math'       => array( 'class', 'style', 'id', 'title' ),
1420                         );
1421                 return $whitelist;
1422         }
1423
1424         /**
1425          * Take a fragment of (potentially invalid) HTML and return
1426          * a version with any tags removed, encoded as plain text.
1427          *
1428          * Warning: this return value must be further escaped for literal
1429          * inclusion in HTML output as of 1.10!
1430          *
1431          * @param $text String: HTML fragment
1432          * @return String
1433          */
1434         static function stripAllTags( $text ) {
1435                 # Actual <tags>
1436                 $text = StringUtils::delimiterReplace( '<', '>', '', $text );
1437
1438                 # Normalize &entities and whitespace
1439                 $text = self::decodeCharReferences( $text );
1440                 $text = self::normalizeWhitespace( $text );
1441
1442                 return $text;
1443         }
1444
1445         /**
1446          * Hack up a private DOCTYPE with HTML's standard entity declarations.
1447          * PHP 4 seemed to know these if you gave it an HTML doctype, but
1448          * PHP 5.1 doesn't.
1449          *
1450          * Use for passing XHTML fragments to PHP's XML parsing functions
1451          *
1452          * @return String
1453          */
1454         static function hackDocType() {
1455                 global $wgHtmlEntities;
1456                 $out = "<!DOCTYPE html [\n";
1457                 foreach( $wgHtmlEntities as $entity => $codepoint ) {
1458                         $out .= "<!ENTITY $entity \"&#$codepoint;\">";
1459                 }
1460                 $out .= "]>\n";
1461                 return $out;
1462         }
1463
1464         static function cleanUrl( $url ) {
1465                 # Normalize any HTML entities in input. They will be
1466                 # re-escaped by makeExternalLink().
1467                 $url = Sanitizer::decodeCharReferences( $url );
1468
1469                 # Escape any control characters introduced by the above step
1470                 $url = preg_replace( '/[\][<>"\\x00-\\x20\\x7F]/e', "urlencode('\\0')", $url );
1471
1472                 # Validate hostname portion
1473                 $matches = array();
1474                 if( preg_match( '!^([^:]+:)(//[^/]+)?(.*)$!iD', $url, $matches ) ) {
1475                         list( /* $whole */, $protocol, $host, $rest ) = $matches;
1476
1477                         // Characters that will be ignored in IDNs.
1478                         // http://tools.ietf.org/html/3454#section-3.1
1479                         // Strip them before further processing so blacklists and such work.
1480                         $strip = "/
1481                                 \\s|          # general whitespace
1482                                 \xc2\xad|     # 00ad SOFT HYPHEN
1483                                 \xe1\xa0\x86| # 1806 MONGOLIAN TODO SOFT HYPHEN
1484                                 \xe2\x80\x8b| # 200b ZERO WIDTH SPACE
1485                                 \xe2\x81\xa0| # 2060 WORD JOINER
1486                                 \xef\xbb\xbf| # feff ZERO WIDTH NO-BREAK SPACE
1487                                 \xcd\x8f|     # 034f COMBINING GRAPHEME JOINER
1488                                 \xe1\xa0\x8b| # 180b MONGOLIAN FREE VARIATION SELECTOR ONE
1489                                 \xe1\xa0\x8c| # 180c MONGOLIAN FREE VARIATION SELECTOR TWO
1490                                 \xe1\xa0\x8d| # 180d MONGOLIAN FREE VARIATION SELECTOR THREE
1491                                 \xe2\x80\x8c| # 200c ZERO WIDTH NON-JOINER
1492                                 \xe2\x80\x8d| # 200d ZERO WIDTH JOINER
1493                                 [\xef\xb8\x80-\xef\xb8\x8f] # fe00-fe00f VARIATION SELECTOR-1-16
1494                                 /xuD";
1495
1496                         $host = preg_replace( $strip, '', $host );
1497
1498                         // @todo Fixme: validate hostnames here
1499
1500                         return $protocol . $host . $rest;
1501                 } else {
1502                         return $url;
1503                 }
1504         }
1505
1506 }