* Replace wfMungeToUtf8 and do_html_entity_decode with a single function
[lhc/web/wiklou.git] / includes / Sanitizer.php
1 <?php
2
3 /**
4 * (X)HTML sanitizer for MediaWiki
5 *
6 * Copyright (C) 2002-2005 Brion Vibber <brion@pobox.com> et al
7 * http://www.mediawiki.org/
8 *
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
22 * http://www.gnu.org/copyleft/gpl.html
23 *
24 * @package MediaWiki
25 * @subpackage Parser
26 */
27
28 /**
29 * Regular expression to match various types of character references in
30 * Sanitizer::normalizeCharReferences and Sanitizer::decodeCharReferences
31 */
32 define( 'MW_CHAR_REFS_REGEX',
33 '/&([A-Za-z0-9]+);
34 |&\#([0-9]+);
35 |&\#x([0-9A-Za-z]+);
36 |&\#X([0-9A-Za-z]+);
37 |(&)/x' );
38
39 /**
40 * List of all named character entities defined in HTML 4.01
41 * http://www.w3.org/TR/html4/sgml/entities.html
42 * @access private
43 */
44 global $wgHtmlEntities;
45 $wgHtmlEntities = array(
46 'Aacute' => 193,
47 'aacute' => 225,
48 'Acirc' => 194,
49 'acirc' => 226,
50 'acute' => 180,
51 'AElig' => 198,
52 'aelig' => 230,
53 'Agrave' => 192,
54 'agrave' => 224,
55 'alefsym' => 8501,
56 'Alpha' => 913,
57 'alpha' => 945,
58 'amp' => 38,
59 'and' => 8743,
60 'ang' => 8736,
61 'Aring' => 197,
62 'aring' => 229,
63 'asymp' => 8776,
64 'Atilde' => 195,
65 'atilde' => 227,
66 'Auml' => 196,
67 'auml' => 228,
68 'bdquo' => 8222,
69 'Beta' => 914,
70 'beta' => 946,
71 'brvbar' => 166,
72 'bull' => 8226,
73 'cap' => 8745,
74 'Ccedil' => 199,
75 'ccedil' => 231,
76 'cedil' => 184,
77 'cent' => 162,
78 'Chi' => 935,
79 'chi' => 967,
80 'circ' => 710,
81 'clubs' => 9827,
82 'cong' => 8773,
83 'copy' => 169,
84 'crarr' => 8629,
85 'cup' => 8746,
86 'curren' => 164,
87 'dagger' => 8224,
88 'Dagger' => 8225,
89 'darr' => 8595,
90 'dArr' => 8659,
91 'deg' => 176,
92 'Delta' => 916,
93 'delta' => 948,
94 'diams' => 9830,
95 'divide' => 247,
96 'Eacute' => 201,
97 'eacute' => 233,
98 'Ecirc' => 202,
99 'ecirc' => 234,
100 'Egrave' => 200,
101 'egrave' => 232,
102 'empty' => 8709,
103 'emsp' => 8195,
104 'ensp' => 8194,
105 'Epsilon' => 917,
106 'epsilon' => 949,
107 'equiv' => 8801,
108 'Eta' => 919,
109 'eta' => 951,
110 'ETH' => 208,
111 'eth' => 240,
112 'Euml' => 203,
113 'euml' => 235,
114 'euro' => 8364,
115 'exist' => 8707,
116 'fnof' => 402,
117 'forall' => 8704,
118 'frac12' => 189,
119 'frac14' => 188,
120 'frac34' => 190,
121 'frasl' => 8260,
122 'Gamma' => 915,
123 'gamma' => 947,
124 'ge' => 8805,
125 'gt' => 62,
126 'harr' => 8596,
127 'hArr' => 8660,
128 'hearts' => 9829,
129 'hellip' => 8230,
130 'Iacute' => 205,
131 'iacute' => 237,
132 'Icirc' => 206,
133 'icirc' => 238,
134 'iexcl' => 161,
135 'Igrave' => 204,
136 'igrave' => 236,
137 'image' => 8465,
138 'infin' => 8734,
139 'int' => 8747,
140 'Iota' => 921,
141 'iota' => 953,
142 'iquest' => 191,
143 'isin' => 8712,
144 'Iuml' => 207,
145 'iuml' => 239,
146 'Kappa' => 922,
147 'kappa' => 954,
148 'Lambda' => 923,
149 'lambda' => 955,
150 'lang' => 9001,
151 'laquo' => 171,
152 'larr' => 8592,
153 'lArr' => 8656,
154 'lceil' => 8968,
155 'ldquo' => 8220,
156 'le' => 8804,
157 'lfloor' => 8970,
158 'lowast' => 8727,
159 'loz' => 9674,
160 'lrm' => 8206,
161 'lsaquo' => 8249,
162 'lsquo' => 8216,
163 'lt' => 60,
164 'macr' => 175,
165 'mdash' => 8212,
166 'micro' => 181,
167 'middot' => 183,
168 'minus' => 8722,
169 'Mu' => 924,
170 'mu' => 956,
171 'nabla' => 8711,
172 'nbsp' => 160,
173 'ndash' => 8211,
174 'ne' => 8800,
175 'ni' => 8715,
176 'not' => 172,
177 'notin' => 8713,
178 'nsub' => 8836,
179 'Ntilde' => 209,
180 'ntilde' => 241,
181 'Nu' => 925,
182 'nu' => 957,
183 'Oacute' => 211,
184 'oacute' => 243,
185 'Ocirc' => 212,
186 'ocirc' => 244,
187 'OElig' => 338,
188 'oelig' => 339,
189 'Ograve' => 210,
190 'ograve' => 242,
191 'oline' => 8254,
192 'Omega' => 937,
193 'omega' => 969,
194 'Omicron' => 927,
195 'omicron' => 959,
196 'oplus' => 8853,
197 'or' => 8744,
198 'ordf' => 170,
199 'ordm' => 186,
200 'Oslash' => 216,
201 'oslash' => 248,
202 'Otilde' => 213,
203 'otilde' => 245,
204 'otimes' => 8855,
205 'Ouml' => 214,
206 'ouml' => 246,
207 'para' => 182,
208 'part' => 8706,
209 'permil' => 8240,
210 'perp' => 8869,
211 'Phi' => 934,
212 'phi' => 966,
213 'Pi' => 928,
214 'pi' => 960,
215 'piv' => 982,
216 'plusmn' => 177,
217 'pound' => 163,
218 'prime' => 8242,
219 'Prime' => 8243,
220 'prod' => 8719,
221 'prop' => 8733,
222 'Psi' => 936,
223 'psi' => 968,
224 'quot' => 34,
225 'radic' => 8730,
226 'rang' => 9002,
227 'raquo' => 187,
228 'rarr' => 8594,
229 'rArr' => 8658,
230 'rceil' => 8969,
231 'rdquo' => 8221,
232 'real' => 8476,
233 'reg' => 174,
234 'rfloor' => 8971,
235 'Rho' => 929,
236 'rho' => 961,
237 'rlm' => 8207,
238 'rsaquo' => 8250,
239 'rsquo' => 8217,
240 'sbquo' => 8218,
241 'Scaron' => 352,
242 'scaron' => 353,
243 'sdot' => 8901,
244 'sect' => 167,
245 'shy' => 173,
246 'Sigma' => 931,
247 'sigma' => 963,
248 'sigmaf' => 962,
249 'sim' => 8764,
250 'spades' => 9824,
251 'sub' => 8834,
252 'sube' => 8838,
253 'sum' => 8721,
254 'sup' => 8835,
255 'sup1' => 185,
256 'sup2' => 178,
257 'sup3' => 179,
258 'supe' => 8839,
259 'szlig' => 223,
260 'Tau' => 932,
261 'tau' => 964,
262 'there4' => 8756,
263 'Theta' => 920,
264 'theta' => 952,
265 'thetasym' => 977,
266 'thinsp' => 8201,
267 'THORN' => 222,
268 'thorn' => 254,
269 'tilde' => 732,
270 'times' => 215,
271 'trade' => 8482,
272 'Uacute' => 218,
273 'uacute' => 250,
274 'uarr' => 8593,
275 'uArr' => 8657,
276 'Ucirc' => 219,
277 'ucirc' => 251,
278 'Ugrave' => 217,
279 'ugrave' => 249,
280 'uml' => 168,
281 'upsih' => 978,
282 'Upsilon' => 933,
283 'upsilon' => 965,
284 'Uuml' => 220,
285 'uuml' => 252,
286 'weierp' => 8472,
287 'Xi' => 926,
288 'xi' => 958,
289 'Yacute' => 221,
290 'yacute' => 253,
291 'yen' => 165,
292 'Yuml' => 376,
293 'yuml' => 255,
294 'Zeta' => 918,
295 'zeta' => 950,
296 'zwj' => 8205,
297 'zwnj' => 8204 );
298
299 class Sanitizer {
300 /**
301 * Cleans up HTML, removes dangerous tags and attributes, and
302 * removes HTML comments
303 * @access private
304 * @param string $text
305 * @return string
306 */
307 function removeHTMLtags( $text ) {
308 global $wgUseTidy, $wgUserHtml;
309 $fname = 'Parser::removeHTMLtags';
310 wfProfileIn( $fname );
311
312 if( $wgUserHtml ) {
313 $htmlpairs = array( # Tags that must be closed
314 'b', 'del', 'i', 'ins', 'u', 'font', 'big', 'small', 'sub', 'sup', 'h1',
315 'h2', 'h3', 'h4', 'h5', 'h6', 'cite', 'code', 'em', 's',
316 'strike', 'strong', 'tt', 'var', 'div', 'center',
317 'blockquote', 'ol', 'ul', 'dl', 'table', 'caption', 'pre',
318 'ruby', 'rt' , 'rb' , 'rp', 'p', 'span'
319 );
320 $htmlsingle = array(
321 'br', 'hr', 'li', 'dt', 'dd'
322 );
323 $htmlnest = array( # Tags that can be nested--??
324 'table', 'tr', 'td', 'th', 'div', 'blockquote', 'ol', 'ul',
325 'dl', 'font', 'big', 'small', 'sub', 'sup', 'span'
326 );
327 $tabletags = array( # Can only appear inside table
328 'td', 'th', 'tr'
329 );
330 } else {
331 $htmlpairs = array();
332 $htmlsingle = array();
333 $htmlnest = array();
334 $tabletags = array();
335 }
336
337 $htmlsingle = array_merge( $tabletags, $htmlsingle );
338 $htmlelements = array_merge( $htmlsingle, $htmlpairs );
339
340 # Remove HTML comments
341 $text = Sanitizer::removeHTMLcomments( $text );
342
343 $bits = explode( '<', $text );
344 $text = array_shift( $bits );
345 if(!$wgUseTidy) {
346 $tagstack = array(); $tablestack = array();
347 foreach ( $bits as $x ) {
348 $prev = error_reporting( E_ALL & ~( E_NOTICE | E_WARNING ) );
349 preg_match( '/^(\\/?)(\\w+)([^>]*)(\\/{0,1}>)([^<]*)$/',
350 $x, $regs );
351 list( $qbar, $slash, $t, $params, $brace, $rest ) = $regs;
352 error_reporting( $prev );
353
354 $badtag = 0 ;
355 if ( in_array( $t = strtolower( $t ), $htmlelements ) ) {
356 # Check our stack
357 if ( $slash ) {
358 # Closing a tag...
359 if ( ! in_array( $t, $htmlsingle ) &&
360 ( $ot = @array_pop( $tagstack ) ) != $t ) {
361 @array_push( $tagstack, $ot );
362 $badtag = 1;
363 } else {
364 if ( $t == 'table' ) {
365 $tagstack = array_pop( $tablestack );
366 }
367 $newparams = '';
368 }
369 } else {
370 # Keep track for later
371 if ( in_array( $t, $tabletags ) &&
372 ! in_array( 'table', $tagstack ) ) {
373 $badtag = 1;
374 } else if ( in_array( $t, $tagstack ) &&
375 ! in_array ( $t , $htmlnest ) ) {
376 $badtag = 1 ;
377 } else if ( ! in_array( $t, $htmlsingle ) ) {
378 if ( $t == 'table' ) {
379 array_push( $tablestack, $tagstack );
380 $tagstack = array();
381 }
382 array_push( $tagstack, $t );
383 }
384 # Strip non-approved attributes from the tag
385 $newparams = Sanitizer::fixTagAttributes( $params, $t );
386 }
387 if ( ! $badtag ) {
388 $rest = str_replace( '>', '&gt;', $rest );
389 $text .= "<$slash$t$newparams$brace$rest";
390 continue;
391 }
392 }
393 $text .= '&lt;' . str_replace( '>', '&gt;', $x);
394 }
395 # Close off any remaining tags
396 while ( is_array( $tagstack ) && ($t = array_pop( $tagstack )) ) {
397 $text .= "</$t>\n";
398 if ( $t == 'table' ) { $tagstack = array_pop( $tablestack ); }
399 }
400 } else {
401 # this might be possible using tidy itself
402 foreach ( $bits as $x ) {
403 preg_match( '/^(\\/?)(\\w+)([^>]*)(\\/{0,1}>)([^<]*)$/',
404 $x, $regs );
405 @list( $qbar, $slash, $t, $params, $brace, $rest ) = $regs;
406 if ( in_array( $t = strtolower( $t ), $htmlelements ) ) {
407 $newparams = Sanitizer::fixTagAttributes( $params, $t );
408 $rest = str_replace( '>', '&gt;', $rest );
409 $text .= "<$slash$t$newparams$brace$rest";
410 } else {
411 $text .= '&lt;' . str_replace( '>', '&gt;', $x);
412 }
413 }
414 }
415 wfProfileOut( $fname );
416 return $text;
417 }
418
419 /**
420 * Remove '<!--', '-->', and everything between.
421 * To avoid leaving blank lines, when a comment is both preceded
422 * and followed by a newline (ignoring spaces), trim leading and
423 * trailing spaces and one of the newlines.
424 *
425 * @access private
426 * @param string $text
427 * @return string
428 */
429 function removeHTMLcomments( $text ) {
430 $fname='Parser::removeHTMLcomments';
431 wfProfileIn( $fname );
432 while (($start = strpos($text, '<!--')) !== false) {
433 $end = strpos($text, '-->', $start + 4);
434 if ($end === false) {
435 # Unterminated comment; bail out
436 break;
437 }
438
439 $end += 3;
440
441 # Trim space and newline if the comment is both
442 # preceded and followed by a newline
443 $spaceStart = max($start - 1, 0);
444 $spaceLen = $end - $spaceStart;
445 while (substr($text, $spaceStart, 1) === ' ' && $spaceStart > 0) {
446 $spaceStart--;
447 $spaceLen++;
448 }
449 while (substr($text, $spaceStart + $spaceLen, 1) === ' ')
450 $spaceLen++;
451 if (substr($text, $spaceStart, 1) === "\n" and substr($text, $spaceStart + $spaceLen, 1) === "\n") {
452 # Remove the comment, leading and trailing
453 # spaces, and leave only one newline.
454 $text = substr_replace($text, "\n", $spaceStart, $spaceLen + 1);
455 }
456 else {
457 # Remove just the comment.
458 $text = substr_replace($text, '', $start, $end - $start);
459 }
460 }
461 wfProfileOut( $fname );
462 return $text;
463 }
464
465 /**
466 * Take a tag soup fragment listing an HTML element's attributes
467 * and normalize it to well-formed XML, discarding unwanted attributes.
468 *
469 * - Normalizes attribute names to lowercase
470 * - Discards attributes not on a whitelist for the given element
471 * - Turns broken or invalid entities into plaintext
472 * - Double-quotes all attribute values
473 * - Attributes without values are given the name as attribute
474 * - Double attributes are discarded
475 * - Unsafe style attributes are discarded
476 * - Prepends space if there are attributes.
477 *
478 * @param string $text
479 * @param string $element
480 * @return string
481 *
482 * @todo Check for legal values where the DTD limits things.
483 * @todo Check for unique id attribute :P
484 */
485 function fixTagAttributes( $text, $element ) {
486 if( trim( $text ) == '' ) {
487 return '';
488 }
489
490 # Unquoted attribute
491 # Since we quote this later, this can be anything distinguishable
492 # from the end of the attribute
493 $attrib = '[A-Za-z0-9]';
494 $space = '[\x09\x0a\x0d\x20]';
495 if( !preg_match_all(
496 "/(?:^|$space)($attrib+)
497 ($space*=$space*
498 (?:
499 # The attribute value: quoted or alone
500 \"([^<\"]*)\"
501 | '([^<']*)'
502 | ([a-zA-Z0-9!#$%&()*,\\-.\\/:;<>?@[\\]^_`{|}~]+)
503 | (\#[0-9a-fA-F]+) # Technically wrong, but lots of
504 # colors are specified like this.
505 # We'll be normalizing it.
506 )
507 )?(?=$space|\$)/sx",
508 $text,
509 $pairs,
510 PREG_SET_ORDER ) ) {
511 return '';
512 }
513
514 $whitelist = array_flip( Sanitizer::attributeWhitelist( $element ) );
515 $attribs = array();
516 foreach( $pairs as $set ) {
517 $attribute = strtolower( $set[1] );
518 if( !isset( $whitelist[$attribute] ) ) {
519 continue;
520 } elseif( isset( $set[6] ) ) {
521 # Illegal #XXXXXX color with no quotes.
522 $value = Sanitizer::normalizeAttributeValue( $set[6] );
523 } elseif( isset( $set[5] ) ) {
524 # No quotes.
525 $value = Sanitizer::normalizeAttributeValue( $set[5] );
526 } elseif( isset( $set[4] ) ) {
527 # Single-quoted
528 $value = str_replace( '"', '&quot;',
529 Sanitizer::normalizeAttributeValue( $set[4] ) );
530 } elseif( isset( $set[3] ) ) {
531 # Double-quoted
532 $value = Sanitizer::normalizeAttributeValue( $set[3] );
533 } elseif( !isset( $set[2] ) ) {
534 # In XHTML, attributes must have a value.
535 $value = $set[1];
536 } else {
537 wfDebugDieBacktrace( "Tag conditions not met. This should never happen and is a bug." );
538 }
539
540 # Strip javascript "expression" from stylesheets.
541 # http://msdn.microsoft.com/workshop/author/dhtml/overview/recalc.asp
542 if( $attribute == 'style' && preg_match(
543 '/(expression|tps*:\/\/|url\\s*\().*/is',
544 Sanitizer::decodeCharReferences( $value ) ) ) {
545 # haxx0r
546 continue;
547 }
548
549 if( !isset( $attribs[$attribute] ) ) {
550 $attribs[$attribute] = "$attribute=\"$value\"";
551 }
552 }
553 if( empty( $attribs ) ) {
554 return '';
555 } else {
556 return ' ' . implode( ' ', $attribs );
557 }
558 }
559
560 /**
561 * Normalize whitespace and character references in an XML source-
562 * encoded text for an attribute value.
563 *
564 * See http://www.w3.org/TR/REC-xml/#AVNormalize for background,
565 * but note that we're not returning the value, but are returning
566 * XML source fragments that will be slapped into output.
567 *
568 * @param string $text
569 * @return string
570 * @access private
571 */
572 function normalizeAttributeValue( $text ) {
573 return preg_replace(
574 '/\r\n|[\x20\x0d\x0a\x09]/',
575 ' ',
576 Sanitizer::normalizeCharReferences( $text ) );
577 }
578
579 /**
580 * Ensure that any entities and character references are legal
581 * for XML and XHTML specifically. Any stray bits will be
582 * &amp;-escaped to result in a valid text fragment.
583 *
584 * a. any named char refs must be known in XHTML
585 * b. any numeric char refs must be legal chars, not invalid or forbidden
586 * c. use &#x, not &#X
587 * d. fix or reject non-valid attributes
588 *
589 * @param string $text
590 * @return string
591 * @access private
592 */
593 function normalizeCharReferences( $text ) {
594 return preg_replace_callback(
595 MW_CHAR_REFS_REGEX,
596 array( 'Sanitizer', 'normalizeCharReferencesCallback' ),
597 $text );
598 }
599 /**
600 * @param string $matches
601 * @return string
602 */
603 function normalizeCharReferencesCallback( $matches ) {
604 $ret = null;
605 if( $matches[1] != '' ) {
606 $ret = Sanitizer::normalizeEntity( $matches[1] );
607 } elseif( $matches[2] != '' ) {
608 $ret = Sanitizer::decCharReference( $matches[2] );
609 } elseif( $matches[3] != '' ) {
610 $ret = Sanitizer::hexCharReference( $matches[3] );
611 } elseif( $matches[4] != '' ) {
612 $ret = Sanitizer::hexCharReference( $matches[4] );
613 }
614 if( is_null( $ret ) ) {
615 return htmlspecialchars( $matches[0] );
616 } else {
617 return $ret;
618 }
619 }
620
621 /**
622 * If the named entity is defined in the HTML 4.0/XHTML 1.0 DTD,
623 * return the named entity reference as is. Otherwise, returns
624 * HTML-escaped text of pseudo-entity source (eg &amp;foo;)
625 *
626 * @param string $name
627 * @return string
628 */
629 function normalizeEntity( $name ) {
630 global $wgHtmlEntities;
631 if( isset( $wgHtmlEntities[$name] ) ) {
632 return "&$name;";
633 } else {
634 return "&amp;$name;";
635 }
636 }
637
638 function decCharReference( $codepoint ) {
639 $point = IntVal( $codepoint );
640 if( Sanitizer::validateCodepoint( $point ) ) {
641 return sprintf( '&#%d;', $point );
642 } else {
643 return null;
644 }
645 }
646
647 function hexCharReference( $codepoint ) {
648 $point = hexdec( $codepoint );
649 if( Sanitizer::validateCodepoint( $point ) ) {
650 return sprintf( '&#x%x;', $point );
651 } else {
652 return null;
653 }
654 }
655
656 /**
657 * Returns true if a given Unicode codepoint is a valid character in XML.
658 * @param int $codepoint
659 * @return bool
660 */
661 function validateCodepoint( $codepoint ) {
662 return ($codepoint == 0x09)
663 || ($codepoint == 0x0a)
664 || ($codepoint == 0x0d)
665 || ($codepoint >= 0x20 && $codepoint <= 0xd7ff)
666 || ($codepoint >= 0xe000 && $codepoint <= 0xfffd)
667 || ($codepoint >= 0x10000 && $codepoint <= 0x10ffff);
668 }
669
670 /**
671 * Decode any character references, numeric or named entities,
672 * in the text and return a UTF-8 string.
673 *
674 * @param string $text
675 * @return string
676 * @access public
677 */
678 function decodeCharReferences( $text ) {
679 return preg_replace_callback(
680 MW_CHAR_REFS_REGEX,
681 array( 'Sanitizer', 'decodeCharReferencesCallback' ),
682 $text );
683 }
684
685 /**
686 * @param string $matches
687 * @return string
688 */
689 function decodeCharReferencesCallback( $matches ) {
690 if( $matches[1] != '' ) {
691 return Sanitizer::decodeEntity( $matches[1] );
692 } elseif( $matches[2] != '' ) {
693 return Sanitizer::decodeChar( intval( $matches[2] ) );
694 } elseif( $matches[3] != '' ) {
695 return Sanitizer::decodeChar( hexdec( $matches[3] ) );
696 } elseif( $matches[4] != '' ) {
697 return Sanitizer::decodeChar( hexdec( $matches[4] ) );
698 }
699 # Last case should be an ampersand by itself
700 return $matches[0];
701 }
702
703 /**
704 * Return UTF-8 string for a codepoint if that is a valid
705 * character reference, otherwise U+FFFD REPLACEMENT CHARACTER.
706 * @param int $codepoint
707 * @return string
708 * @access private
709 */
710 function decodeChar( $codepoint ) {
711 if( Sanitizer::validateCodepoint( $codepoint ) ) {
712 return codepointToUtf8( $codepoint );
713 } else {
714 return UTF8_REPLACEMENT;
715 }
716 }
717
718 /**
719 * If the named entity is defined in the HTML 4.0/XHTML 1.0 DTD,
720 * return the UTF-8 encoding of that character. Otherwise, returns
721 * pseudo-entity source (eg &foo;)
722 *
723 * @param string $name
724 * @return string
725 */
726 function decodeEntity( $name ) {
727 global $wgHtmlEntities;
728 if( isset( $wgHtmlEntities[$name] ) ) {
729 return codepointToUtf8( $wgHtmlEntities[$name] );
730 } else {
731 return "&$name;";
732 }
733 }
734
735 /**
736 * Fetch the whitelist of acceptable attributes for a given
737 * element name.
738 *
739 * @param string $element
740 * @return array
741 */
742 function attributeWhitelist( $element ) {
743 static $list;
744 if( !isset( $list ) ) {
745 $list = Sanitizer::setupAttributeWhitelist();
746 }
747 return isset( $list[$element] )
748 ? $list[$element]
749 : array();
750 }
751
752 /**
753 * @return array
754 */
755 function setupAttributeWhitelist() {
756 $common = array( 'id', 'class', 'lang', 'dir', 'title', 'style' );
757 $block = array_merge( $common, array( 'align' ) );
758 $tablealign = array( 'align', 'char', 'charoff', 'valign' );
759 $tablecell = array( 'abbr',
760 'axis',
761 'headers',
762 'scope',
763 'rowspan',
764 'colspan',
765 'nowrap', # deprecated
766 'width', # deprecated
767 'height', # deprecated
768 'bgcolor' # deprecated
769 );
770
771 # Numbers refer to sections in HTML 4.01 standard describing the element.
772 # See: http://www.w3.org/TR/html4/
773 $whitelist = array (
774 # 7.5.4
775 'div' => $block,
776 'center' => $common, # deprecated
777 'span' => $block, # ??
778
779 # 7.5.5
780 'h1' => $block,
781 'h2' => $block,
782 'h3' => $block,
783 'h4' => $block,
784 'h5' => $block,
785 'h6' => $block,
786
787 # 7.5.6
788 # address
789
790 # 8.2.4
791 # bdo
792
793 # 9.2.1
794 'em' => $common,
795 'strong' => $common,
796 'cite' => $common,
797 # dfn
798 'code' => $common,
799 # samp
800 # kbd
801 'var' => $common,
802 # abbr
803 # acronym
804
805 # 9.2.2
806 'blockquote' => array_merge( $common, array( 'cite' ) ),
807 # q
808
809 # 9.2.3
810 'sub' => $common,
811 'sup' => $common,
812
813 # 9.3.1
814 'p' => $block,
815
816 # 9.3.2
817 'br' => array( 'id', 'class', 'title', 'style', 'clear' ),
818
819 # 9.3.4
820 'pre' => array_merge( $common, array( 'width' ) ),
821
822 # 9.4
823 'ins' => array_merge( $common, array( 'cite', 'datetime' ) ),
824 'del' => array_merge( $common, array( 'cite', 'datetime' ) ),
825
826 # 10.2
827 'ul' => array_merge( $common, array( 'type' ) ),
828 'ol' => array_merge( $common, array( 'type', 'start' ) ),
829 'li' => array_merge( $common, array( 'type', 'value' ) ),
830
831 # 10.3
832 'dl' => $common,
833 'dd' => $common,
834 'dt' => $common,
835
836 # 11.2.1
837 'table' => array_merge( $common,
838 array( 'summary', 'width', 'border', 'frame',
839 'rules', 'cellspacing', 'cellpadding',
840 'align', 'bgcolor', 'frame', 'rules',
841 'border' ) ),
842
843 # 11.2.2
844 'caption' => array_merge( $common, array( 'align' ) ),
845
846 # 11.2.3
847 'thead' => array_merge( $common, $tablealign ),
848 'tfoot' => array_merge( $common, $tablealign ),
849 'tbody' => array_merge( $common, $tablealign ),
850
851 # 11.2.4
852 'colgroup' => array_merge( $common, array( 'span', 'width' ), $tablealign ),
853 'col' => array_merge( $common, array( 'span', 'width' ), $tablealign ),
854
855 # 11.2.5
856 'tr' => array_merge( $common, array( 'bgcolor' ), $tablealign ),
857
858 # 11.2.6
859 'td' => array_merge( $common, $tablecell, $tablealign ),
860 'th' => array_merge( $common, $tablecell, $tablealign ),
861
862 # 15.2.1
863 'tt' => $common,
864 'b' => $common,
865 'i' => $common,
866 'big' => $common,
867 'small' => $common,
868 'strike' => $common,
869 's' => $common,
870 'u' => $common,
871
872 # 15.2.2
873 'font' => array_merge( $common, array( 'size', 'color', 'face' ) ),
874 # basefont
875
876 # 15.3
877 'hr' => array_merge( $common, array( 'noshade', 'size', 'width' ) ),
878
879 # XHTML Ruby annotation text module, simple ruby only.
880 # http://www.w3c.org/TR/ruby/
881 'ruby' => $common,
882 # rbc
883 # rtc
884 'rb' => $common,
885 'rt' => $common, #array_merge( $common, array( 'rbspan' ) ),
886 'rp' => $common,
887 );
888 return $whitelist;
889 }
890
891 /**
892 * Take a fragment of (potentially invalid) HTML and return
893 * a version with any tags removed, encoded suitably for literal
894 * inclusion in an attribute value.
895 *
896 * @param string $text HTML fragment
897 * @return string
898 */
899 function stripAllTags( $text ) {
900 # Actual <tags>
901 $text = preg_replace( '/<[^>]*>/', '', $text );
902
903 # Normalize &entities and whitespace
904 $text = Sanitizer::normalizeAttributeValue( $text );
905
906 # Will be placed into "double-quoted" attributes,
907 # make sure remaining bits are safe.
908 $text = str_replace(
909 array('<', '>', '"'),
910 array('&lt;', '&gt;', '&quot;'),
911 $text );
912
913 return $text;
914 }
915
916 }
917
918 ?>