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 * XHTML sanitizer for MediaWiki
33 * Regular expression to match various types of character references in
34 * Sanitizer::normalizeCharReferences and Sanitizer::decodeCharReferences
36 const CHAR_REFS_REGEX
=
37 '/&([A-Za-z0-9\x80-\xff]+);
39 |&\#[xX]([0-9A-Fa-f]+);
43 * Blacklist for evil uris like javascript:
44 * WARNING: DO NOT use this in any place that actually requires blacklisting
45 * for security reasons. There are NUMEROUS[1] ways to bypass blacklisting, the
46 * only way to be secure from javascript: uri based xss vectors is to whitelist
47 * things that you know are safe and deny everything else.
48 * [1]: http://ha.ckers.org/xss.html
50 const EVIL_URI_PATTERN
= '!(^|\s|\*/\s*)(javascript|vbscript)([^\w]|$)!i';
51 const XMLNS_ATTRIBUTE_PATTERN
= "/^xmlns:[:A-Z_a-z-.0-9]+$/";
54 * List of all named character entities defined in HTML 4.01
55 * http://www.w3.org/TR/html4/sgml/entities.html
56 * As well as ' which is only defined starting in XHTML1.
59 static $htmlEntities = array(
75 'apos' => 39, // New in XHTML & HTML 5; avoid in output for compatibility with IE.
316 * Character entity aliases accepted by MediaWiki
318 static $htmlEntityAliases = array(
324 * Lazy-initialised attributes regex, see getAttribsRegex()
326 static $attribsRegex;
329 * Regular expression to match HTML/XML attribute pairs within a tag.
330 * Allows some... latitude.
331 * Used in Sanitizer::fixTagAttributes and Sanitizer::decodeTagAttributes
333 static function getAttribsRegex() {
334 if ( self
::$attribsRegex === null ) {
335 $attribFirst = '[:A-Z_a-z0-9]';
336 $attrib = '[:A-Z_a-z-.0-9]';
337 $space = '[\x09\x0a\x0d\x20]';
338 self
::$attribsRegex =
339 "/(?:^|$space)({$attribFirst}{$attrib}*)
342 # The attribute value: quoted or alone
345 | ([a-zA-Z0-9!#$%&()*,\\-.\\/:;<>?@[\\]^_`{|}~]+)
346 | (\#[0-9a-fA-F]+) # Technically wrong, but lots of
347 # colors are specified like this.
348 # We'll be normalizing it.
352 return self
::$attribsRegex;
356 * Cleans up HTML, removes dangerous tags and attributes, and
357 * removes HTML comments
359 * @param $text String
360 * @param $processCallback Callback to do any variable or parameter replacements in HTML attribute values
361 * @param array $args for the processing callback
362 * @param array $extratags for any extra tags to include
363 * @param array $removetags for any tags (default or extra) to exclude
366 static function removeHTMLtags( $text, $processCallback = null, $args = array(), $extratags = array(), $removetags = array() ) {
367 global $wgUseTidy, $wgHtml5, $wgAllowMicrodataAttributes, $wgAllowImageTag;
369 static $htmlpairsStatic, $htmlsingle, $htmlsingleonly, $htmlnest, $tabletags,
370 $htmllist, $listtags, $htmlsingleallowed, $htmlelementsStatic, $staticInitialised;
372 wfProfileIn( __METHOD__
);
374 // Base our staticInitialised variable off of the global config state so that if the globals
375 // are changed (like in the screwed up test system) we will re-initialise the settings.
376 $globalContext = implode( '-', compact( 'wgHtml5', 'wgAllowMicrodataAttributes', 'wgAllowImageTag' ) );
377 if ( !$staticInitialised ||
$staticInitialised != $globalContext ) {
379 $htmlpairsStatic = array( # Tags that must be closed
380 'b', 'bdi', 'del', 'i', 'ins', 'u', 'font', 'big', 'small', 'sub', 'sup', 'h1',
381 'h2', 'h3', 'h4', 'h5', 'h6', 'cite', 'code', 'em', 's',
382 'strike', 'strong', 'tt', 'var', 'div', 'center',
383 'blockquote', 'ol', 'ul', 'dl', 'table', 'caption', 'pre',
384 'ruby', 'rt', 'rb', 'rp', 'p', 'span', 'abbr', 'dfn',
388 $htmlpairsStatic = array_merge( $htmlpairsStatic, array( 'data', 'time', 'mark' ) );
391 'br', 'hr', 'li', 'dt', 'dd'
393 $htmlsingleonly = array( # Elements that cannot have close tags
396 if ( $wgHtml5 && $wgAllowMicrodataAttributes ) {
397 $htmlsingle[] = $htmlsingleonly[] = 'meta';
398 $htmlsingle[] = $htmlsingleonly[] = 'link';
400 $htmlnest = array( # Tags that can be nested--??
401 'table', 'tr', 'td', 'th', 'div', 'blockquote', 'ol', 'ul',
402 'li', 'dl', 'dt', 'dd', 'font', 'big', 'small', 'sub', 'sup', 'span',
405 $tabletags = array( # Can only appear inside table, we will close them
408 $htmllist = array( # Tags used by list
411 $listtags = array( # Tags that can appear in a list
415 if ( $wgAllowImageTag ) {
416 $htmlsingle[] = 'img';
417 $htmlsingleonly[] = 'img';
420 $htmlsingleallowed = array_unique( array_merge( $htmlsingle, $tabletags ) );
421 $htmlelementsStatic = array_unique( array_merge( $htmlsingle, $htmlpairsStatic, $htmlnest ) );
423 # Convert them all to hashtables for faster lookup
424 $vars = array( 'htmlpairsStatic', 'htmlsingle', 'htmlsingleonly', 'htmlnest', 'tabletags',
425 'htmllist', 'listtags', 'htmlsingleallowed', 'htmlelementsStatic' );
426 foreach ( $vars as $var ) {
427 $
$var = array_flip( $
$var );
429 $staticInitialised = $globalContext;
431 # Populate $htmlpairs and $htmlelements with the $extratags and $removetags arrays
432 $extratags = array_flip( $extratags );
433 $removetags = array_flip( $removetags );
434 $htmlpairs = array_merge( $extratags, $htmlpairsStatic );
435 $htmlelements = array_diff_key( array_merge( $extratags, $htmlelementsStatic ), $removetags );
437 # Remove HTML comments
438 $text = Sanitizer
::removeHTMLcomments( $text );
439 $bits = explode( '<', $text );
440 $text = str_replace( '>', '>', array_shift( $bits ) );
442 $tagstack = $tablestack = array();
443 foreach ( $bits as $x ) {
445 # $slash: Does the current element start with a '/'?
446 # $t: Current element name
447 # $params: String between element name and >
448 # $brace: Ending '>' or '/>'
449 # $rest: Everything until the next element of $bits
450 if ( preg_match( '!^(/?)(\\w+)([^>]*?)(/{0,1}>)([^<]*)$!', $x, $regs ) ) {
451 list( /* $qbar */, $slash, $t, $params, $brace, $rest ) = $regs;
453 $slash = $t = $params = $brace = $rest = null;
457 if ( isset( $htmlelements[$t = strtolower( $t )] ) ) {
459 if ( $slash && isset( $htmlsingleonly[$t] ) ) {
461 } elseif ( $slash ) {
462 # Closing a tag... is it the one we just opened?
463 $ot = @array_pop
( $tagstack );
465 if ( isset( $htmlsingleallowed[$ot] ) ) {
466 # Pop all elements with an optional close tag
467 # and see if we find a match below them
469 array_push( $optstack, $ot );
470 wfSuppressWarnings();
471 $ot = array_pop( $tagstack );
473 while ( $ot != $t && isset( $htmlsingleallowed[$ot] ) ) {
474 array_push( $optstack, $ot );
475 wfSuppressWarnings();
476 $ot = array_pop( $tagstack );
480 # No match. Push the optional elements back again
482 wfSuppressWarnings();
483 $ot = array_pop( $optstack );
486 array_push( $tagstack, $ot );
487 wfSuppressWarnings();
488 $ot = array_pop( $optstack );
493 @array_push
( $tagstack, $ot );
494 # <li> can be nested in <ul> or <ol>, skip those cases:
495 if ( !isset( $htmllist[$ot] ) ||
!isset( $listtags[$t] ) ) {
500 if ( $t == 'table' ) {
501 $tagstack = array_pop( $tablestack );
506 # Keep track for later
507 if ( isset( $tabletags[$t] ) &&
508 !in_array( 'table', $tagstack ) ) {
510 } elseif ( in_array( $t, $tagstack ) &&
511 !isset( $htmlnest[$t] ) ) {
513 # Is it a self closed htmlpair ? (bug 5487)
514 } elseif ( $brace == '/>' &&
515 isset( $htmlpairs[$t] ) ) {
517 } elseif ( isset( $htmlsingleonly[$t] ) ) {
518 # Hack to force empty tag for unclosable elements
520 } elseif ( isset( $htmlsingle[$t] ) ) {
521 # Hack to not close $htmlsingle tags
523 # Still need to push this optionally-closed tag to
524 # the tag stack so that we can match end tags
525 # instead of marking them as bad.
526 array_push( $tagstack, $t );
527 } elseif ( isset( $tabletags[$t] )
528 && in_array( $t, $tagstack ) ) {
529 // New table tag but forgot to close the previous one
532 if ( $t == 'table' ) {
533 array_push( $tablestack, $tagstack );
536 array_push( $tagstack, $t );
539 # Replace any variables or template parameters with
541 if ( is_callable( $processCallback ) ) {
542 call_user_func_array( $processCallback, array( &$params, $args ) );
545 if ( !Sanitizer
::validateTag( $params, $t ) ) {
549 # Strip non-approved attributes from the tag
550 $newparams = Sanitizer
::fixTagAttributes( $params, $t );
553 $rest = str_replace( '>', '>', $rest );
554 $close = ( $brace == '/>' && !$slash ) ?
' /' : '';
555 $text .= "<$slash$t$newparams$close>$rest";
559 $text .= '<' . str_replace( '>', '>', $x );
561 # Close off any remaining tags
562 while ( is_array( $tagstack ) && ( $t = array_pop( $tagstack ) ) ) {
564 if ( $t == 'table' ) {
565 $tagstack = array_pop( $tablestack );
569 # this might be possible using tidy itself
570 foreach ( $bits as $x ) {
571 preg_match( '/^(\\/?)(\\w+)([^>]*?)(\\/{0,1}>)([^<]*)$/',
573 @list
( /* $qbar */, $slash, $t, $params, $brace, $rest ) = $regs;
575 if ( isset( $htmlelements[$t = strtolower( $t )] ) ) {
576 if ( is_callable( $processCallback ) ) {
577 call_user_func_array( $processCallback, array( &$params, $args ) );
580 if ( !Sanitizer
::validateTag( $params, $t ) ) {
584 $newparams = Sanitizer
::fixTagAttributes( $params, $t );
586 $rest = str_replace( '>', '>', $rest );
587 $text .= "<$slash$t$newparams$brace$rest";
591 $text .= '<' . str_replace( '>', '>', $x );
594 wfProfileOut( __METHOD__
);
599 * Remove '<!--', '-->', and everything between.
600 * To avoid leaving blank lines, when a comment is both preceded
601 * and followed by a newline (ignoring spaces), trim leading and
602 * trailing spaces and one of the newlines.
605 * @param $text String
608 static function removeHTMLcomments( $text ) {
609 wfProfileIn( __METHOD__
);
610 while ( ( $start = strpos( $text, '<!--' ) ) !== false ) {
611 $end = strpos( $text, '-->', $start +
4 );
612 if ( $end === false ) {
613 # Unterminated comment; bail out
619 # Trim space and newline if the comment is both
620 # preceded and followed by a newline
621 $spaceStart = max( $start - 1, 0 );
622 $spaceLen = $end - $spaceStart;
623 while ( substr( $text, $spaceStart, 1 ) === ' ' && $spaceStart > 0 ) {
627 while ( substr( $text, $spaceStart +
$spaceLen, 1 ) === ' ' ) {
630 if ( substr( $text, $spaceStart, 1 ) === "\n" and substr( $text, $spaceStart +
$spaceLen, 1 ) === "\n" ) {
631 # Remove the comment, leading and trailing
632 # spaces, and leave only one newline.
633 $text = substr_replace( $text, "\n", $spaceStart, $spaceLen +
1 );
636 # Remove just the comment.
637 $text = substr_replace( $text, '', $start, $end - $start );
640 wfProfileOut( __METHOD__
);
645 * Takes attribute names and values for a tag and the tag name and
646 * validates that the tag is allowed to be present.
647 * This DOES NOT validate the attributes, nor does it validate the
648 * tags themselves. This method only handles the special circumstances
649 * where we may want to allow a tag within content but ONLY when it has
650 * specific attributes set.
656 static function validateTag( $params, $element ) {
657 $params = Sanitizer
::decodeTagAttributes( $params );
659 if ( $element == 'meta' ||
$element == 'link' ) {
660 if ( !isset( $params['itemprop'] ) ) {
661 // <meta> and <link> must have an itemprop="" otherwise they are not valid or safe in content
664 if ( $element == 'meta' && !isset( $params['content'] ) ) {
665 // <meta> must have a content="" for the itemprop
668 if ( $element == 'link' && !isset( $params['href'] ) ) {
669 // <link> must have an associated href=""
678 * Take an array of attribute names and values and normalize or discard
679 * illegal values for the given element type.
681 * - Discards attributes not on a whitelist for the given element
682 * - Unsafe style attributes are discarded
683 * - Invalid id attributes are re-encoded
685 * @param $attribs Array
686 * @param $element String
689 * @todo Check for legal values where the DTD limits things.
690 * @todo Check for unique id attribute :P
692 static function validateTagAttributes( $attribs, $element ) {
693 return Sanitizer
::validateAttributes( $attribs,
694 Sanitizer
::attributeWhitelist( $element ) );
698 * Take an array of attribute names and values and normalize or discard
699 * illegal values for the given whitelist.
701 * - Discards attributes not the given whitelist
702 * - Unsafe style attributes are discarded
703 * - Invalid id attributes are re-encoded
705 * @param $attribs Array
706 * @param array $whitelist list of allowed attribute names
709 * @todo Check for legal values where the DTD limits things.
710 * @todo Check for unique id attribute :P
712 static function validateAttributes( $attribs, $whitelist ) {
713 global $wgAllowRdfaAttributes, $wgAllowMicrodataAttributes, $wgHtml5;
715 $whitelist = array_flip( $whitelist );
716 $hrefExp = '/^(' . wfUrlProtocols() . ')[^\s]+$/';
719 foreach ( $attribs as $attribute => $value ) {
720 #allow XML namespace declaration if RDFa is enabled
721 if ( $wgAllowRdfaAttributes && preg_match( self
::XMLNS_ATTRIBUTE_PATTERN
, $attribute ) ) {
722 if ( !preg_match( self
::EVIL_URI_PATTERN
, $value ) ) {
723 $out[$attribute] = $value;
729 # Allow any attribute beginning with "data-", if in HTML5 mode
730 if ( !( $wgHtml5 && preg_match( '/^data-/i', $attribute ) ) && !isset( $whitelist[$attribute] ) ) {
734 # Strip javascript "expression" from stylesheets.
735 # http://msdn.microsoft.com/workshop/author/dhtml/overview/recalc.asp
736 if ( $attribute == 'style' ) {
737 $value = Sanitizer
::checkCss( $value );
740 if ( $attribute === 'id' ) {
741 $value = Sanitizer
::escapeId( $value, 'noninitial' );
745 # http://www.w3.org/TR/wai-aria/
746 # http://www.whatwg.org/specs/web-apps/current-work/multipage/elements.html#wai-aria
747 # For now we only support role="presentation" until we work out what roles should be
748 # usable by content and we ensure that our code explicitly rejects patterns that
749 # violate HTML5's ARIA restrictions.
750 if ( $attribute === 'role' && $value !== 'presentation' ) {
754 //RDFa and microdata properties allow URLs, URIs and/or CURIs. check them for sanity
755 if ( $attribute === 'rel' ||
$attribute === 'rev' ||
756 $attribute === 'about' ||
$attribute === 'property' ||
$attribute === 'resource' ||
#RDFa
757 $attribute === 'datatype' ||
$attribute === 'typeof' ||
#RDFa
758 $attribute === 'itemid' ||
$attribute === 'itemprop' ||
$attribute === 'itemref' ||
#HTML5 microdata
759 $attribute === 'itemscope' ||
$attribute === 'itemtype' ) { #HTML5 microdata
761 //Paranoia. Allow "simple" values but suppress javascript
762 if ( preg_match( self
::EVIL_URI_PATTERN
, $value ) ) {
767 # NOTE: even though elements using href/src are not allowed directly, supply
768 # validation code that can be used by tag hook handlers, etc
769 if ( $attribute === 'href' ||
$attribute === 'src' ) {
770 if ( !preg_match( $hrefExp, $value ) ) {
771 continue; //drop any href or src attributes not using an allowed protocol.
772 //NOTE: this also drops all relative URLs
776 // If this attribute was previously set, override it.
777 // Output should only have one attribute of each name.
778 $out[$attribute] = $value;
781 if ( $wgAllowMicrodataAttributes ) {
782 # itemtype, itemid, itemref don't make sense without itemscope
783 if ( !array_key_exists( 'itemscope', $out ) ) {
784 unset( $out['itemtype'] );
785 unset( $out['itemid'] );
786 unset( $out['itemref'] );
788 # TODO: Strip itemprop if we aren't descendants of an itemscope or pointed to by an itemref.
794 * Merge two sets of HTML attributes. Conflicting items in the second set
795 * will override those in the first, except for 'class' attributes which
796 * will be combined (if they're both strings).
798 * @todo implement merging for other attributes such as style
803 static function mergeAttributes( $a, $b ) {
804 $out = array_merge( $a, $b );
805 if ( isset( $a['class'] ) && isset( $b['class'] )
806 && is_string( $a['class'] ) && is_string( $b['class'] )
807 && $a['class'] !== $b['class']
809 $classes = preg_split( '/\s+/', "{$a['class']} {$b['class']}",
810 -1, PREG_SPLIT_NO_EMPTY
);
811 $out['class'] = implode( ' ', array_unique( $classes ) );
817 * Pick apart some CSS and check it for forbidden or unsafe structures.
818 * Returns a sanitized string. This sanitized string will have
819 * character references and escape sequences decoded, and comments
820 * stripped. If the input is just too evil, only a comment complaining
821 * about evilness will be returned.
823 * Currently URL references, 'expression', 'tps' are forbidden.
825 * NOTE: Despite the fact that character references are decoded, the
826 * returned string may contain character references given certain
827 * clever input strings. These character references must
828 * be escaped before the return value is embedded in HTML.
830 * @param $value String
833 static function checkCss( $value ) {
834 // Decode character references like {
835 $value = Sanitizer
::decodeCharReferences( $value );
837 // Decode escape sequences and line continuation
838 // See the grammar in the CSS 2 spec, appendix D.
839 // This has to be done AFTER decoding character references.
840 // This means it isn't possible for this function to return
841 // unsanitized escape sequences. It is possible to manufacture
842 // input that contains character references that decode to
843 // escape sequences that decode to character references, but
844 // it's OK for the return value to contain character references
845 // because the caller is supposed to escape those anyway.
847 if ( !$decodeRegex ) {
848 $space = '[\\x20\\t\\r\\n\\f]';
849 $nl = '(?:\\n|\\r\\n|\\r|\\f)';
851 $decodeRegex = "/ $backslash
853 ($nl) | # 1. Line continuation
854 ([0-9A-Fa-f]{1,6})$space? | # 2. character number
855 (.) | # 3. backslash cancelling special meaning
856 () | # 4. backslash at end of string
859 $value = preg_replace_callback( $decodeRegex,
860 array( __CLASS__
, 'cssDecodeCallback' ), $value );
862 // Remove any comments; IE gets token splitting wrong
863 // This must be done AFTER decoding character references and
864 // escape sequences, because those steps can introduce comments
865 // This step cannot introduce character references or escape
866 // sequences, because it replaces comments with spaces rather
867 // than removing them completely.
868 $value = StringUtils
::delimiterReplace( '/*', '*/', ' ', $value );
870 // Remove anything after a comment-start token, to guard against
871 // incorrect client implementations.
872 $commentPos = strpos( $value, '/*' );
873 if ( $commentPos !== false ) {
874 $value = substr( $value, 0, $commentPos );
877 // Reject problematic keywords and control characters
878 if ( preg_match( '/[\000-\010\016-\037\177]/', $value ) ) {
879 return '/* invalid control char */';
880 } elseif ( preg_match( '! expression | filter\s*: | accelerator\s*: | url\s*\( | image\s*\( | image-set\s*\( !ix', $value ) ) {
881 return '/* insecure input */';
887 * @param $matches array
890 static function cssDecodeCallback( $matches ) {
891 if ( $matches[1] !== '' ) {
894 } elseif ( $matches[2] !== '' ) {
895 $char = codepointToUtf8( hexdec( $matches[2] ) );
896 } elseif ( $matches[3] !== '' ) {
901 if ( $char == "\n" ||
$char == '"' ||
$char == "'" ||
$char == '\\' ) {
902 // These characters need to be escaped in strings
903 // Clean up the escape sequence to avoid parsing errors by clients
904 return '\\' . dechex( ord( $char ) ) . ' ';
906 // Decode unnecessary escape
912 * Take a tag soup fragment listing an HTML element's attributes
913 * and normalize it to well-formed XML, discarding unwanted attributes.
914 * Output is safe for further wikitext processing, with escaping of
915 * values that could trigger problems.
917 * - Normalizes attribute names to lowercase
918 * - Discards attributes not on a whitelist for the given element
919 * - Turns broken or invalid entities into plaintext
920 * - Double-quotes all attribute values
921 * - Attributes without values are given the name as attribute
922 * - Double attributes are discarded
923 * - Unsafe style attributes are discarded
924 * - Prepends space if there are attributes.
926 * @param $text String
927 * @param $element String
930 static function fixTagAttributes( $text, $element ) {
931 if ( trim( $text ) == '' ) {
935 $decoded = Sanitizer
::decodeTagAttributes( $text );
936 $stripped = Sanitizer
::validateTagAttributes( $decoded, $element );
939 foreach ( $stripped as $attribute => $value ) {
940 $encAttribute = htmlspecialchars( $attribute );
941 $encValue = Sanitizer
::safeEncodeAttribute( $value );
943 $attribs[] = "$encAttribute=\"$encValue\"";
945 return count( $attribs ) ?
' ' . implode( ' ', $attribs ) : '';
949 * Encode an attribute value for HTML output.
950 * @param $text String
951 * @return HTML-encoded text fragment
953 static function encodeAttribute( $text ) {
954 $encValue = htmlspecialchars( $text, ENT_QUOTES
);
956 // Whitespace is normalized during attribute decoding,
957 // so if we've been passed non-spaces we must encode them
958 // ahead of time or they won't be preserved.
959 $encValue = strtr( $encValue, array(
969 * Encode an attribute value for HTML tags, with extra armoring
970 * against further wiki processing.
971 * @param $text String
972 * @return HTML-encoded text fragment
974 static function safeEncodeAttribute( $text ) {
975 $encValue = Sanitizer
::encodeAttribute( $text );
977 # Templates and links may be expanded in later parsing,
978 # creating invalid or dangerous output. Suppress this.
979 $encValue = strtr( $encValue, array(
980 '<' => '<', // This should never happen,
981 '>' => '>', // we've received invalid input
982 '"' => '"', // which should have been escaped.
985 "''" => '''',
986 'ISBN' => 'ISBN',
988 'PMID' => 'PMID',
994 $encValue = preg_replace_callback(
995 '/((?i)' . wfUrlProtocols() . ')/',
996 array( 'Sanitizer', 'armorLinksCallback' ),
1002 * Given a value, escape it so that it can be used in an id attribute and
1003 * return it. This will use HTML5 validation if $wgExperimentalHtmlIds is
1004 * true, allowing anything but ASCII whitespace. Otherwise it will use
1005 * HTML 4 rules, which means a narrow subset of ASCII, with bad characters
1006 * escaped with lots of dots.
1008 * To ensure we don't have to bother escaping anything, we also strip ', ",
1009 * & even if $wgExperimentalIds is true. TODO: Is this the best tactic?
1010 * We also strip # because it upsets IE, and % because it could be
1011 * ambiguous if it's part of something that looks like a percent escape
1012 * (which don't work reliably in fragments cross-browser).
1014 * @see http://www.w3.org/TR/html401/types.html#type-name Valid characters
1017 * @see http://www.w3.org/TR/html401/struct/links.html#h-12.2.3 Anchors with the id attribute
1018 * @see http://www.whatwg.org/specs/web-apps/current-work/multipage/elements.html#the-id-attribute
1019 * HTML5 definition of id attribute
1021 * @param string $id id to escape
1022 * @param $options Mixed: string or array of strings (default is array()):
1023 * 'noninitial': This is a non-initial fragment of an id, not a full id,
1024 * so don't pay attention if the first character isn't valid at the
1025 * beginning of an id. Only matters if $wgExperimentalHtmlIds is
1027 * 'legacy': Behave the way the old HTML 4-based ID escaping worked even
1028 * if $wgExperimentalHtmlIds is used, so we can generate extra
1029 * anchors and links won't break.
1032 static function escapeId( $id, $options = array() ) {
1033 global $wgHtml5, $wgExperimentalHtmlIds;
1034 $options = (array)$options;
1036 if ( $wgHtml5 && $wgExperimentalHtmlIds && !in_array( 'legacy', $options ) ) {
1037 $id = Sanitizer
::decodeCharReferences( $id );
1038 $id = preg_replace( '/[ \t\n\r\f_\'"&#%]+/', '_', $id );
1039 $id = trim( $id, '_' );
1041 # Must have been all whitespace to start with.
1048 # HTML4-style escaping
1049 static $replace = array(
1054 $id = urlencode( Sanitizer
::decodeCharReferences( strtr( $id, ' ', '_' ) ) );
1055 $id = str_replace( array_keys( $replace ), array_values( $replace ), $id );
1057 if ( !preg_match( '/^[a-zA-Z]/', $id )
1058 && !in_array( 'noninitial', $options ) ) {
1059 // Initial character must be a letter!
1066 * Given a value, escape it so that it can be used as a CSS class and
1069 * @todo For extra validity, input should be validated UTF-8.
1071 * @see http://www.w3.org/TR/CSS21/syndata.html Valid characters/format
1073 * @param $class String
1076 static function escapeClass( $class ) {
1077 // Convert ugly stuff to underscores and kill underscores in ugly places
1078 return rtrim( preg_replace(
1079 array( '/(^[0-9\\-])|[\\x00-\\x20!"#$%&\'()*+,.\\/:;<=>?@[\\]^`{|}~]|\\xC2\\xA0/', '/_+/' ),
1085 * Given HTML input, escape with htmlspecialchars but un-escape entities.
1086 * This allows (generally harmless) entities like   to survive.
1088 * @param string $html to escape
1089 * @return String: escaped input
1091 static function escapeHtmlAllowEntities( $html ) {
1092 $html = Sanitizer
::decodeCharReferences( $html );
1093 # It seems wise to escape ' as well as ", as a matter of course. Can't
1095 $html = htmlspecialchars( $html, ENT_QUOTES
);
1100 * Regex replace callback for armoring links against further processing.
1101 * @param $matches Array
1104 private static function armorLinksCallback( $matches ) {
1105 return str_replace( ':', ':', $matches[1] );
1109 * Return an associative array of attribute names and values from
1110 * a partial tag string. Attribute names are forces to lowercase,
1111 * character references are decoded to UTF-8 text.
1113 * @param $text String
1116 public static function decodeTagAttributes( $text ) {
1117 if ( trim( $text ) == '' ) {
1123 if ( !preg_match_all(
1124 self
::getAttribsRegex(),
1127 PREG_SET_ORDER
) ) {
1131 foreach ( $pairs as $set ) {
1132 $attribute = strtolower( $set[1] );
1133 $value = Sanitizer
::getTagAttributeCallback( $set );
1135 // Normalize whitespace
1136 $value = preg_replace( '/[\t\r\n ]+/', ' ', $value );
1137 $value = trim( $value );
1139 // Decode character references
1140 $attribs[$attribute] = Sanitizer
::decodeCharReferences( $value );
1146 * Pick the appropriate attribute value from a match set from the
1147 * attribs regex matches.
1150 * @throws MWException
1153 private static function getTagAttributeCallback( $set ) {
1154 if ( isset( $set[6] ) ) {
1155 # Illegal #XXXXXX color with no quotes.
1157 } elseif ( isset( $set[5] ) ) {
1160 } elseif ( isset( $set[4] ) ) {
1163 } elseif ( isset( $set[3] ) ) {
1166 } elseif ( !isset( $set[2] ) ) {
1167 # In XHTML, attributes must have a value.
1168 # For 'reduced' form, return explicitly the attribute name here.
1171 throw new MWException( "Tag conditions not met. This should never happen and is a bug." );
1176 * Normalize whitespace and character references in an XML source-
1177 * encoded text for an attribute value.
1179 * See http://www.w3.org/TR/REC-xml/#AVNormalize for background,
1180 * but note that we're not returning the value, but are returning
1181 * XML source fragments that will be slapped into output.
1183 * @param $text String
1186 private static function normalizeAttributeValue( $text ) {
1187 return str_replace( '"', '"',
1188 self
::normalizeWhitespace(
1189 Sanitizer
::normalizeCharReferences( $text ) ) );
1193 * @param $text string
1196 private static function normalizeWhitespace( $text ) {
1197 return preg_replace(
1198 '/\r\n|[\x20\x0d\x0a\x09]/',
1204 * Normalizes whitespace in a section name, such as might be returned
1205 * by Parser::stripSectionName(), for use in the id's that are used for
1208 * @param $section String
1211 static function normalizeSectionNameWhitespace( $section ) {
1212 return trim( preg_replace( '/[ _]+/', ' ', $section ) );
1216 * Ensure that any entities and character references are legal
1217 * for XML and XHTML specifically. Any stray bits will be
1218 * &-escaped to result in a valid text fragment.
1220 * a. named char refs can only be < > & ", others are
1221 * numericized (this way we're well-formed even without a DTD)
1222 * b. any numeric char refs must be legal chars, not invalid or forbidden
1223 * c. use lower cased "&#x", not "&#X"
1224 * d. fix or reject non-valid attributes
1226 * @param $text String
1230 static function normalizeCharReferences( $text ) {
1231 return preg_replace_callback(
1232 self
::CHAR_REFS_REGEX
,
1233 array( 'Sanitizer', 'normalizeCharReferencesCallback' ),
1237 * @param $matches String
1240 static function normalizeCharReferencesCallback( $matches ) {
1242 if ( $matches[1] != '' ) {
1243 $ret = Sanitizer
::normalizeEntity( $matches[1] );
1244 } elseif ( $matches[2] != '' ) {
1245 $ret = Sanitizer
::decCharReference( $matches[2] );
1246 } elseif ( $matches[3] != '' ) {
1247 $ret = Sanitizer
::hexCharReference( $matches[3] );
1249 if ( is_null( $ret ) ) {
1250 return htmlspecialchars( $matches[0] );
1257 * If the named entity is defined in the HTML 4.0/XHTML 1.0 DTD,
1258 * return the equivalent numeric entity reference (except for the core <
1259 * > & "). If the entity is a MediaWiki-specific alias, returns
1260 * the HTML equivalent. Otherwise, returns HTML-escaped text of
1261 * pseudo-entity source (eg &foo;)
1263 * @param $name String
1266 static function normalizeEntity( $name ) {
1267 if ( isset( self
::$htmlEntityAliases[$name] ) ) {
1268 return '&' . self
::$htmlEntityAliases[$name] . ';';
1269 } elseif ( in_array( $name,
1270 array( 'lt', 'gt', 'amp', 'quot' ) ) ) {
1272 } elseif ( isset( self
::$htmlEntities[$name] ) ) {
1273 return '&#' . self
::$htmlEntities[$name] . ';';
1275 return "&$name;";
1281 * @return null|string
1283 static function decCharReference( $codepoint ) {
1284 $point = intval( $codepoint );
1285 if ( Sanitizer
::validateCodepoint( $point ) ) {
1286 return sprintf( '&#%d;', $point );
1294 * @return null|string
1296 static function hexCharReference( $codepoint ) {
1297 $point = hexdec( $codepoint );
1298 if ( Sanitizer
::validateCodepoint( $point ) ) {
1299 return sprintf( '&#x%x;', $point );
1306 * Returns true if a given Unicode codepoint is a valid character in XML.
1307 * @param $codepoint Integer
1310 private static function validateCodepoint( $codepoint ) {
1311 return ($codepoint == 0x09)
1312 ||
($codepoint == 0x0a)
1313 ||
($codepoint == 0x0d)
1314 ||
($codepoint >= 0x20 && $codepoint <= 0xd7ff)
1315 ||
($codepoint >= 0xe000 && $codepoint <= 0xfffd)
1316 ||
($codepoint >= 0x10000 && $codepoint <= 0x10ffff);
1320 * Decode any character references, numeric or named entities,
1321 * in the text and return a UTF-8 string.
1323 * @param $text String
1326 public static function decodeCharReferences( $text ) {
1327 return preg_replace_callback(
1328 self
::CHAR_REFS_REGEX
,
1329 array( 'Sanitizer', 'decodeCharReferencesCallback' ),
1334 * Decode any character references, numeric or named entities,
1335 * in the next and normalize the resulting string. (bug 14952)
1337 * This is useful for page titles, not for text to be displayed,
1338 * MediaWiki allows HTML entities to escape normalization as a feature.
1340 * @param string $text (already normalized, containing entities)
1341 * @return String (still normalized, without entities)
1343 public static function decodeCharReferencesAndNormalize( $text ) {
1345 $text = preg_replace_callback(
1346 self
::CHAR_REFS_REGEX
,
1347 array( 'Sanitizer', 'decodeCharReferencesCallback' ),
1348 $text, /* limit */ -1, $count );
1351 return $wgContLang->normalize( $text );
1358 * @param $matches String
1361 static function decodeCharReferencesCallback( $matches ) {
1362 if ( $matches[1] != '' ) {
1363 return Sanitizer
::decodeEntity( $matches[1] );
1364 } elseif ( $matches[2] != '' ) {
1365 return Sanitizer
::decodeChar( intval( $matches[2] ) );
1366 } elseif ( $matches[3] != '' ) {
1367 return Sanitizer
::decodeChar( hexdec( $matches[3] ) );
1369 # Last case should be an ampersand by itself
1374 * Return UTF-8 string for a codepoint if that is a valid
1375 * character reference, otherwise U+FFFD REPLACEMENT CHARACTER.
1376 * @param $codepoint Integer
1380 static function decodeChar( $codepoint ) {
1381 if ( Sanitizer
::validateCodepoint( $codepoint ) ) {
1382 return codepointToUtf8( $codepoint );
1384 return UTF8_REPLACEMENT
;
1389 * If the named entity is defined in the HTML 4.0/XHTML 1.0 DTD,
1390 * return the UTF-8 encoding of that character. Otherwise, returns
1391 * pseudo-entity source (eg "&foo;")
1393 * @param $name String
1396 static function decodeEntity( $name ) {
1397 if ( isset( self
::$htmlEntityAliases[$name] ) ) {
1398 $name = self
::$htmlEntityAliases[$name];
1400 if ( isset( self
::$htmlEntities[$name] ) ) {
1401 return codepointToUtf8( self
::$htmlEntities[$name] );
1408 * Fetch the whitelist of acceptable attributes for a given element name.
1410 * @param $element String
1413 static function attributeWhitelist( $element ) {
1414 $list = Sanitizer
::setupAttributeWhitelist();
1415 return isset( $list[$element] )
1421 * Foreach array key (an allowed HTML element), return an array
1422 * of allowed attributes
1425 static function setupAttributeWhitelist() {
1426 global $wgAllowRdfaAttributes, $wgHtml5, $wgAllowMicrodataAttributes;
1428 static $whitelist, $staticInitialised;
1429 $globalContext = implode( '-', compact( 'wgAllowRdfaAttributes', 'wgHtml5', 'wgAllowMicrodataAttributes' ) );
1431 if ( isset( $whitelist ) && $staticInitialised == $globalContext ) {
1448 if ( $wgAllowRdfaAttributes ) {
1449 #RDFa attributes as specified in section 9 of http://www.w3.org/TR/2008/REC-rdfa-syntax-20081014
1450 $common = array_merge( $common, array(
1451 'about', 'property', 'resource', 'datatype', 'typeof',
1455 if ( $wgHtml5 && $wgAllowMicrodataAttributes ) {
1456 # add HTML5 microdata tags as specified by http://www.whatwg.org/specs/web-apps/current-work/multipage/microdata.html#the-microdata-model
1457 $common = array_merge( $common, array(
1458 'itemid', 'itemprop', 'itemref', 'itemscope', 'itemtype'
1462 $block = array_merge( $common, array( 'align' ) );
1463 $tablealign = array( 'align', 'char', 'charoff', 'valign' );
1471 'nowrap', # deprecated
1472 'width', # deprecated
1473 'height', # deprecated
1474 'bgcolor', # deprecated
1477 # Numbers refer to sections in HTML 4.01 standard describing the element.
1478 # See: http://www.w3.org/TR/html4/
1482 'center' => $common, # deprecated
1483 'span' => $block, # ??
1501 'strong' => $common,
1512 'blockquote' => array_merge( $common, array( 'cite' ) ),
1523 'br' => array( 'id', 'class', 'title', 'style', 'clear' ),
1526 'pre' => array_merge( $common, array( 'width' ) ),
1529 'ins' => array_merge( $common, array( 'cite', 'datetime' ) ),
1530 'del' => array_merge( $common, array( 'cite', 'datetime' ) ),
1533 'ul' => array_merge( $common, array( 'type' ) ),
1534 'ol' => array_merge( $common, array( 'type', 'start' ) ),
1535 'li' => array_merge( $common, array( 'type', 'value' ) ),
1543 'table' => array_merge( $common,
1544 array( 'summary', 'width', 'border', 'frame',
1545 'rules', 'cellspacing', 'cellpadding',
1550 'caption' => array_merge( $common, array( 'align' ) ),
1553 'thead' => array_merge( $common, $tablealign ),
1554 'tfoot' => array_merge( $common, $tablealign ),
1555 'tbody' => array_merge( $common, $tablealign ),
1558 'colgroup' => array_merge( $common, array( 'span', 'width' ), $tablealign ),
1559 'col' => array_merge( $common, array( 'span', 'width' ), $tablealign ),
1562 'tr' => array_merge( $common, array( 'bgcolor' ), $tablealign ),
1565 'td' => array_merge( $common, $tablecell, $tablealign ),
1566 'th' => array_merge( $common, $tablecell, $tablealign ),
1568 # 12.2 # NOTE: <a> is not allowed directly, but the attrib whitelist is used from the Parser object
1569 'a' => array_merge( $common, array( 'href', 'rel', 'rev' ) ), # rel/rev esp. for RDFa
1572 # Not usually allowed, but may be used for extension-style hooks
1573 # such as <math> when it is rasterized, or if $wgAllowImageTag is
1575 'img' => array_merge( $common, array( 'alt', 'src', 'width', 'height' ) ),
1583 'strike' => $common,
1588 'font' => array_merge( $common, array( 'size', 'color', 'face' ) ),
1592 'hr' => array_merge( $common, array( 'noshade', 'size', 'width' ) ),
1594 # XHTML Ruby annotation text module, simple ruby only.
1595 # http://www.w3c.org/TR/ruby/
1600 'rt' => $common, #array_merge( $common, array( 'rbspan' ) ),
1603 # MathML root element, where used for extensions
1604 # 'title' may not be 100% valid here; it's XHTML
1605 # http://www.w3.org/TR/REC-MathML/
1606 'math' => array( 'class', 'style', 'id', 'title' ),
1608 # HTML 5 section 4.6
1614 # HTML5 elements, defined by:
1615 # http://www.whatwg.org/specs/web-apps/current-work/multipage/
1616 $whitelist +
= array(
1617 'data' => array_merge( $common, array( 'value' ) ),
1618 'time' => array_merge( $common, array( 'datetime' ) ),
1621 // meta and link are only permitted by removeHTMLtags when Microdata
1622 // is enabled so we don't bother adding a conditional to hide these
1623 // Also meta and link are only valid in WikiText as Microdata elements
1624 // (ie: validateTag rejects tags missing the attributes needed for Microdata)
1625 // So we don't bother including $common attributes that have no purpose.
1626 'meta' => array( 'itemprop', 'content' ),
1627 'link' => array( 'itemprop', 'href' ),
1631 $staticInitialised = $globalContext;
1637 * Take a fragment of (potentially invalid) HTML and return
1638 * a version with any tags removed, encoded as plain text.
1640 * Warning: this return value must be further escaped for literal
1641 * inclusion in HTML output as of 1.10!
1643 * @param string $text HTML fragment
1646 static function stripAllTags( $text ) {
1648 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
1650 # Normalize &entities and whitespace
1651 $text = self
::decodeCharReferences( $text );
1652 $text = self
::normalizeWhitespace( $text );
1658 * Hack up a private DOCTYPE with HTML's standard entity declarations.
1659 * PHP 4 seemed to know these if you gave it an HTML doctype, but
1662 * Use for passing XHTML fragments to PHP's XML parsing functions
1666 static function hackDocType() {
1667 $out = "<!DOCTYPE html [\n";
1668 foreach ( self
::$htmlEntities as $entity => $codepoint ) {
1669 $out .= "<!ENTITY $entity \"&#$codepoint;\">";
1676 * @param $url string
1677 * @return mixed|string
1679 static function cleanUrl( $url ) {
1680 # Normalize any HTML entities in input. They will be
1681 # re-escaped by makeExternalLink().
1682 $url = Sanitizer
::decodeCharReferences( $url );
1684 # Escape any control characters introduced by the above step
1685 $url = preg_replace_callback( '/[\][<>"\\x00-\\x20\\x7F\|]/',
1686 array( __CLASS__
, 'cleanUrlCallback' ), $url );
1688 # Validate hostname portion
1690 if ( preg_match( '!^([^:]+:)(//[^/]+)?(.*)$!iD', $url, $matches ) ) {
1691 list( /* $whole */, $protocol, $host, $rest ) = $matches;
1693 // Characters that will be ignored in IDNs.
1694 // http://tools.ietf.org/html/3454#section-3.1
1695 // Strip them before further processing so blacklists and such work.
1697 \\s| # general whitespace
1698 \xc2\xad| # 00ad SOFT HYPHEN
1699 \xe1\xa0\x86| # 1806 MONGOLIAN TODO SOFT HYPHEN
1700 \xe2\x80\x8b| # 200b ZERO WIDTH SPACE
1701 \xe2\x81\xa0| # 2060 WORD JOINER
1702 \xef\xbb\xbf| # feff ZERO WIDTH NO-BREAK SPACE
1703 \xcd\x8f| # 034f COMBINING GRAPHEME JOINER
1704 \xe1\xa0\x8b| # 180b MONGOLIAN FREE VARIATION SELECTOR ONE
1705 \xe1\xa0\x8c| # 180c MONGOLIAN FREE VARIATION SELECTOR TWO
1706 \xe1\xa0\x8d| # 180d MONGOLIAN FREE VARIATION SELECTOR THREE
1707 \xe2\x80\x8c| # 200c ZERO WIDTH NON-JOINER
1708 \xe2\x80\x8d| # 200d ZERO WIDTH JOINER
1709 [\xef\xb8\x80-\xef\xb8\x8f] # fe00-fe0f VARIATION SELECTOR-1-16
1712 $host = preg_replace( $strip, '', $host );
1714 // @todo FIXME: Validate hostnames here
1716 return $protocol . $host . $rest;
1723 * @param $matches array
1726 static function cleanUrlCallback( $matches ) {
1727 return urlencode( $matches[0] );
1731 * Does a string look like an e-mail address?
1733 * This validates an email address using an HTML5 specification found at:
1734 * http://www.whatwg.org/specs/web-apps/current-work/multipage/states-of-the-type-attribute.html#valid-e-mail-address
1735 * Which as of 2011-01-24 says:
1737 * A valid e-mail address is a string that matches the ABNF production
1738 * 1*( atext / "." ) "@" ldh-str *( "." ldh-str ) where atext is defined
1739 * in RFC 5322 section 3.2.3, and ldh-str is defined in RFC 1034 section
1742 * This function is an implementation of the specification as requested in
1745 * Client-side forms will use the same standard validation rules via JS or
1746 * HTML 5 validation; additional restrictions can be enforced server-side
1747 * by extensions via the 'isValidEmailAddr' hook.
1749 * Note that this validation doesn't 100% match RFC 2822, but is believed
1750 * to be liberal enough for wide use. Some invalid addresses will still
1751 * pass validation here.
1755 * @param string $addr E-mail address
1758 public static function validateEmail( $addr ) {
1760 if ( !wfRunHooks( 'isValidEmailAddr', array( $addr, &$result ) ) ) {
1764 // Please note strings below are enclosed in brackets [], this make the
1765 // hyphen "-" a range indicator. Hence it is double backslashed below.
1767 $rfc5322_atext = "a-z0-9!#$%&'*+\\-\/=?^_`{|}~";
1768 $rfc1034_ldh_str = "a-z0-9\\-";
1770 $HTML5_email_regexp = "/
1772 [$rfc5322_atext\\.]+ # user part which is liberal :p
1774 [$rfc1034_ldh_str]+ # First domain part
1775 (\\.[$rfc1034_ldh_str]+)* # Following part prefixed with a dot
1777 /ix"; // case Insensitive, eXtended
1779 return (bool) preg_match( $HTML5_email_regexp, $addr );