3 * XHTML sanitizer for MediaWiki
5 * Copyright © 2002-2005 Brion Vibber <brion@pobox.com> et al
6 * http://www.mediawiki.org/
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
28 * Regular expression to match various types of character references in
29 * Sanitizer::normalizeCharReferences and Sanitizer::decodeCharReferences
31 define( 'MW_CHAR_REFS_REGEX',
32 '/&([A-Za-z0-9\x80-\xff]+);
39 * Regular expression to match HTML/XML attribute pairs within a tag.
40 * Allows some... latitude.
41 * Used in Sanitizer::fixTagAttributes and Sanitizer::decodeTagAttributes
43 $attrib_first = '[:A-Z_a-z]';
44 $attrib = '[:A-Z_a-z-.0-9]';
45 $space = '[\x09\x0a\x0d\x20]';
46 define( 'MW_ATTRIBS_REGEX',
47 "/(?:^|$space)({$attrib_first}{$attrib}*)
50 # The attribute value: quoted or alone
53 | ([a-zA-Z0-9!#$%&()*,\\-.\\/:;<>?@[\\]^_`{|}~]+)
54 | (\#[0-9a-fA-F]+) # Technically wrong, but lots of
55 # colors are specified like this.
56 # We'll be normalizing it.
58 )?(?=$space|\$)/sx" );
61 * Regular expression to match URIs that could trigger script execution
63 define( 'MW_EVIL_URI_PATTERN', '!(^|\s|\*/\s*)(javascript|vbscript)([^\w]|$)!i' );
66 * Regular expression to match namespace attributes
68 define( 'MW_XMLNS_ATTRIBUTE_PATTRN', "/^xmlns:$attrib+$/" );
71 * List of all named character entities defined in HTML 4.01
72 * http://www.w3.org/TR/html4/sgml/entities.html
75 global $wgHtmlEntities;
76 $wgHtmlEntities = array(
331 * Character entity aliases accepted by MediaWiki
333 global $wgHtmlEntityAliases;
334 $wgHtmlEntityAliases = array(
341 * XHTML sanitizer for MediaWiki
346 * Cleans up HTML, removes dangerous tags and attributes, and
347 * removes HTML comments
349 * @param $text String
350 * @param $processCallback Callback to do any variable or parameter replacements in HTML attribute values
351 * @param $args Array for the processing callback
352 * @param $extratags Array for any extra tags to include
353 * @param $removetags Array for any tags (default or extra) to exclude
356 static function removeHTMLtags( $text, $processCallback = null, $args = array(), $extratags = array(), $removetags = array() ) {
359 static $htmlpairsStatic, $htmlsingle, $htmlsingleonly, $htmlnest, $tabletags,
360 $htmllist, $listtags, $htmlsingleallowed, $htmlelementsStatic, $staticInitialised;
362 wfProfileIn( __METHOD__
);
364 if ( !$staticInitialised ) {
366 $htmlpairsStatic = array( # Tags that must be closed
367 'b', 'del', 'i', 'ins', 'u', 'font', 'big', 'small', 'sub', 'sup', 'h1',
368 'h2', 'h3', 'h4', 'h5', 'h6', 'cite', 'code', 'em', 's',
369 'strike', 'strong', 'tt', 'var', 'div', 'center',
370 'blockquote', 'ol', 'ul', 'dl', 'table', 'caption', 'pre',
371 'ruby', 'rt' , 'rb' , 'rp', 'p', 'span', 'u', 'abbr', 'dfn',
375 'br', 'hr', 'li', 'dt', 'dd'
377 $htmlsingleonly = array( # Elements that cannot have close tags
380 $htmlnest = array( # Tags that can be nested--??
381 'table', 'tr', 'td', 'th', 'div', 'blockquote', 'ol', 'ul',
382 'dl', 'font', 'big', 'small', 'sub', 'sup', 'span'
384 $tabletags = array( # Can only appear inside table, we will close them
387 $htmllist = array( # Tags used by list
390 $listtags = array( # Tags that can appear in a list
394 global $wgAllowImageTag;
395 if ( $wgAllowImageTag ) {
396 $htmlsingle[] = 'img';
397 $htmlsingleonly[] = 'img';
400 $htmlsingleallowed = array_unique( array_merge( $htmlsingle, $tabletags ) );
401 $htmlelementsStatic = array_unique( array_merge( $htmlsingle, $htmlpairsStatic, $htmlnest ) );
403 # Convert them all to hashtables for faster lookup
404 $vars = array( 'htmlpairsStatic', 'htmlsingle', 'htmlsingleonly', 'htmlnest', 'tabletags',
405 'htmllist', 'listtags', 'htmlsingleallowed', 'htmlelementsStatic' );
406 foreach ( $vars as $var ) {
407 $
$var = array_flip( $
$var );
409 $staticInitialised = true;
411 # Populate $htmlpairs and $htmlelements with the $extratags and $removetags arrays
412 $extratags = array_flip( $extratags );
413 $removetags = array_flip( $removetags );
414 $htmlpairs = array_merge( $extratags, $htmlpairsStatic );
415 $htmlelements = array_diff_key( array_merge( $extratags, $htmlelementsStatic ) , $removetags );
417 # Remove HTML comments
418 $text = Sanitizer
::removeHTMLcomments( $text );
419 $bits = explode( '<', $text );
420 $text = str_replace( '>', '>', array_shift( $bits ) );
422 $tagstack = $tablestack = array();
423 foreach ( $bits as $x ) {
425 # $slash: Does the current element start with a '/'?
426 # $t: Current element name
427 # $params: String between element name and >
428 # $brace: Ending '>' or '/>'
429 # $rest: Everything until the next element of $bits
430 if( preg_match( '!^(/?)(\\w+)([^>]*?)(/{0,1}>)([^<]*)$!', $x, $regs ) ) {
431 list( /* $qbar */, $slash, $t, $params, $brace, $rest ) = $regs;
433 $slash = $t = $params = $brace = $rest = null;
437 if ( isset( $htmlelements[$t = strtolower( $t )] ) ) {
439 if ( $slash && isset( $htmlsingleonly[$t] ) ) {
441 } elseif ( $slash ) {
442 # Closing a tag... is it the one we just opened?
443 $ot = @array_pop
( $tagstack );
445 if ( isset( $htmlsingleallowed[$ot] ) ) {
446 # Pop all elements with an optional close tag
447 # and see if we find a match below them
449 array_push( $optstack, $ot );
450 $ot = @array_pop
( $tagstack );
451 while ( $ot != $t && isset( $htmlsingleallowed[$ot] ) ) {
452 array_push( $optstack, $ot );
453 $ot = @array_pop
( $tagstack );
456 # No match. Push the optional elements back again
458 while ( $ot = @array_pop
( $optstack ) ) {
459 array_push( $tagstack, $ot );
463 @array_push
( $tagstack, $ot );
464 # <li> can be nested in <ul> or <ol>, skip those cases:
465 if ( !isset( $htmllist[$ot] ) ||
!isset( $listtags[$t] ) ) {
470 if ( $t == 'table' ) {
471 $tagstack = array_pop( $tablestack );
476 # Keep track for later
477 if ( isset( $tabletags[$t] ) &&
478 !in_array( 'table', $tagstack ) ) {
480 } elseif ( in_array( $t, $tagstack ) &&
481 !isset( $htmlnest [$t ] ) ) {
483 # Is it a self closed htmlpair ? (bug 5487)
484 } elseif ( $brace == '/>' &&
485 isset( $htmlpairs[$t] ) ) {
487 } elseif ( isset( $htmlsingleonly[$t] ) ) {
488 # Hack to force empty tag for uncloseable elements
490 } elseif ( isset( $htmlsingle[$t] ) ) {
491 # Hack to not close $htmlsingle tags
493 } elseif ( isset( $tabletags[$t] )
494 && in_array( $t, $tagstack ) ) {
495 // New table tag but forgot to close the previous one
498 if ( $t == 'table' ) {
499 array_push( $tablestack, $tagstack );
502 array_push( $tagstack, $t );
505 # Replace any variables or template parameters with
507 if( is_callable( $processCallback ) ) {
508 call_user_func_array( $processCallback, array( &$params, $args ) );
511 # Strip non-approved attributes from the tag
512 $newparams = Sanitizer
::fixTagAttributes( $params, $t );
515 $rest = str_replace( '>', '>', $rest );
516 $close = ( $brace == '/>' && !$slash ) ?
' /' : '';
517 $text .= "<$slash$t$newparams$close>$rest";
521 $text .= '<' . str_replace( '>', '>', $x);
523 # Close off any remaining tags
524 while ( is_array( $tagstack ) && ($t = array_pop( $tagstack )) ) {
526 if ( $t == 'table' ) { $tagstack = array_pop( $tablestack ); }
529 # this might be possible using tidy itself
530 foreach ( $bits as $x ) {
531 preg_match( '/^(\\/?)(\\w+)([^>]*?)(\\/{0,1}>)([^<]*)$/',
533 @list
( /* $qbar */, $slash, $t, $params, $brace, $rest ) = $regs;
534 if ( isset( $htmlelements[$t = strtolower( $t )] ) ) {
535 if( is_callable( $processCallback ) ) {
536 call_user_func_array( $processCallback, array( &$params, $args ) );
538 $newparams = Sanitizer
::fixTagAttributes( $params, $t );
539 $rest = str_replace( '>', '>', $rest );
540 $text .= "<$slash$t$newparams$brace$rest";
542 $text .= '<' . str_replace( '>', '>', $x);
546 wfProfileOut( __METHOD__
);
551 * Remove '<!--', '-->', and everything between.
552 * To avoid leaving blank lines, when a comment is both preceded
553 * and followed by a newline (ignoring spaces), trim leading and
554 * trailing spaces and one of the newlines.
557 * @param $text String
560 static function removeHTMLcomments( $text ) {
561 wfProfileIn( __METHOD__
);
562 while (($start = strpos($text, '<!--')) !== false) {
563 $end = strpos($text, '-->', $start +
4);
564 if ($end === false) {
565 # Unterminated comment; bail out
571 # Trim space and newline if the comment is both
572 # preceded and followed by a newline
573 $spaceStart = max($start - 1, 0);
574 $spaceLen = $end - $spaceStart;
575 while (substr($text, $spaceStart, 1) === ' ' && $spaceStart > 0) {
579 while (substr($text, $spaceStart +
$spaceLen, 1) === ' ')
581 if (substr($text, $spaceStart, 1) === "\n" and substr($text, $spaceStart +
$spaceLen, 1) === "\n") {
582 # Remove the comment, leading and trailing
583 # spaces, and leave only one newline.
584 $text = substr_replace($text, "\n", $spaceStart, $spaceLen +
1);
587 # Remove just the comment.
588 $text = substr_replace($text, '', $start, $end - $start);
591 wfProfileOut( __METHOD__
);
596 * Take an array of attribute names and values and normalize or discard
597 * illegal values for the given element type.
599 * - Discards attributes not on a whitelist for the given element
600 * - Unsafe style attributes are discarded
601 * - Invalid id attributes are reencoded
603 * @param $attribs Array
604 * @param $element String
607 * @todo Check for legal values where the DTD limits things.
608 * @todo Check for unique id attribute :P
610 static function validateTagAttributes( $attribs, $element ) {
611 return Sanitizer
::validateAttributes( $attribs,
612 Sanitizer
::attributeWhitelist( $element ) );
616 * Take an array of attribute names and values and normalize or discard
617 * illegal values for the given whitelist.
619 * - Discards attributes not the given whitelist
620 * - Unsafe style attributes are discarded
621 * - Invalid id attributes are reencoded
623 * @param $attribs Array
624 * @param $whitelist Array: list of allowed attribute names
627 * @todo Check for legal values where the DTD limits things.
628 * @todo Check for unique id attribute :P
630 static function validateAttributes( $attribs, $whitelist ) {
631 global $wgAllowRdfaAttributes, $wgAllowMicrodataAttributes, $wgHtml5;
633 $whitelist = array_flip( $whitelist );
634 $hrefExp = '/^(' . wfUrlProtocols() . ')[^\s]+$/';
637 foreach( $attribs as $attribute => $value ) {
638 #allow XML namespace declaration if RDFa is enabled
639 if ( $wgAllowRdfaAttributes && preg_match( MW_XMLNS_ATTRIBUTE_PATTRN
, $attribute ) ) {
640 if ( !preg_match( MW_EVIL_URI_PATTERN
, $value ) ) {
641 $out[$attribute] = $value;
647 # Allow any attribute beginning with "data-", if in HTML5 mode
648 if ( !($wgHtml5 && preg_match( '/^data-/i', $attribute )) && !isset( $whitelist[$attribute] ) ) {
652 # Strip javascript "expression" from stylesheets.
653 # http://msdn.microsoft.com/workshop/author/dhtml/overview/recalc.asp
654 if( $attribute == 'style' ) {
655 $value = Sanitizer
::checkCss( $value );
658 if ( $attribute === 'id' ) {
659 $value = Sanitizer
::escapeId( $value, 'noninitial' );
662 //RDFa and microdata properties allow URLs, URIs and/or CURIs. check them for sanity
663 if ( $attribute === 'rel' ||
$attribute === 'rev' ||
664 $attribute === 'about' ||
$attribute === 'property' ||
$attribute === 'resource' ||
#RDFa
665 $attribute === 'datatype' ||
$attribute === 'typeof' ||
#RDFa
666 $attribute === 'itemid' ||
$attribute === 'itemprop' ||
$attribute === 'itemref' ||
#HTML5 microdata
667 $attribute === 'itemscope' ||
$attribute === 'itemtype' ) { #HTML5 microdata
669 //Paranoia. Allow "simple" values but suppress javascript
670 if ( preg_match( MW_EVIL_URI_PATTERN
, $value ) ) {
675 # NOTE: even though elements using href/src are not allowed directly, supply
676 # validation code that can be used by tag hook handlers, etc
677 if ( $attribute === 'href' ||
$attribute === 'src' ) {
678 if ( !preg_match( $hrefExp, $value ) ) {
679 continue; //drop any href or src attributes not using an allowed protocol.
680 //NOTE: this also drops all relative URLs
684 // If this attribute was previously set, override it.
685 // Output should only have one attribute of each name.
686 $out[$attribute] = $value;
689 if ( $wgAllowMicrodataAttributes ) {
690 # There are some complicated validity constraints we need to
691 # enforce here. First of all, we don't want to allow non-standard
693 $allowedTypes = array(
694 'http://microformats.org/profile/hcard',
695 'http://microformats.org/profile/hcalendar#vevent',
696 'http://n.whatwg.org/work',
698 if ( isset( $out['itemtype'] ) && !in_array( $out['itemtype'],
701 unset( $out['itemscope'] );
703 # itemtype, itemid, itemref don't make sense without itemscope
704 if ( !array_key_exists( 'itemscope', $out ) ) {
705 unset( $out['itemtype'] );
706 unset( $out['itemid'] );
707 unset( $out['itemref'] );
709 # TODO: Strip itemprop if we aren't descendants of an itemscope.
715 * Merge two sets of HTML attributes. Conflicting items in the second set
716 * will override those in the first, except for 'class' attributes which
717 * will be combined (if they're both strings).
719 * @todo implement merging for other attributes such as style
724 static function mergeAttributes( $a, $b ) {
725 $out = array_merge( $a, $b );
726 if( isset( $a['class'] ) && isset( $b['class'] )
727 && is_string( $a['class'] ) && is_string( $b['class'] )
728 && $a['class'] !== $b['class'] ) {
729 $classes = preg_split( '/\s+/', "{$a['class']} {$b['class']}",
730 -1, PREG_SPLIT_NO_EMPTY
);
731 $out['class'] = implode( ' ', array_unique( $classes ) );
737 * Pick apart some CSS and check it for forbidden or unsafe structures.
738 * Returns a sanitized string, or false if it was just too evil.
740 * Currently URL references, 'expression', 'tps' are forbidden.
742 * @param $value String
745 static function checkCss( $value ) {
746 $value = Sanitizer
::decodeCharReferences( $value );
748 // Remove any comments; IE gets token splitting wrong
749 $value = StringUtils
::delimiterReplace( '/*', '*/', ' ', $value );
751 // Decode escape sequences and line continuation
752 // See the grammar in the CSS 2 spec, appendix D.
754 if ( !$decodeRegex ) {
755 $space = '[\\x20\\t\\r\\n\\f]';
756 $nl = '(?:\\n|\\r\\n|\\r|\\f)';
758 $decodeRegex = "/ $backslash
760 ($nl) | # 1. Line continuation
761 ([0-9A-Fa-f]{1,6})$space? | # 2. character number
762 (.) | # 3. backslash cancelling special meaning
763 () | # 4. backslash at end of string
766 $value = preg_replace_callback( $decodeRegex,
767 array( __CLASS__
, 'cssDecodeCallback' ), $value );
769 // Reject problematic keywords and control characters
770 if ( preg_match( '/[\000-\010\016-\037\177]/', $value ) ) {
771 return '/* invalid control char */';
772 } elseif ( preg_match( '! expression | filter\s*: | accelerator\s*: | url\s*\( !ix', $value ) ) {
773 return '/* insecure input */';
778 static function cssDecodeCallback( $matches ) {
779 if ( $matches[1] !== '' ) {
782 } elseif ( $matches[2] !== '' ) {
783 $char = codepointToUtf8( hexdec( $matches[2] ) );
784 } elseif ( $matches[3] !== '' ) {
789 if ( $char == "\n" ||
$char == '"' ||
$char == "'" ||
$char == '\\' ) {
790 // These characters need to be escaped in strings
791 // Clean up the escape sequence to avoid parsing errors by clients
792 return '\\' . dechex( ord( $char ) ) . ' ';
794 // Decode unnecessary escape
800 * Take an associative array of attribute name/value pairs
801 * and generate a css style representing all the style-related
802 * attributes. If there already a style attribute in the array,
803 * it is also included in the value returned.
805 static function styleFromAttributes( $attributes ) {
808 foreach ( $attributes as $attribute => $value ) {
809 if ( $attribute == 'bgcolor' ) {
810 $styles[] = "background-color: $value";
811 } else if ( $attribute == 'border' ) {
812 $styles[] = "border-width: $value";
813 } else if ( $attribute == 'align' ) {
814 $styles[] = "text-align: $value";
815 } else if ( $attribute == 'valign' ) {
816 $styles[] = "vertical-align: $value";
817 } else if ( $attribute == 'width' ) {
818 if ( preg_match( '/\d+/', $value ) === false ) {
822 $styles[] = "width: $value";
823 } else if ( $attribute == 'height' ) {
824 if ( preg_match( '/\d+/', $value ) === false ) {
828 $styles[] = "height: $value";
829 } else if ( $attribute == 'nowrap' ) {
831 $styles[] = "white-space: nowrap";
836 if ( isset( $attributes[ 'style' ] ) ) {
837 $styles[] = $attributes[ 'style' ];
840 if ( !$styles ) return '';
841 else return implode( '; ', $styles );
845 * Take a tag soup fragment listing an HTML element's attributes
846 * and normalize it to well-formed XML, discarding unwanted attributes.
847 * Output is safe for further wikitext processing, with escaping of
848 * values that could trigger problems.
850 * - Normalizes attribute names to lowercase
851 * - Discards attributes not on a whitelist for the given element
852 * - Turns broken or invalid entities into plaintext
853 * - Double-quotes all attribute values
854 * - Attributes without values are given the name as attribute
855 * - Double attributes are discarded
856 * - Unsafe style attributes are discarded
857 * - Prepends space if there are attributes.
859 * @param $text String
860 * @param $element String
861 * @param $defaults Array (optional) associative array of default attributes to splice in.
862 * class and style attributes are combined. Otherwise, values from
863 * $attributes take precedence over values from $defaults.
866 static function fixTagAttributes( $text, $element, $defaults = null ) {
867 if( trim( $text ) == '' ) {
871 $decoded = Sanitizer
::decodeTagAttributes( $text );
872 $stripped = Sanitizer
::validateTagAttributes( $decoded, $element );
873 $attribs = Sanitizer
::collapseTagAttributes( $stripped, $defaults );
879 * Take an associative array or attribute name/value pairs
880 * and collapses it to well-formed XML.
881 * Does not filter attributes.
882 * Output is safe for further wikitext processing, with escaping of
883 * values that could trigger problems.
885 * - Double-quotes all attribute values
886 * - Prepends space if there are attributes.
888 * @param $attributes Array is an associative array of attribute name/value pairs.
889 * Assumed to be sanitized already.
890 * @param $defaults Array (optional) associative array of default attributes to splice in.
891 * class and style attributes are combined. Otherwise, values from
892 * $attributes take precedence over values from $defaults.
895 static function collapseTagAttributes( $attributes, $defaults = null ) {
897 foreach( $defaults as $attribute => $value ) {
898 if ( isset( $attributes[ $attribute ] ) ) {
899 if ( $attribute == 'class' ) {
900 $value .= ' '. $attributes[ $attribute ];
901 } else if ( $attribute == 'style' ) {
902 $value .= '; ' . $attributes[ $attribute ];
908 $attributes[ $attribute ] = $value;
914 foreach( $attributes as $attribute => $value ) {
915 $encAttribute = htmlspecialchars( $attribute );
916 $encValue = Sanitizer
::safeEncodeAttribute( $value );
918 $chunks[] = "$encAttribute=\"$encValue\"";
920 return count( $chunks ) ?
' ' . implode( ' ', $chunks ) : '';
924 * Encode an attribute value for HTML output.
925 * @param $text String
926 * @return HTML-encoded text fragment
928 static function encodeAttribute( $text ) {
929 $encValue = htmlspecialchars( $text, ENT_QUOTES
);
931 // Whitespace is normalized during attribute decoding,
932 // so if we've been passed non-spaces we must encode them
933 // ahead of time or they won't be preserved.
934 $encValue = strtr( $encValue, array(
944 * Encode an attribute value for HTML tags, with extra armoring
945 * against further wiki processing.
946 * @param $text String
947 * @return HTML-encoded text fragment
949 static function safeEncodeAttribute( $text ) {
950 $encValue = Sanitizer
::encodeAttribute( $text );
952 # Templates and links may be expanded in later parsing,
953 # creating invalid or dangerous output. Suppress this.
954 $encValue = strtr( $encValue, array(
955 '<' => '<', // This should never happen,
956 '>' => '>', // we've received invalid input
957 '"' => '"', // which should have been escaped.
960 "''" => '''',
961 'ISBN' => 'ISBN',
963 'PMID' => 'PMID',
969 $encValue = preg_replace_callback(
970 '/(' . wfUrlProtocols() . ')/',
971 array( 'Sanitizer', 'armorLinksCallback' ),
977 * Given a value, escape it so that it can be used in an id attribute and
978 * return it. This will use HTML5 validation if $wgExperimentalHtmlIds is
979 * true, allowing anything but ASCII whitespace. Otherwise it will use
980 * HTML 4 rules, which means a narrow subset of ASCII, with bad characters
981 * escaped with lots of dots.
983 * To ensure we don't have to bother escaping anything, we also strip ', ",
984 * & even if $wgExperimentalIds is true. TODO: Is this the best tactic?
985 * We also strip # because it upsets IE, and % because it could be
986 * ambiguous if it's part of something that looks like a percent escape
987 * (which don't work reliably in fragments cross-browser).
989 * @see http://www.w3.org/TR/html401/types.html#type-name Valid characters
992 * @see http://www.w3.org/TR/html401/struct/links.html#h-12.2.3 Anchors with the id attribute
993 * @see http://www.whatwg.org/specs/web-apps/current-work/multipage/elements.html#the-id-attribute
994 * HTML5 definition of id attribute
996 * @param $id String: id to escape
997 * @param $options Mixed: string or array of strings (default is array()):
998 * 'noninitial': This is a non-initial fragment of an id, not a full id,
999 * so don't pay attention if the first character isn't valid at the
1000 * beginning of an id. Only matters if $wgExperimentalHtmlIds is
1002 * 'legacy': Behave the way the old HTML 4-based ID escaping worked even
1003 * if $wgExperimentalHtmlIds is used, so we can generate extra
1004 * anchors and links won't break.
1007 static function escapeId( $id, $options = array() ) {
1008 global $wgHtml5, $wgExperimentalHtmlIds;
1009 $options = (array)$options;
1011 if ( $wgHtml5 && $wgExperimentalHtmlIds && !in_array( 'legacy', $options ) ) {
1012 $id = Sanitizer
::decodeCharReferences( $id );
1013 $id = preg_replace( '/[ \t\n\r\f_\'"&#%]+/', '_', $id );
1014 $id = trim( $id, '_' );
1016 # Must have been all whitespace to start with.
1023 # HTML4-style escaping
1024 static $replace = array(
1029 $id = urlencode( Sanitizer
::decodeCharReferences( strtr( $id, ' ', '_' ) ) );
1030 $id = str_replace( array_keys( $replace ), array_values( $replace ), $id );
1032 if ( !preg_match( '/^[a-zA-Z]/', $id )
1033 && !in_array( 'noninitial', $options ) ) {
1034 // Initial character must be a letter!
1041 * Given a value, escape it so that it can be used as a CSS class and
1044 * @todo For extra validity, input should be validated UTF-8.
1046 * @see http://www.w3.org/TR/CSS21/syndata.html Valid characters/format
1048 * @param $class String
1051 static function escapeClass( $class ) {
1052 // Convert ugly stuff to underscores and kill underscores in ugly places
1053 return rtrim(preg_replace(
1054 array('/(^[0-9\\-])|[\\x00-\\x20!"#$%&\'()*+,.\\/:;<=>?@[\\]^`{|}~]|\\xC2\\xA0/','/_+/'),
1060 * Given HTML input, escape with htmlspecialchars but un-escape entites.
1061 * This allows (generally harmless) entities like   to survive.
1063 * @param $html String to escape
1064 * @return String: escaped input
1066 static function escapeHtmlAllowEntities( $html ) {
1067 $html = Sanitizer
::decodeCharReferences( $html );
1068 # It seems wise to escape ' as well as ", as a matter of course. Can't
1070 $html = htmlspecialchars( $html, ENT_QUOTES
);
1075 * Regex replace callback for armoring links against further processing.
1076 * @param $matches Array
1079 private static function armorLinksCallback( $matches ) {
1080 return str_replace( ':', ':', $matches[1] );
1084 * Return an associative array of attribute names and values from
1085 * a partial tag string. Attribute names are forces to lowercase,
1086 * character references are decoded to UTF-8 text.
1088 * @param $text String
1091 public static function decodeTagAttributes( $text ) {
1092 if( trim( $text ) == '' ) {
1098 if( !preg_match_all(
1102 PREG_SET_ORDER
) ) {
1106 foreach( $pairs as $set ) {
1107 $attribute = strtolower( $set[1] );
1108 $value = Sanitizer
::getTagAttributeCallback( $set );
1110 // Normalize whitespace
1111 $value = preg_replace( '/[\t\r\n ]+/', ' ', $value );
1112 $value = trim( $value );
1114 // Decode character references
1115 $attribs[$attribute] = Sanitizer
::decodeCharReferences( $value );
1121 * Pick the appropriate attribute value from a match set from the
1122 * MW_ATTRIBS_REGEX matches.
1127 private static function getTagAttributeCallback( $set ) {
1128 if( isset( $set[6] ) ) {
1129 # Illegal #XXXXXX color with no quotes.
1131 } elseif( isset( $set[5] ) ) {
1134 } elseif( isset( $set[4] ) ) {
1137 } elseif( isset( $set[3] ) ) {
1140 } elseif( !isset( $set[2] ) ) {
1141 # In XHTML, attributes must have a value.
1142 # For 'reduced' form, return explicitly the attribute name here.
1145 throw new MWException( "Tag conditions not met. This should never happen and is a bug." );
1150 * Normalize whitespace and character references in an XML source-
1151 * encoded text for an attribute value.
1153 * See http://www.w3.org/TR/REC-xml/#AVNormalize for background,
1154 * but note that we're not returning the value, but are returning
1155 * XML source fragments that will be slapped into output.
1157 * @param $text String
1160 private static function normalizeAttributeValue( $text ) {
1161 return str_replace( '"', '"',
1162 self
::normalizeWhitespace(
1163 Sanitizer
::normalizeCharReferences( $text ) ) );
1166 private static function normalizeWhitespace( $text ) {
1167 return preg_replace(
1168 '/\r\n|[\x20\x0d\x0a\x09]/',
1174 * Normalizes whitespace in a section name, such as might be returned
1175 * by Parser::stripSectionName(), for use in the id's that are used for
1178 * @param $section String
1181 static function normalizeSectionNameWhitespace( $section ) {
1182 return trim( preg_replace( '/[ _]+/', ' ', $section ) );
1186 * Ensure that any entities and character references are legal
1187 * for XML and XHTML specifically. Any stray bits will be
1188 * &-escaped to result in a valid text fragment.
1190 * a. any named char refs must be known in XHTML
1191 * b. any numeric char refs must be legal chars, not invalid or forbidden
1192 * c. use &#x, not &#X
1193 * d. fix or reject non-valid attributes
1195 * @param $text String
1199 static function normalizeCharReferences( $text ) {
1200 return preg_replace_callback(
1202 array( 'Sanitizer', 'normalizeCharReferencesCallback' ),
1206 * @param $matches String
1209 static function normalizeCharReferencesCallback( $matches ) {
1211 if( $matches[1] != '' ) {
1212 $ret = Sanitizer
::normalizeEntity( $matches[1] );
1213 } elseif( $matches[2] != '' ) {
1214 $ret = Sanitizer
::decCharReference( $matches[2] );
1215 } elseif( $matches[3] != '' ) {
1216 $ret = Sanitizer
::hexCharReference( $matches[3] );
1217 } elseif( $matches[4] != '' ) {
1218 $ret = Sanitizer
::hexCharReference( $matches[4] );
1220 if( is_null( $ret ) ) {
1221 return htmlspecialchars( $matches[0] );
1228 * If the named entity is defined in the HTML 4.0/XHTML 1.0 DTD,
1229 * return the named entity reference as is. If the entity is a
1230 * MediaWiki-specific alias, returns the HTML equivalent. Otherwise,
1231 * returns HTML-escaped text of pseudo-entity source (eg &foo;)
1233 * @param $name String
1236 static function normalizeEntity( $name ) {
1237 global $wgHtmlEntities, $wgHtmlEntityAliases;
1238 if ( isset( $wgHtmlEntityAliases[$name] ) ) {
1239 return "&{$wgHtmlEntityAliases[$name]};";
1240 } elseif( isset( $wgHtmlEntities[$name] ) ) {
1243 return "&$name;";
1247 static function decCharReference( $codepoint ) {
1248 $point = intval( $codepoint );
1249 if( Sanitizer
::validateCodepoint( $point ) ) {
1250 return sprintf( '&#%d;', $point );
1256 static function hexCharReference( $codepoint ) {
1257 $point = hexdec( $codepoint );
1258 if( Sanitizer
::validateCodepoint( $point ) ) {
1259 return sprintf( '&#x%x;', $point );
1266 * Returns true if a given Unicode codepoint is a valid character in XML.
1267 * @param $codepoint Integer
1270 private static function validateCodepoint( $codepoint ) {
1271 return ($codepoint == 0x09)
1272 ||
($codepoint == 0x0a)
1273 ||
($codepoint == 0x0d)
1274 ||
($codepoint >= 0x20 && $codepoint <= 0xd7ff)
1275 ||
($codepoint >= 0xe000 && $codepoint <= 0xfffd)
1276 ||
($codepoint >= 0x10000 && $codepoint <= 0x10ffff);
1280 * Decode any character references, numeric or named entities,
1281 * in the text and return a UTF-8 string.
1283 * @param $text String
1286 public static function decodeCharReferences( $text ) {
1287 return preg_replace_callback(
1289 array( 'Sanitizer', 'decodeCharReferencesCallback' ),
1294 * Decode any character references, numeric or named entities,
1295 * in the next and normalize the resulting string. (bug 14952)
1297 * This is useful for page titles, not for text to be displayed,
1298 * MediaWiki allows HTML entities to escape normalization as a feature.
1300 * @param $text String (already normalized, containing entities)
1301 * @return String (still normalized, without entities)
1303 public static function decodeCharReferencesAndNormalize( $text ) {
1305 $text = preg_replace_callback(
1307 array( 'Sanitizer', 'decodeCharReferencesCallback' ),
1308 $text, /* limit */ -1, $count );
1311 return $wgContLang->normalize( $text );
1318 * @param $matches String
1321 static function decodeCharReferencesCallback( $matches ) {
1322 if( $matches[1] != '' ) {
1323 return Sanitizer
::decodeEntity( $matches[1] );
1324 } elseif( $matches[2] != '' ) {
1325 return Sanitizer
::decodeChar( intval( $matches[2] ) );
1326 } elseif( $matches[3] != '' ) {
1327 return Sanitizer
::decodeChar( hexdec( $matches[3] ) );
1328 } elseif( $matches[4] != '' ) {
1329 return Sanitizer
::decodeChar( hexdec( $matches[4] ) );
1331 # Last case should be an ampersand by itself
1336 * Return UTF-8 string for a codepoint if that is a valid
1337 * character reference, otherwise U+FFFD REPLACEMENT CHARACTER.
1338 * @param $codepoint Integer
1342 static function decodeChar( $codepoint ) {
1343 if( Sanitizer
::validateCodepoint( $codepoint ) ) {
1344 return codepointToUtf8( $codepoint );
1346 return UTF8_REPLACEMENT
;
1351 * If the named entity is defined in the HTML 4.0/XHTML 1.0 DTD,
1352 * return the UTF-8 encoding of that character. Otherwise, returns
1353 * pseudo-entity source (eg &foo;)
1355 * @param $name Strings
1358 static function decodeEntity( $name ) {
1359 global $wgHtmlEntities, $wgHtmlEntityAliases;
1360 if ( isset( $wgHtmlEntityAliases[$name] ) ) {
1361 $name = $wgHtmlEntityAliases[$name];
1363 if( isset( $wgHtmlEntities[$name] ) ) {
1364 return codepointToUtf8( $wgHtmlEntities[$name] );
1371 * Fetch the whitelist of acceptable attributes for a given element name.
1373 * @param $element String
1376 static function attributeWhitelist( $element ) {
1378 if( !isset( $list ) ) {
1379 $list = Sanitizer
::setupAttributeWhitelist();
1381 return isset( $list[$element] )
1387 * Foreach array key (an allowed HTML element), return an array
1388 * of allowed attributes
1391 static function setupAttributeWhitelist() {
1392 global $wgAllowRdfaAttributes, $wgHtml5, $wgAllowMicrodataAttributes;
1394 $common = array( 'id', 'class', 'lang', 'dir', 'title', 'style' );
1396 if ( $wgAllowRdfaAttributes ) {
1397 #RDFa attributes as specified in section 9 of http://www.w3.org/TR/2008/REC-rdfa-syntax-20081014
1398 $common = array_merge( $common, array(
1399 'about', 'property', 'resource', 'datatype', 'typeof',
1403 if ( $wgHtml5 && $wgAllowMicrodataAttributes ) {
1404 # add HTML5 microdata tages as pecified by http://www.whatwg.org/specs/web-apps/current-work/multipage/microdata.html#the-microdata-model
1405 $common = array_merge( $common, array(
1406 'itemid', 'itemprop', 'itemref', 'itemscope', 'itemtype'
1410 $block = array_merge( $common, array( 'align' ) );
1411 $tablealign = array( 'align', 'char', 'charoff', 'valign' );
1412 $tablecell = array( 'abbr',
1418 'nowrap', # deprecated
1419 'width', # deprecated
1420 'height', # deprecated
1421 'bgcolor' # deprecated
1424 # Numbers refer to sections in HTML 4.01 standard describing the element.
1425 # See: http://www.w3.org/TR/html4/
1426 $whitelist = array (
1429 'center' => $common, # deprecated
1430 'span' => $block, # ??
1448 'strong' => $common,
1459 'blockquote' => array_merge( $common, array( 'cite' ) ),
1470 'br' => array( 'id', 'class', 'title', 'style', 'clear' ),
1473 'pre' => array_merge( $common, array( 'width' ) ),
1476 'ins' => array_merge( $common, array( 'cite', 'datetime' ) ),
1477 'del' => array_merge( $common, array( 'cite', 'datetime' ) ),
1480 'ul' => array_merge( $common, array( 'type' ) ),
1481 'ol' => array_merge( $common, array( 'type', 'start' ) ),
1482 'li' => array_merge( $common, array( 'type', 'value' ) ),
1490 'table' => array_merge( $common,
1491 array( 'summary', 'width', 'border', 'frame',
1492 'rules', 'cellspacing', 'cellpadding',
1497 'caption' => array_merge( $common, array( 'align' ) ),
1500 'thead' => array_merge( $common, $tablealign ),
1501 'tfoot' => array_merge( $common, $tablealign ),
1502 'tbody' => array_merge( $common, $tablealign ),
1505 'colgroup' => array_merge( $common, array( 'span', 'width' ), $tablealign ),
1506 'col' => array_merge( $common, array( 'span', 'width' ), $tablealign ),
1509 'tr' => array_merge( $common, array( 'bgcolor' ), $tablealign ),
1512 'td' => array_merge( $common, $tablecell, $tablealign ),
1513 'th' => array_merge( $common, $tablecell, $tablealign ),
1515 # 12.2 # NOTE: <a> is not allowed directly, but the attrib whitelist is used from the Parser object
1516 'a' => array_merge( $common, array( 'href', 'rel', 'rev' ) ), # rel/rev esp. for RDFa
1519 # Not usually allowed, but may be used for extension-style hooks
1520 # such as <math> when it is rasterized, or if $wgAllowImageTag is
1522 'img' => array_merge( $common, array( 'alt', 'src', 'width', 'height' ) ),
1530 'strike' => $common,
1535 'font' => array_merge( $common, array( 'size', 'color', 'face' ) ),
1539 'hr' => array_merge( $common, array( 'noshade', 'size', 'width' ) ),
1541 # XHTML Ruby annotation text module, simple ruby only.
1542 # http://www.w3c.org/TR/ruby/
1547 'rt' => $common, #array_merge( $common, array( 'rbspan' ) ),
1550 # MathML root element, where used for extensions
1551 # 'title' may not be 100% valid here; it's XHTML
1552 # http://www.w3.org/TR/REC-MathML/
1553 'math' => array( 'class', 'style', 'id', 'title' ),
1559 * Take a fragment of (potentially invalid) HTML and return
1560 * a version with any tags removed, encoded as plain text.
1562 * Warning: this return value must be further escaped for literal
1563 * inclusion in HTML output as of 1.10!
1565 * @param $text String: HTML fragment
1568 static function stripAllTags( $text ) {
1570 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
1572 # Normalize &entities and whitespace
1573 $text = self
::decodeCharReferences( $text );
1574 $text = self
::normalizeWhitespace( $text );
1580 * Hack up a private DOCTYPE with HTML's standard entity declarations.
1581 * PHP 4 seemed to know these if you gave it an HTML doctype, but
1584 * Use for passing XHTML fragments to PHP's XML parsing functions
1588 static function hackDocType() {
1589 global $wgHtmlEntities;
1590 $out = "<!DOCTYPE html [\n";
1591 foreach( $wgHtmlEntities as $entity => $codepoint ) {
1592 $out .= "<!ENTITY $entity \"&#$codepoint;\">";
1598 static function cleanUrl( $url ) {
1599 # Normalize any HTML entities in input. They will be
1600 # re-escaped by makeExternalLink().
1601 $url = Sanitizer
::decodeCharReferences( $url );
1603 # Escape any control characters introduced by the above step
1604 $url = preg_replace( '/[\][<>"\\x00-\\x20\\x7F\|]/e', "urlencode('\\0')", $url );
1606 # Validate hostname portion
1608 if( preg_match( '!^([^:]+:)(//[^/]+)?(.*)$!iD', $url, $matches ) ) {
1609 list( /* $whole */, $protocol, $host, $rest ) = $matches;
1611 // Characters that will be ignored in IDNs.
1612 // http://tools.ietf.org/html/3454#section-3.1
1613 // Strip them before further processing so blacklists and such work.
1615 \\s| # general whitespace
1616 \xc2\xad| # 00ad SOFT HYPHEN
1617 \xe1\xa0\x86| # 1806 MONGOLIAN TODO SOFT HYPHEN
1618 \xe2\x80\x8b| # 200b ZERO WIDTH SPACE
1619 \xe2\x81\xa0| # 2060 WORD JOINER
1620 \xef\xbb\xbf| # feff ZERO WIDTH NO-BREAK SPACE
1621 \xcd\x8f| # 034f COMBINING GRAPHEME JOINER
1622 \xe1\xa0\x8b| # 180b MONGOLIAN FREE VARIATION SELECTOR ONE
1623 \xe1\xa0\x8c| # 180c MONGOLIAN FREE VARIATION SELECTOR TWO
1624 \xe1\xa0\x8d| # 180d MONGOLIAN FREE VARIATION SELECTOR THREE
1625 \xe2\x80\x8c| # 200c ZERO WIDTH NON-JOINER
1626 \xe2\x80\x8d| # 200d ZERO WIDTH JOINER
1627 [\xef\xb8\x80-\xef\xb8\x8f] # fe00-fe00f VARIATION SELECTOR-1-16
1630 $host = preg_replace( $strip, '', $host );
1632 // @todo Fixme: validate hostnames here
1634 return $protocol . $host . $rest;