3 * kses 0.2.2 - HTML/XHTML filter that only allows some elements and attributes
4 * Copyright (C) 2002, 2003, 2005 Ulf Harnhammar
6 * This program is free software and open source software; you can redistribute
7 * it and/or modify it under the terms of the GNU General Public License as
8 * published by the Free Software Foundation; either version 2 of the License,
9 * or (at your option) any later version.
11 * This program is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
16 * You should have received a copy of the GNU General Public License along
17 * with this program; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19 * http://www.gnu.org/licenses/gpl.html
21 * [kses strips evil scripts!]
23 * Added wp_ prefix to avoid conflicts with existing kses users
26 * @copyright (C) 2002, 2003, 2005
27 * @author Ulf Harnhammar <http://advogato.org/person/metaur/>
35 * You can override this in a plugin.
37 * The {@see 'wp_kses_allowed_html'} filter is more powerful and supplies context.
39 * `CUSTOM_TAGS` is not recommended and should be considered deprecated.
41 * @see wp_kses_allowed_html()
45 if ( ! defined( 'CUSTOM_TAGS' ) )
46 define( 'CUSTOM_TAGS', false );
48 // Ensure that these variables are added to the global namespace
49 // (e.g. if using namespaces / autoload in the current PHP environment).
50 global $allowedposttags, $allowedtags, $allowedentitynames;
52 if ( ! CUSTOM_TAGS ) {
54 * Kses global for default allowable HTML tags.
56 * Can be override by using CUSTOM_TAGS constant.
58 * @global array $allowedposttags
61 $allowedposttags = array(
105 'blockquote' => array(
163 'fieldset' => array(),
170 'figcaption' => array(
190 'accept-charset' => true,
314 'cellpadding' => true,
315 'cellspacing' => true,
419 * Kses allowed HTML elements.
421 * @global array $allowedtags
424 $allowedtags = array(
436 'blockquote' => array(
454 $allowedentitynames = array(
455 'nbsp', 'iexcl', 'cent', 'pound', 'curren', 'yen',
456 'brvbar', 'sect', 'uml', 'copy', 'ordf', 'laquo',
457 'not', 'shy', 'reg', 'macr', 'deg', 'plusmn',
458 'acute', 'micro', 'para', 'middot', 'cedil', 'ordm',
459 'raquo', 'iquest', 'Agrave', 'Aacute', 'Acirc', 'Atilde',
460 'Auml', 'Aring', 'AElig', 'Ccedil', 'Egrave', 'Eacute',
461 'Ecirc', 'Euml', 'Igrave', 'Iacute', 'Icirc', 'Iuml',
462 'ETH', 'Ntilde', 'Ograve', 'Oacute', 'Ocirc', 'Otilde',
463 'Ouml', 'times', 'Oslash', 'Ugrave', 'Uacute', 'Ucirc',
464 'Uuml', 'Yacute', 'THORN', 'szlig', 'agrave', 'aacute',
465 'acirc', 'atilde', 'auml', 'aring', 'aelig', 'ccedil',
466 'egrave', 'eacute', 'ecirc', 'euml', 'igrave', 'iacute',
467 'icirc', 'iuml', 'eth', 'ntilde', 'ograve', 'oacute',
468 'ocirc', 'otilde', 'ouml', 'divide', 'oslash', 'ugrave',
469 'uacute', 'ucirc', 'uuml', 'yacute', 'thorn', 'yuml',
470 'quot', 'amp', 'lt', 'gt', 'apos', 'OElig',
471 'oelig', 'Scaron', 'scaron', 'Yuml', 'circ', 'tilde',
472 'ensp', 'emsp', 'thinsp', 'zwnj', 'zwj', 'lrm',
473 'rlm', 'ndash', 'mdash', 'lsquo', 'rsquo', 'sbquo',
474 'ldquo', 'rdquo', 'bdquo', 'dagger', 'Dagger', 'permil',
475 'lsaquo', 'rsaquo', 'euro', 'fnof', 'Alpha', 'Beta',
476 'Gamma', 'Delta', 'Epsilon', 'Zeta', 'Eta', 'Theta',
477 'Iota', 'Kappa', 'Lambda', 'Mu', 'Nu', 'Xi',
478 'Omicron', 'Pi', 'Rho', 'Sigma', 'Tau', 'Upsilon',
479 'Phi', 'Chi', 'Psi', 'Omega', 'alpha', 'beta',
480 'gamma', 'delta', 'epsilon', 'zeta', 'eta', 'theta',
481 'iota', 'kappa', 'lambda', 'mu', 'nu', 'xi',
482 'omicron', 'pi', 'rho', 'sigmaf', 'sigma', 'tau',
483 'upsilon', 'phi', 'chi', 'psi', 'omega', 'thetasym',
484 'upsih', 'piv', 'bull', 'hellip', 'prime', 'Prime',
485 'oline', 'frasl', 'weierp', 'image', 'real', 'trade',
486 'alefsym', 'larr', 'uarr', 'rarr', 'darr', 'harr',
487 'crarr', 'lArr', 'uArr', 'rArr', 'dArr', 'hArr',
488 'forall', 'part', 'exist', 'empty', 'nabla', 'isin',
489 'notin', 'ni', 'prod', 'sum', 'minus', 'lowast',
490 'radic', 'prop', 'infin', 'ang', 'and', 'or',
491 'cap', 'cup', 'int', 'sim', 'cong', 'asymp',
492 'ne', 'equiv', 'le', 'ge', 'sub', 'sup',
493 'nsub', 'sube', 'supe', 'oplus', 'otimes', 'perp',
494 'sdot', 'lceil', 'rceil', 'lfloor', 'rfloor', 'lang',
495 'rang', 'loz', 'spades', 'clubs', 'hearts', 'diams',
496 'sup1', 'sup2', 'sup3', 'frac14', 'frac12', 'frac34',
500 $allowedposttags = array_map( '_wp_add_global_attributes', $allowedposttags );
502 $allowedtags = wp_kses_array_lc( $allowedtags );
503 $allowedposttags = wp_kses_array_lc( $allowedposttags );
507 * Filters content and keeps only allowable HTML elements.
509 * This function makes sure that only the allowed HTML element names, attribute
510 * names and attribute values plus only sane HTML entities will occur in
511 * $string. You have to remove any slashes from PHP's magic quotes before you
512 * call this function.
514 * The default allowed protocols are 'http', 'https', 'ftp', 'mailto', 'news',
515 * 'irc', 'gopher', 'nntp', 'feed', 'telnet, 'mms', 'rtsp' and 'svn'. This
516 * covers all common link protocols, except for 'javascript' which should not
517 * be allowed for untrusted users.
521 * @param string $string Content to filter through kses
522 * @param array $allowed_html List of allowed HTML elements
523 * @param array $allowed_protocols Optional. Allowed protocol in links.
524 * @return string Filtered content with only allowed HTML elements
526 function wp_kses( $string, $allowed_html, $allowed_protocols = array() ) {
527 if ( empty( $allowed_protocols ) )
528 $allowed_protocols = wp_allowed_protocols();
529 $string = wp_kses_no_null( $string, array( 'slash_zero' => 'keep' ) );
530 $string = wp_kses_normalize_entities($string);
531 $string = wp_kses_hook($string, $allowed_html, $allowed_protocols); // WP changed the order of these funcs and added args to wp_kses_hook
532 return wp_kses_split($string, $allowed_html, $allowed_protocols);
536 * Filters one attribute only and ensures its value is allowed.
538 * This function has the advantage of being more secure than esc_attr() and can
539 * escape data in some situations where wp_kses() must strip the whole attribute.
543 * @param string $string The 'whole' attribute, including name and value.
544 * @param string $element The element name to which the attribute belongs.
545 * @return string Filtered attribute.
547 function wp_kses_one_attr( $string, $element ) {
548 $uris = array('xmlns', 'profile', 'href', 'src', 'cite', 'classid', 'codebase', 'data', 'usemap', 'longdesc', 'action');
549 $allowed_html = wp_kses_allowed_html( 'post' );
550 $allowed_protocols = wp_allowed_protocols();
551 $string = wp_kses_no_null( $string, array( 'slash_zero' => 'keep' ) );
553 // Preserve leading and trailing whitespace.
555 preg_match('/^\s*/', $string, $matches);
557 preg_match('/\s*$/', $string, $matches);
558 $trail = $matches[0];
559 if ( empty( $trail ) ) {
560 $string = substr( $string, strlen( $lead ) );
562 $string = substr( $string, strlen( $lead ), -strlen( $trail ) );
565 // Parse attribute name and value from input.
566 $split = preg_split( '/\s*=\s*/', $string, 2 );
568 if ( count( $split ) == 2 ) {
571 // Remove quotes surrounding $value.
572 // Also guarantee correct quoting in $string for this one attribute.
573 if ( '' == $value ) {
578 if ( '"' == $quote || "'" == $quote ) {
579 if ( substr( $value, -1 ) != $quote ) {
582 $value = substr( $value, 1, -1 );
587 // Sanitize quotes, angle braces, and entities.
588 $value = esc_attr( $value );
590 // Sanitize URI values.
591 if ( in_array( strtolower( $name ), $uris ) ) {
592 $value = wp_kses_bad_protocol( $value, $allowed_protocols );
595 $string = "$name=$quote$value$quote";
602 // Sanitize attribute by name.
603 wp_kses_attr_check( $name, $value, $string, $vless, $element, $allowed_html );
605 // Restore whitespace.
606 return $lead . $string . $trail;
610 * Return a list of allowed tags and attributes for a given context.
614 * @global array $allowedposttags
615 * @global array $allowedtags
616 * @global array $allowedentitynames
618 * @param string $context The context for which to retrieve tags.
619 * Allowed values are post, strip, data,entities, or
620 * the name of a field filter such as pre_user_description.
621 * @return array List of allowed tags and their allowed attributes.
623 function wp_kses_allowed_html( $context = '' ) {
624 global $allowedposttags, $allowedtags, $allowedentitynames;
626 if ( is_array( $context ) ) {
628 * Filters HTML elements allowed for a given context.
632 * @param string $tags Allowed tags, attributes, and/or entities.
633 * @param string $context Context to judge allowed tags by. Allowed values are 'post',
634 * 'data', 'strip', 'entities', 'explicit', or the name of a filter.
636 return apply_filters( 'wp_kses_allowed_html', $context, 'explicit' );
639 switch ( $context ) {
641 /** This filter is documented in wp-includes/kses.php */
642 return apply_filters( 'wp_kses_allowed_html', $allowedposttags, $context );
644 case 'user_description':
645 case 'pre_user_description':
646 $tags = $allowedtags;
647 $tags['a']['rel'] = true;
648 /** This filter is documented in wp-includes/kses.php */
649 return apply_filters( 'wp_kses_allowed_html', $tags, $context );
652 /** This filter is documented in wp-includes/kses.php */
653 return apply_filters( 'wp_kses_allowed_html', array(), $context );
656 /** This filter is documented in wp-includes/kses.php */
657 return apply_filters( 'wp_kses_allowed_html', $allowedentitynames, $context);
661 /** This filter is documented in wp-includes/kses.php */
662 return apply_filters( 'wp_kses_allowed_html', $allowedtags, $context );
667 * You add any kses hooks here.
669 * There is currently only one kses WordPress hook, {@see 'pre_kses'}, and it is called here.
670 * All parameters are passed to the hooks and expected to receive a string.
674 * @param string $string Content to filter through kses
675 * @param array $allowed_html List of allowed HTML elements
676 * @param array $allowed_protocols Allowed protocol in links
677 * @return string Filtered content through {@see 'pre_kses'} hook.
679 function wp_kses_hook( $string, $allowed_html, $allowed_protocols ) {
681 * Filters content to be run through kses.
685 * @param string $string Content to run through kses.
686 * @param array $allowed_html Allowed HTML elements.
687 * @param array $allowed_protocols Allowed protocol in links.
689 return apply_filters( 'pre_kses', $string, $allowed_html, $allowed_protocols );
693 * This function returns kses' version number.
697 * @return string KSES Version Number
699 function wp_kses_version() {
704 * Searches for HTML tags, no matter how malformed.
706 * It also matches stray ">" characters.
710 * @global array $pass_allowed_html
711 * @global array $pass_allowed_protocols
713 * @param string $string Content to filter
714 * @param array $allowed_html Allowed HTML elements
715 * @param array $allowed_protocols Allowed protocols to keep
716 * @return string Content with fixed HTML tags
718 function wp_kses_split( $string, $allowed_html, $allowed_protocols ) {
719 global $pass_allowed_html, $pass_allowed_protocols;
720 $pass_allowed_html = $allowed_html;
721 $pass_allowed_protocols = $allowed_protocols;
722 return preg_replace_callback( '%(<!--.*?(-->|$))|(<[^>]*(>|$)|>)%', '_wp_kses_split_callback', $string );
726 * Callback for wp_kses_split.
731 * @global array $pass_allowed_html
732 * @global array $pass_allowed_protocols
736 function _wp_kses_split_callback( $match ) {
737 global $pass_allowed_html, $pass_allowed_protocols;
738 return wp_kses_split2( $match[0], $pass_allowed_html, $pass_allowed_protocols );
742 * Callback for wp_kses_split for fixing malformed HTML tags.
744 * This function does a lot of work. It rejects some very malformed things like
745 * <:::>. It returns an empty string, if the element isn't allowed (look ma, no
746 * strip_tags()!). Otherwise it splits the tag into an element and an attribute
749 * After the tag is split into an element and an attribute list, it is run
750 * through another filter which will remove illegal attributes and once that is
751 * completed, will be returned.
756 * @param string $string Content to filter
757 * @param array $allowed_html Allowed HTML elements
758 * @param array $allowed_protocols Allowed protocols to keep
759 * @return string Fixed HTML element
761 function wp_kses_split2($string, $allowed_html, $allowed_protocols) {
762 $string = wp_kses_stripslashes($string);
764 if (substr($string, 0, 1) != '<')
766 // It matched a ">" character
768 if ( '<!--' == substr( $string, 0, 4 ) ) {
769 $string = str_replace( array('<!--', '-->'), '', $string );
770 while ( $string != ($newstring = wp_kses($string, $allowed_html, $allowed_protocols)) )
771 $string = $newstring;
774 // prevent multiple dashes in comments
775 $string = preg_replace('/--+/', '-', $string);
776 // prevent three dashes closing a comment
777 $string = preg_replace('/-$/', '', $string);
778 return "<!--{$string}-->";
780 // Allow HTML comments
782 if (!preg_match('%^<\s*(/\s*)?([a-zA-Z0-9-]+)([^>]*)>?$%', $string, $matches))
784 // It's seriously malformed
786 $slash = trim($matches[1]);
788 $attrlist = $matches[3];
790 if ( ! is_array( $allowed_html ) )
791 $allowed_html = wp_kses_allowed_html( $allowed_html );
793 if ( ! isset($allowed_html[strtolower($elem)]) )
795 // They are using a not allowed HTML element
799 // No attributes are allowed for closing elements
801 return wp_kses_attr( $elem, $attrlist, $allowed_html, $allowed_protocols );
805 * Removes all attributes, if none are allowed for this element.
807 * If some are allowed it calls wp_kses_hair() to split them further, and then
808 * it builds up new HTML code from the data that kses_hair() returns. It also
809 * removes "<" and ">" characters, if there are any left. One more thing it does
810 * is to check if the tag has a closing XHTML slash, and if it does, it puts one
811 * in the returned code as well.
815 * @param string $element HTML element/tag
816 * @param string $attr HTML attributes from HTML element to closing HTML element tag
817 * @param array $allowed_html Allowed HTML elements
818 * @param array $allowed_protocols Allowed protocols to keep
819 * @return string Sanitized HTML element
821 function wp_kses_attr($element, $attr, $allowed_html, $allowed_protocols) {
822 if ( ! is_array( $allowed_html ) )
823 $allowed_html = wp_kses_allowed_html( $allowed_html );
825 // Is there a closing XHTML slash at the end of the attributes?
827 if (preg_match('%\s*/\s*$%', $attr))
830 // Are any attributes allowed at all for this element?
831 if ( ! isset($allowed_html[strtolower($element)]) || count($allowed_html[strtolower($element)]) == 0 )
832 return "<$element$xhtml_slash>";
835 $attrarr = wp_kses_hair($attr, $allowed_protocols);
837 // Go through $attrarr, and save the allowed attributes for this element
840 foreach ( $attrarr as $arreach ) {
841 if ( wp_kses_attr_check( $arreach['name'], $arreach['value'], $arreach['whole'], $arreach['vless'], $element, $allowed_html ) ) {
842 $attr2 .= ' '.$arreach['whole'];
846 // Remove any "<" or ">" characters
847 $attr2 = preg_replace('/[<>]/', '', $attr2);
849 return "<$element$attr2$xhtml_slash>";
853 * Determine whether an attribute is allowed.
857 * @param string $name The attribute name. Returns empty string when not allowed.
858 * @param string $value The attribute value. Returns a filtered value.
859 * @param string $whole The name=value input. Returns filtered input.
860 * @param string $vless 'y' when attribute like "enabled", otherwise 'n'.
861 * @param string $element The name of the element to which this attribute belongs.
862 * @param array $allowed_html The full list of allowed elements and attributes.
863 * @return bool Is the attribute allowed?
865 function wp_kses_attr_check( &$name, &$value, &$whole, $vless, $element, $allowed_html ) {
866 $allowed_attr = $allowed_html[strtolower( $element )];
868 $name_low = strtolower( $name );
869 if ( ! isset( $allowed_attr[$name_low] ) || '' == $allowed_attr[$name_low] ) {
870 $name = $value = $whole = '';
874 if ( 'style' == $name_low ) {
875 $new_value = safecss_filter_attr( $value );
877 if ( empty( $new_value ) ) {
878 $name = $value = $whole = '';
882 $whole = str_replace( $value, $new_value, $whole );
886 if ( is_array( $allowed_attr[$name_low] ) ) {
887 // there are some checks
888 foreach ( $allowed_attr[$name_low] as $currkey => $currval ) {
889 if ( ! wp_kses_check_attr_val( $value, $vless, $currkey, $currval ) ) {
890 $name = $value = $whole = '';
900 * Builds an attribute list from string containing attributes.
902 * This function does a lot of work. It parses an attribute list into an array
903 * with attribute data, and tries to do the right thing even if it gets weird
904 * input. It will add quotes around attribute values that don't have any quotes
905 * or apostrophes around them, to make it easier to produce HTML code that will
906 * conform to W3C's HTML specification. It will also remove bad URL protocols
907 * from attribute values. It also reduces duplicate attributes by using the
908 * attribute defined first (foo='bar' foo='baz' will result in foo='bar').
912 * @param string $attr Attribute list from HTML element to closing HTML element tag
913 * @param array $allowed_protocols Allowed protocols to keep
914 * @return array List of attributes after parsing
916 function wp_kses_hair($attr, $allowed_protocols) {
920 $uris = array('xmlns', 'profile', 'href', 'src', 'cite', 'classid', 'codebase', 'data', 'usemap', 'longdesc', 'action');
922 // Loop through the whole attribute list
924 while (strlen($attr) != 0) {
925 $working = 0; // Was the last operation successful?
928 case 0 : // attribute name, href for instance
930 if ( preg_match('/^([-a-zA-Z:]+)/', $attr, $match ) ) {
931 $attrname = $match[1];
932 $working = $mode = 1;
933 $attr = preg_replace( '/^[-a-zA-Z:]+/', '', $attr );
938 case 1 : // equals sign or valueless ("selected")
940 if (preg_match('/^\s*=\s*/', $attr)) // equals sign
944 $attr = preg_replace('/^\s*=\s*/', '', $attr);
948 if (preg_match('/^\s+/', $attr)) // valueless
952 if(false === array_key_exists($attrname, $attrarr)) {
953 $attrarr[$attrname] = array ('name' => $attrname, 'value' => '', 'whole' => $attrname, 'vless' => 'y');
955 $attr = preg_replace('/^\s+/', '', $attr);
960 case 2 : // attribute value, a URL after href= for instance
962 if (preg_match('%^"([^"]*)"(\s+|/?$)%', $attr, $match))
965 $thisval = $match[1];
966 if ( in_array(strtolower($attrname), $uris) )
967 $thisval = wp_kses_bad_protocol($thisval, $allowed_protocols);
969 if(false === array_key_exists($attrname, $attrarr)) {
970 $attrarr[$attrname] = array ('name' => $attrname, 'value' => $thisval, 'whole' => "$attrname=\"$thisval\"", 'vless' => 'n');
974 $attr = preg_replace('/^"[^"]*"(\s+|$)/', '', $attr);
978 if (preg_match("%^'([^']*)'(\s+|/?$)%", $attr, $match))
981 $thisval = $match[1];
982 if ( in_array(strtolower($attrname), $uris) )
983 $thisval = wp_kses_bad_protocol($thisval, $allowed_protocols);
985 if(false === array_key_exists($attrname, $attrarr)) {
986 $attrarr[$attrname] = array ('name' => $attrname, 'value' => $thisval, 'whole' => "$attrname='$thisval'", 'vless' => 'n');
990 $attr = preg_replace("/^'[^']*'(\s+|$)/", '', $attr);
994 if (preg_match("%^([^\s\"']+)(\s+|/?$)%", $attr, $match))
997 $thisval = $match[1];
998 if ( in_array(strtolower($attrname), $uris) )
999 $thisval = wp_kses_bad_protocol($thisval, $allowed_protocols);
1001 if(false === array_key_exists($attrname, $attrarr)) {
1002 $attrarr[$attrname] = array ('name' => $attrname, 'value' => $thisval, 'whole' => "$attrname=\"$thisval\"", 'vless' => 'n');
1004 // We add quotes to conform to W3C's HTML spec.
1007 $attr = preg_replace("%^[^\s\"']+(\s+|$)%", '', $attr);
1013 if ($working == 0) // not well formed, remove and try again
1015 $attr = wp_kses_html_error($attr);
1020 if ($mode == 1 && false === array_key_exists($attrname, $attrarr))
1021 // special case, for when the attribute list ends with a valueless
1022 // attribute like "selected"
1023 $attrarr[$attrname] = array ('name' => $attrname, 'value' => '', 'whole' => $attrname, 'vless' => 'y');
1029 * Finds all attributes of an HTML element.
1031 * Does not modify input. May return "evil" output.
1033 * Based on wp_kses_split2() and wp_kses_attr()
1037 * @param string $element HTML element/tag
1038 * @return array|bool List of attributes found in $element. Returns false on failure.
1040 function wp_kses_attr_parse( $element ) {
1041 $valid = preg_match('%^(<\s*)(/\s*)?([a-zA-Z0-9]+\s*)([^>]*)(>?)$%', $element, $matches);
1042 if ( 1 !== $valid ) {
1046 $begin = $matches[1];
1047 $slash = $matches[2];
1048 $elname = $matches[3];
1049 $attr = $matches[4];
1052 if ( '' !== $slash ) {
1053 // Closing elements do not get parsed.
1057 // Is there a closing XHTML slash at the end of the attributes?
1058 if ( 1 === preg_match( '%\s*/\s*$%', $attr, $matches ) ) {
1059 $xhtml_slash = $matches[0];
1060 $attr = substr( $attr, 0, -strlen( $xhtml_slash ) );
1066 $attrarr = wp_kses_hair_parse( $attr );
1067 if ( false === $attrarr ) {
1071 // Make sure all input is returned by adding front and back matter.
1072 array_unshift( $attrarr, $begin . $slash . $elname );
1073 array_push( $attrarr, $xhtml_slash . $end );
1079 * Builds an attribute list from string containing attributes.
1081 * Does not modify input. May return "evil" output.
1082 * In case of unexpected input, returns false instead of stripping things.
1084 * Based on wp_kses_hair() but does not return a multi-dimensional array.
1088 * @param string $attr Attribute list from HTML element to closing HTML element tag
1089 * @return array|bool List of attributes found in $attr. Returns false on failure.
1091 function wp_kses_hair_parse( $attr ) {
1092 if ( '' === $attr ) {
1098 . '[-a-zA-Z:]+' // Attribute name.
1100 . '\[\[?[^\[\]]+\]\]?' // Shortcode in the name position implies unfiltered_html.
1102 . '(?:' // Attribute value.
1103 . '\s*=\s*' // All values begin with '='
1105 . '"[^"]*"' // Double-quoted
1107 . "'[^']*'" // Single-quoted
1109 . '[^\s"\']+' // Non-quoted
1110 . '(?:\s|$)' // Must have a space
1113 . '(?:\s|$)' // If attribute has no value, space is required.
1115 . '\s*'; // Trailing space is optional except as mentioned above.
1117 // Although it is possible to reduce this procedure to a single regexp,
1118 // we must run that regexp twice to get exactly the expected result.
1120 $validation = "%^($regex)+$%";
1121 $extraction = "%$regex%";
1123 if ( 1 === preg_match( $validation, $attr ) ) {
1124 preg_match_all( $extraction, $attr, $attrarr );
1132 * Performs different checks for attribute values.
1134 * The currently implemented checks are "maxlen", "minlen", "maxval", "minval"
1139 * @param string $value Attribute value
1140 * @param string $vless Whether the value is valueless. Use 'y' or 'n'
1141 * @param string $checkname What $checkvalue is checking for.
1142 * @param mixed $checkvalue What constraint the value should pass
1143 * @return bool Whether check passes
1145 function wp_kses_check_attr_val($value, $vless, $checkname, $checkvalue) {
1148 switch (strtolower($checkname)) {
1150 // The maxlen check makes sure that the attribute value has a length not
1151 // greater than the given value. This can be used to avoid Buffer Overflows
1152 // in WWW clients and various Internet servers.
1154 if (strlen($value) > $checkvalue)
1159 // The minlen check makes sure that the attribute value has a length not
1160 // smaller than the given value.
1162 if (strlen($value) < $checkvalue)
1167 // The maxval check does two things: it checks that the attribute value is
1168 // an integer from 0 and up, without an excessive amount of zeroes or
1169 // whitespace (to avoid Buffer Overflows). It also checks that the attribute
1170 // value is not greater than the given value.
1171 // This check can be used to avoid Denial of Service attacks.
1173 if (!preg_match('/^\s{0,6}[0-9]{1,6}\s{0,6}$/', $value))
1175 if ($value > $checkvalue)
1180 // The minval check makes sure that the attribute value is a positive integer,
1181 // and that it is not smaller than the given value.
1183 if (!preg_match('/^\s{0,6}[0-9]{1,6}\s{0,6}$/', $value))
1185 if ($value < $checkvalue)
1190 // The valueless check makes sure if the attribute has a value
1191 // (like <a href="blah">) or not (<option selected>). If the given value
1192 // is a "y" or a "Y", the attribute must not have a value.
1193 // If the given value is an "n" or an "N", the attribute must have one.
1195 if (strtolower($checkvalue) != $vless)
1204 * Sanitize string from bad protocols.
1206 * This function removes all non-allowed protocols from the beginning of
1207 * $string. It ignores whitespace and the case of the letters, and it does
1208 * understand HTML entities. It does its work in a while loop, so it won't be
1209 * fooled by a string like "javascript:javascript:alert(57)".
1213 * @param string $string Content to filter bad protocols from
1214 * @param array $allowed_protocols Allowed protocols to keep
1215 * @return string Filtered content
1217 function wp_kses_bad_protocol($string, $allowed_protocols) {
1218 $string = wp_kses_no_null($string);
1222 $original_string = $string;
1223 $string = wp_kses_bad_protocol_once($string, $allowed_protocols);
1224 } while ( $original_string != $string && ++$iterations < 6 );
1226 if ( $original_string != $string )
1233 * Removes any invalid control characters in $string.
1235 * Also removes any instance of the '\0' string.
1239 * @param string $string
1240 * @param array $options Set 'slash_zero' => 'keep' when '\0' is allowed. Default is 'remove'.
1243 function wp_kses_no_null( $string, $options = null ) {
1244 if ( ! isset( $options['slash_zero'] ) ) {
1245 $options = array( 'slash_zero' => 'remove' );
1248 $string = preg_replace( '/[\x00-\x08\x0B\x0C\x0E-\x1F]/', '', $string );
1249 if ( 'remove' == $options['slash_zero'] ) {
1250 $string = preg_replace( '/\\\\+0+/', '', $string );
1257 * Strips slashes from in front of quotes.
1259 * This function changes the character sequence \" to just ". It leaves all
1260 * other slashes alone. It's really weird, but the quoting from
1261 * preg_replace(//e) seems to require this.
1265 * @param string $string String to strip slashes
1266 * @return string Fixed string with quoted slashes
1268 function wp_kses_stripslashes($string) {
1269 return preg_replace('%\\\\"%', '"', $string);
1273 * Goes through an array and changes the keys to all lower case.
1277 * @param array $inarray Unfiltered array
1278 * @return array Fixed array with all lowercase keys
1280 function wp_kses_array_lc($inarray) {
1281 $outarray = array ();
1283 foreach ( (array) $inarray as $inkey => $inval) {
1284 $outkey = strtolower($inkey);
1285 $outarray[$outkey] = array ();
1287 foreach ( (array) $inval as $inkey2 => $inval2) {
1288 $outkey2 = strtolower($inkey2);
1289 $outarray[$outkey][$outkey2] = $inval2;
1291 } // foreach $inarray
1297 * Handles parsing errors in wp_kses_hair().
1299 * The general plan is to remove everything to and including some whitespace,
1300 * but it deals with quotes and apostrophes as well.
1304 * @param string $string
1307 function wp_kses_html_error($string) {
1308 return preg_replace('/^("[^"]*("|$)|\'[^\']*(\'|$)|\S)*\s*/', '', $string);
1312 * Sanitizes content from bad protocols and other characters.
1314 * This function searches for URL protocols at the beginning of $string, while
1315 * handling whitespace and HTML entities.
1319 * @param string $string Content to check for bad protocols
1320 * @param string $allowed_protocols Allowed protocols
1321 * @return string Sanitized content
1323 function wp_kses_bad_protocol_once($string, $allowed_protocols, $count = 1 ) {
1324 $string2 = preg_split( '/:|�*58;|�*3a;/i', $string, 2 );
1325 if ( isset($string2[1]) && ! preg_match('%/\?%', $string2[0]) ) {
1326 $string = trim( $string2[1] );
1327 $protocol = wp_kses_bad_protocol_once2( $string2[0], $allowed_protocols );
1328 if ( 'feed:' == $protocol ) {
1331 $string = wp_kses_bad_protocol_once( $string, $allowed_protocols, ++$count );
1332 if ( empty( $string ) )
1335 $string = $protocol . $string;
1342 * Callback for wp_kses_bad_protocol_once() regular expression.
1344 * This function processes URL protocols, checks to see if they're in the
1345 * whitelist or not, and returns different data depending on the answer.
1350 * @param string $string URI scheme to check against the whitelist
1351 * @param string $allowed_protocols Allowed protocols
1352 * @return string Sanitized content
1354 function wp_kses_bad_protocol_once2( $string, $allowed_protocols ) {
1355 $string2 = wp_kses_decode_entities($string);
1356 $string2 = preg_replace('/\s/', '', $string2);
1357 $string2 = wp_kses_no_null($string2);
1358 $string2 = strtolower($string2);
1361 foreach ( (array) $allowed_protocols as $one_protocol )
1362 if ( strtolower($one_protocol) == $string2 ) {
1374 * Converts and fixes HTML entities.
1376 * This function normalizes HTML entities. It will convert `AT&T` to the correct
1377 * `AT&T`, `:` to `:`, `&#XYZZY;` to `&#XYZZY;` and so on.
1381 * @param string $string Content to normalize entities
1382 * @return string Content with normalized entities
1384 function wp_kses_normalize_entities($string) {
1385 // Disarm all entities by converting & to &
1386 $string = str_replace('&', '&', $string);
1388 // Change back the allowed entities in our entity whitelist
1389 $string = preg_replace_callback('/&([A-Za-z]{2,8}[0-9]{0,2});/', 'wp_kses_named_entities', $string);
1390 $string = preg_replace_callback('/&#(0*[0-9]{1,7});/', 'wp_kses_normalize_entities2', $string);
1391 $string = preg_replace_callback('/&#[Xx](0*[0-9A-Fa-f]{1,6});/', 'wp_kses_normalize_entities3', $string);
1397 * Callback for wp_kses_normalize_entities() regular expression.
1399 * This function only accepts valid named entity references, which are finite,
1400 * case-sensitive, and highly scrutinized by HTML and XML validators.
1404 * @global array $allowedentitynames
1406 * @param array $matches preg_replace_callback() matches array
1407 * @return string Correctly encoded entity
1409 function wp_kses_named_entities($matches) {
1410 global $allowedentitynames;
1412 if ( empty($matches[1]) )
1416 return ( ! in_array( $i, $allowedentitynames ) ) ? "&$i;" : "&$i;";
1420 * Callback for wp_kses_normalize_entities() regular expression.
1422 * This function helps wp_kses_normalize_entities() to only accept 16-bit
1423 * values and nothing more for `&#number;` entities.
1428 * @param array $matches preg_replace_callback() matches array
1429 * @return string Correctly encoded entity
1431 function wp_kses_normalize_entities2($matches) {
1432 if ( empty($matches[1]) )
1436 if (valid_unicode($i)) {
1437 $i = str_pad(ltrim($i,'0'), 3, '0', STR_PAD_LEFT);
1447 * Callback for wp_kses_normalize_entities() for regular expression.
1449 * This function helps wp_kses_normalize_entities() to only accept valid Unicode
1450 * numeric entities in hex form.
1454 * @param array $matches preg_replace_callback() matches array
1455 * @return string Correctly encoded entity
1457 function wp_kses_normalize_entities3($matches) {
1458 if ( empty($matches[1]) )
1461 $hexchars = $matches[1];
1462 return ( ! valid_unicode( hexdec( $hexchars ) ) ) ? "&#x$hexchars;" : '&#x'.ltrim($hexchars,'0').';';
1466 * Helper function to determine if a Unicode value is valid.
1468 * @param int $i Unicode value
1469 * @return bool True if the value was a valid Unicode number
1471 function valid_unicode($i) {
1472 return ( $i == 0x9 || $i == 0xa || $i == 0xd ||
1473 ($i >= 0x20 && $i <= 0xd7ff) ||
1474 ($i >= 0xe000 && $i <= 0xfffd) ||
1475 ($i >= 0x10000 && $i <= 0x10ffff) );
1479 * Convert all entities to their character counterparts.
1481 * This function decodes numeric HTML entities (`A` and `A`).
1482 * It doesn't do anything with other entities like ä, but we don't
1483 * need them in the URL protocol whitelisting system anyway.
1487 * @param string $string Content to change entities
1488 * @return string Content after decoded entities
1490 function wp_kses_decode_entities($string) {
1491 $string = preg_replace_callback('/&#([0-9]+);/', '_wp_kses_decode_entities_chr', $string);
1492 $string = preg_replace_callback('/&#[Xx]([0-9A-Fa-f]+);/', '_wp_kses_decode_entities_chr_hexdec', $string);
1498 * Regex callback for wp_kses_decode_entities()
1500 * @param array $match preg match
1503 function _wp_kses_decode_entities_chr( $match ) {
1504 return chr( $match[1] );
1508 * Regex callback for wp_kses_decode_entities()
1510 * @param array $match preg match
1513 function _wp_kses_decode_entities_chr_hexdec( $match ) {
1514 return chr( hexdec( $match[1] ) );
1518 * Sanitize content with allowed HTML Kses rules.
1522 * @param string $data Content to filter, expected to be escaped with slashes
1523 * @return string Filtered content
1525 function wp_filter_kses( $data ) {
1526 return addslashes( wp_kses( stripslashes( $data ), current_filter() ) );
1530 * Sanitize content with allowed HTML Kses rules.
1534 * @param string $data Content to filter, expected to not be escaped
1535 * @return string Filtered content
1537 function wp_kses_data( $data ) {
1538 return wp_kses( $data, current_filter() );
1542 * Sanitize content for allowed HTML tags for post content.
1544 * Post content refers to the page contents of the 'post' type and not $_POST
1549 * @param string $data Post content to filter, expected to be escaped with slashes
1550 * @return string Filtered post content with allowed HTML tags and attributes intact.
1552 function wp_filter_post_kses( $data ) {
1553 return addslashes( wp_kses( stripslashes( $data ), 'post' ) );
1557 * Sanitize content for allowed HTML tags for post content.
1559 * Post content refers to the page contents of the 'post' type and not $_POST
1564 * @param string $data Post content to filter
1565 * @return string Filtered post content with allowed HTML tags and attributes intact.
1567 function wp_kses_post( $data ) {
1568 return wp_kses( $data, 'post' );
1572 * Navigates through an array, object, or scalar, and sanitizes content for
1573 * allowed HTML tags for post content.
1579 * @param mixed $data The array, object, or scalar value to inspect.
1580 * @return mixed The filtered content.
1582 function wp_kses_post_deep( $data ) {
1583 return map_deep( $data, 'wp_kses_post' );
1587 * Strips all of the HTML in the content.
1591 * @param string $data Content to strip all HTML from
1592 * @return string Filtered content without any HTML
1594 function wp_filter_nohtml_kses( $data ) {
1595 return addslashes( wp_kses( stripslashes( $data ), 'strip' ) );
1599 * Adds all Kses input form content filters.
1601 * All hooks have default priority. The wp_filter_kses() function is added to
1602 * the 'pre_comment_content' and 'title_save_pre' hooks.
1604 * The wp_filter_post_kses() function is added to the 'content_save_pre',
1605 * 'excerpt_save_pre', and 'content_filtered_save_pre' hooks.
1609 function kses_init_filters() {
1611 add_filter('title_save_pre', 'wp_filter_kses');
1613 // Comment filtering
1614 if ( current_user_can( 'unfiltered_html' ) )
1615 add_filter( 'pre_comment_content', 'wp_filter_post_kses' );
1617 add_filter( 'pre_comment_content', 'wp_filter_kses' );
1620 add_filter('content_save_pre', 'wp_filter_post_kses');
1621 add_filter('excerpt_save_pre', 'wp_filter_post_kses');
1622 add_filter('content_filtered_save_pre', 'wp_filter_post_kses');
1626 * Removes all Kses input form content filters.
1628 * A quick procedural method to removing all of the filters that kses uses for
1629 * content in WordPress Loop.
1631 * Does not remove the kses_init() function from {@see 'init'} hook (priority is
1632 * default). Also does not remove kses_init() function from {@see 'set_current_user'}
1633 * hook (priority is also default).
1637 function kses_remove_filters() {
1639 remove_filter('title_save_pre', 'wp_filter_kses');
1641 // Comment filtering
1642 remove_filter( 'pre_comment_content', 'wp_filter_post_kses' );
1643 remove_filter( 'pre_comment_content', 'wp_filter_kses' );
1646 remove_filter('content_save_pre', 'wp_filter_post_kses');
1647 remove_filter('excerpt_save_pre', 'wp_filter_post_kses');
1648 remove_filter('content_filtered_save_pre', 'wp_filter_post_kses');
1652 * Sets up most of the Kses filters for input form content.
1654 * If you remove the kses_init() function from {@see 'init'} hook and
1655 * {@see 'set_current_user'} (priority is default), then none of the Kses filter hooks
1658 * First removes all of the Kses filters in case the current user does not need
1659 * to have Kses filter the content. If the user does not have unfiltered_html
1660 * capability, then Kses filters are added.
1664 function kses_init() {
1665 kses_remove_filters();
1667 if ( ! current_user_can( 'unfiltered_html' ) ) {
1668 kses_init_filters();
1677 * @param string $css A string of CSS rules.
1678 * @param string $deprecated Not used.
1679 * @return string Filtered string of CSS rules.
1681 function safecss_filter_attr( $css, $deprecated = '' ) {
1682 if ( !empty( $deprecated ) )
1683 _deprecated_argument( __FUNCTION__, '2.8.1' ); // Never implemented
1685 $css = wp_kses_no_null($css);
1686 $css = str_replace(array("\n","\r","\t"), '', $css);
1688 if ( preg_match( '%[\\\\(&=}]|/\*%', $css ) ) // remove any inline css containing \ ( & } = or comments
1691 $css_array = explode( ';', trim( $css ) );
1694 * Filters list of allowed CSS attributes.
1697 * @since 4.4.0 Added support for `min-height`, `max-height`, `min-width`, and `max-width`.
1698 * @since 4.6.0 Added support for `list-style-type`.
1700 * @param array $attr List of allowed CSS attributes.
1702 $allowed_attr = apply_filters( 'safe_style_css', array(
1711 'border-right-color',
1712 'border-right-style',
1713 'border-right-width',
1715 'border-bottom-color',
1716 'border-bottom-style',
1717 'border-bottom-width',
1719 'border-left-color',
1720 'border-left-style',
1721 'border-left-width',
1773 if ( empty($allowed_attr) )
1777 foreach ( $css_array as $css_item ) {
1778 if ( $css_item == '' )
1780 $css_item = trim( $css_item );
1782 if ( strpos( $css_item, ':' ) === false ) {
1785 $parts = explode( ':', $css_item );
1786 if ( in_array( trim( $parts[0] ), $allowed_attr ) )
1800 * Helper function to add global attributes to a tag in the allowed html list.
1805 * @param array $value An array of attributes.
1806 * @return array The array of attributes with global attributes added.
1808 function _wp_add_global_attributes( $value ) {
1809 $global_attributes = array(
1817 if ( true === $value )
1820 if ( is_array( $value ) )
1821 return array_merge( $value, $global_attributes );