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.
39 if ( ! defined( 'CUSTOM_TAGS' ) )
40 define( 'CUSTOM_TAGS', false );
42 if ( ! CUSTOM_TAGS ) {
44 * Kses global for default allowable HTML tags.
46 * Can be override by using CUSTOM_TAGS constant.
48 * @global array $allowedposttags
51 $allowedposttags = array(
73 'xml:lang' => array(),
81 'xml:lang' => array(),
85 'blockquote' => array(
90 'xml:lang' => array()),
94 'disabled' => array (),
100 'class' => array ()),
105 'title' => array ()),
111 'charoff' => array (),
115 'valign' => array (),
116 'width' => array ()),
118 'datetime' => array ()),
127 'xml:lang' => array(),
135 'xml:lang' => array()),
139 'fieldset' => array(),
146 'xml:lang' => array(),
148 'figcaption' => array(
154 'xml:lang' => array(),
166 'xml:lang' => array(),
169 'action' => array (),
170 'accept' => array (),
171 'accept-charset' => array (),
172 'enctype' => array (),
173 'method' => array (),
175 'target' => array ()),
180 'style' => array ()),
185 'style' => array ()),
190 'style' => array ()),
195 'style' => array ()),
200 'style' => array ()),
205 'style' => array ()),
212 'xml:lang' => array(),
220 'xml:lang' => array(),
225 'noshade' => array (),
227 'width' => array ()),
232 'border' => array (),
234 'height' => array (),
235 'hspace' => array (),
236 'longdesc' => array (),
237 'vspace' => array (),
240 'width' => array ()),
242 'datetime' => array (),
248 'align' => array ()),
251 'class' => array ()),
262 'xml:lang' => array(),
270 'xml:lang' => array()),
273 'width' => array ()),
284 'xml:lang' => array()),
291 'xml:lang' => array(),
302 'xml:lang' => array(),
307 'bgcolor' => array (),
308 'border' => array (),
309 'cellpadding' => array (),
310 'cellspacing' => array (),
316 'summary' => array (),
317 'width' => array ()),
321 'charoff' => array (),
322 'valign' => array ()),
327 'bgcolor' => array (),
329 'charoff' => array (),
331 'colspan' => array (),
333 'headers' => array (),
334 'height' => array (),
335 'nowrap' => array (),
336 'rowspan' => array (),
339 'valign' => array (),
340 'width' => array ()),
344 'disabled' => array (),
346 'readonly' => array ()),
351 'charoff' => array (),
352 'valign' => array ()),
357 'bgcolor' => array (),
359 'charoff' => array (),
361 'colspan' => array (),
362 'headers' => array (),
363 'height' => array (),
364 'nowrap' => array (),
365 'rowspan' => array (),
367 'valign' => array (),
368 'width' => array ()),
372 'charoff' => array (),
374 'valign' => array ()),
378 'bgcolor' => array (),
380 'charoff' => array (),
383 'valign' => array ()),
398 * Kses allowed HTML elements.
400 * @global array $allowedtags
403 $allowedtags = array(
406 'title' => array ()),
408 'title' => array ()),
410 'title' => array ()),
412 'blockquote' => array(
418 'datetime' => array ()),
422 'em' => array (), 'i' => array (),
423 // 'ins' => array('datetime' => array(), 'cite' => array()),
437 $allowedentitynames = array(
438 'nbsp', 'iexcl', 'cent', 'pound', 'curren', 'yen',
439 'brvbar', 'sect', 'uml', 'copy', 'ordf', 'laquo',
440 'not', 'shy', 'reg', 'macr', 'deg', 'plusmn',
441 'acute', 'micro', 'para', 'middot', 'cedil', 'ordm',
442 'raquo', 'iquest', 'Agrave', 'Aacute', 'Acirc', 'Atilde',
443 'Auml', 'Aring', 'AElig', 'Ccedil', 'Egrave', 'Eacute',
444 'Ecirc', 'Euml', 'Igrave', 'Iacute', 'Icirc', 'Iuml',
445 'ETH', 'Ntilde', 'Ograve', 'Oacute', 'Ocirc', 'Otilde',
446 'Ouml', 'times', 'Oslash', 'Ugrave', 'Uacute', 'Ucirc',
447 'Uuml', 'Yacute', 'THORN', 'szlig', 'agrave', 'aacute',
448 'acirc', 'atilde', 'auml', 'aring', 'aelig', 'ccedil',
449 'egrave', 'eacute', 'ecirc', 'euml', 'igrave', 'iacute',
450 'icirc', 'iuml', 'eth', 'ntilde', 'ograve', 'oacute',
451 'ocirc', 'otilde', 'ouml', 'divide', 'oslash', 'ugrave',
452 'uacute', 'ucirc', 'uuml', 'yacute', 'thorn', 'yuml',
453 'quot', 'amp', 'lt', 'gt', 'apos', 'OElig',
454 'oelig', 'Scaron', 'scaron', 'Yuml', 'circ', 'tilde',
455 'ensp', 'emsp', 'thinsp', 'zwnj', 'zwj', 'lrm',
456 'rlm', 'ndash', 'mdash', 'lsquo', 'rsquo', 'sbquo',
457 'ldquo', 'rdquo', 'bdquo', 'dagger', 'Dagger', 'permil',
458 'lsaquo', 'rsaquo', 'euro', 'fnof', 'Alpha', 'Beta',
459 'Gamma', 'Delta', 'Epsilon', 'Zeta', 'Eta', 'Theta',
460 'Iota', 'Kappa', 'Lambda', 'Mu', 'Nu', 'Xi',
461 'Omicron', 'Pi', 'Rho', 'Sigma', 'Tau', 'Upsilon',
462 'Phi', 'Chi', 'Psi', 'Omega', 'alpha', 'beta',
463 'gamma', 'delta', 'epsilon', 'zeta', 'eta', 'theta',
464 'iota', 'kappa', 'lambda', 'mu', 'nu', 'xi',
465 'omicron', 'pi', 'rho', 'sigmaf', 'sigma', 'tau',
466 'upsilon', 'phi', 'chi', 'psi', 'omega', 'thetasym',
467 'upsih', 'piv', 'bull', 'hellip', 'prime', 'Prime',
468 'oline', 'frasl', 'weierp', 'image', 'real', 'trade',
469 'alefsym', 'larr', 'uarr', 'rarr', 'darr', 'harr',
470 'crarr', 'lArr', 'uArr', 'rArr', 'dArr', 'hArr',
471 'forall', 'part', 'exist', 'empty', 'nabla', 'isin',
472 'notin', 'ni', 'prod', 'sum', 'minus', 'lowast',
473 'radic', 'prop', 'infin', 'ang', 'and', 'or',
474 'cap', 'cup', 'int', 'sim', 'cong', 'asymp',
475 'ne', 'equiv', 'le', 'ge', 'sub', 'sup',
476 'nsub', 'sube', 'supe', 'oplus', 'otimes', 'perp',
477 'sdot', 'lceil', 'rceil', 'lfloor', 'rfloor', 'lang',
478 'rang', 'loz', 'spades', 'clubs', 'hearts', 'diams',
483 * Filters content and keeps only allowable HTML elements.
485 * This function makes sure that only the allowed HTML element names, attribute
486 * names and attribute values plus only sane HTML entities will occur in
487 * $string. You have to remove any slashes from PHP's magic quotes before you
488 * call this function.
490 * The default allowed protocols are 'http', 'https', 'ftp', 'mailto', 'news',
491 * 'irc', 'gopher', 'nntp', 'feed', 'telnet, 'mms', 'rtsp' and 'svn'. This
492 * covers all common link protocols, except for 'javascript' which should not
493 * be allowed for untrusted users.
497 * @param string $string Content to filter through kses
498 * @param array $allowed_html List of allowed HTML elements
499 * @param array $allowed_protocols Optional. Allowed protocol in links.
500 * @return string Filtered content with only allowed HTML elements
502 function wp_kses($string, $allowed_html, $allowed_protocols = array ()) {
503 $allowed_protocols = wp_parse_args( $allowed_protocols, apply_filters('kses_allowed_protocols', array ('http', 'https', 'ftp', 'ftps', 'mailto', 'news', 'irc', 'gopher', 'nntp', 'feed', 'telnet', 'mms', 'rtsp', 'svn') ));
504 $string = wp_kses_no_null($string);
505 $string = wp_kses_js_entities($string);
506 $string = wp_kses_normalize_entities($string);
507 $allowed_html_fixed = wp_kses_array_lc($allowed_html);
508 $string = wp_kses_hook($string, $allowed_html_fixed, $allowed_protocols); // WP changed the order of these funcs and added args to wp_kses_hook
509 return wp_kses_split($string, $allowed_html_fixed, $allowed_protocols);
513 * You add any kses hooks here.
515 * There is currently only one kses WordPress hook and it is called here. All
516 * parameters are passed to the hooks and expected to receive a string.
520 * @param string $string Content to filter through kses
521 * @param array $allowed_html List of allowed HTML elements
522 * @param array $allowed_protocols Allowed protocol in links
523 * @return string Filtered content through 'pre_kses' hook
525 function wp_kses_hook($string, $allowed_html, $allowed_protocols) {
526 $string = apply_filters('pre_kses', $string, $allowed_html, $allowed_protocols);
531 * This function returns kses' version number.
535 * @return string KSES Version Number
537 function wp_kses_version() {
542 * Searches for HTML tags, no matter how malformed.
544 * It also matches stray ">" characters.
548 * @param string $string Content to filter
549 * @param array $allowed_html Allowed HTML elements
550 * @param array $allowed_protocols Allowed protocols to keep
551 * @return string Content with fixed HTML tags
553 function wp_kses_split($string, $allowed_html, $allowed_protocols) {
554 global $pass_allowed_html, $pass_allowed_protocols;
555 $pass_allowed_html = $allowed_html;
556 $pass_allowed_protocols = $allowed_protocols;
557 return preg_replace_callback( '%(<!--.*?(-->|$))|(<[^>]*(>|$)|>)%', '_wp_kses_split_callback', $string );
561 * Callback for wp_kses_split.
566 function _wp_kses_split_callback( $match ) {
567 global $pass_allowed_html, $pass_allowed_protocols;
568 return wp_kses_split2( $match[0], $pass_allowed_html, $pass_allowed_protocols );
572 * Callback for wp_kses_split for fixing malformed HTML tags.
574 * This function does a lot of work. It rejects some very malformed things like
575 * <:::>. It returns an empty string, if the element isn't allowed (look ma, no
576 * strip_tags()!). Otherwise it splits the tag into an element and an attribute
579 * After the tag is split into an element and an attribute list, it is run
580 * through another filter which will remove illegal attributes and once that is
581 * completed, will be returned.
585 * @uses wp_kses_attr()
587 * @param string $string Content to filter
588 * @param array $allowed_html Allowed HTML elements
589 * @param array $allowed_protocols Allowed protocols to keep
590 * @return string Fixed HTML element
592 function wp_kses_split2($string, $allowed_html, $allowed_protocols) {
593 $string = wp_kses_stripslashes($string);
595 if (substr($string, 0, 1) != '<')
597 # It matched a ">" character
599 if ( '<!--' == substr( $string, 0, 4 ) ) {
600 $string = str_replace( array('<!--', '-->'), '', $string );
601 while ( $string != ($newstring = wp_kses($string, $allowed_html, $allowed_protocols)) )
602 $string = $newstring;
605 // prevent multiple dashes in comments
606 $string = preg_replace('/--+/', '-', $string);
607 // prevent three dashes closing a comment
608 $string = preg_replace('/-$/', '', $string);
609 return "<!--{$string}-->";
611 # Allow HTML comments
613 if (!preg_match('%^<\s*(/\s*)?([a-zA-Z0-9]+)([^>]*)>?$%', $string, $matches))
615 # It's seriously malformed
617 $slash = trim($matches[1]);
619 $attrlist = $matches[3];
621 if ( ! isset($allowed_html[strtolower($elem)]) )
623 # They are using a not allowed HTML element
627 # No attributes are allowed for closing elements
629 return wp_kses_attr( $elem, $attrlist, $allowed_html, $allowed_protocols );
633 * Removes all attributes, if none are allowed for this element.
635 * If some are allowed it calls wp_kses_hair() to split them further, and then
636 * it builds up new HTML code from the data that kses_hair() returns. It also
637 * removes "<" and ">" characters, if there are any left. One more thing it does
638 * is to check if the tag has a closing XHTML slash, and if it does, it puts one
639 * in the returned code as well.
643 * @param string $element HTML element/tag
644 * @param string $attr HTML attributes from HTML element to closing HTML element tag
645 * @param array $allowed_html Allowed HTML elements
646 * @param array $allowed_protocols Allowed protocols to keep
647 * @return string Sanitized HTML element
649 function wp_kses_attr($element, $attr, $allowed_html, $allowed_protocols) {
650 # Is there a closing XHTML slash at the end of the attributes?
653 if (preg_match('%\s*/\s*$%', $attr))
656 # Are any attributes allowed at all for this element?
657 if ( ! isset($allowed_html[strtolower($element)]) || count($allowed_html[strtolower($element)]) == 0 )
658 return "<$element$xhtml_slash>";
661 $attrarr = wp_kses_hair($attr, $allowed_protocols);
663 # Go through $attrarr, and save the allowed attributes for this element
667 $allowed_attr = $allowed_html[strtolower($element)];
668 foreach ($attrarr as $arreach) {
669 if ( ! isset( $allowed_attr[strtolower($arreach['name'])] ) )
670 continue; # the attribute is not allowed
672 $current = $allowed_attr[strtolower($arreach['name'])];
673 if ( $current == '' )
674 continue; # the attribute is not allowed
676 if ( ! is_array($current) ) {
677 $attr2 .= ' '.$arreach['whole'];
678 # there are no checks
681 # there are some checks
683 foreach ($current as $currkey => $currval) {
684 if ( ! wp_kses_check_attr_val($arreach['value'], $arreach['vless'], $currkey, $currval) ) {
690 if ( strtolower($arreach['name']) == 'style' ) {
691 $orig_value = $arreach['value'];
692 $value = safecss_filter_attr($orig_value);
697 $arreach['value'] = $value;
698 $arreach['whole'] = str_replace($orig_value, $value, $arreach['whole']);
702 $attr2 .= ' '.$arreach['whole']; # it passed them
703 } # if !is_array($current)
706 # Remove any "<" or ">" characters
707 $attr2 = preg_replace('/[<>]/', '', $attr2);
709 return "<$element$attr2$xhtml_slash>";
713 * Builds an attribute list from string containing attributes.
715 * This function does a lot of work. It parses an attribute list into an array
716 * with attribute data, and tries to do the right thing even if it gets weird
717 * input. It will add quotes around attribute values that don't have any quotes
718 * or apostrophes around them, to make it easier to produce HTML code that will
719 * conform to W3C's HTML specification. It will also remove bad URL protocols
720 * from attribute values. It also reduces duplicate attributes by using the
721 * attribute defined first (foo='bar' foo='baz' will result in foo='bar').
725 * @param string $attr Attribute list from HTML element to closing HTML element tag
726 * @param array $allowed_protocols Allowed protocols to keep
727 * @return array List of attributes after parsing
729 function wp_kses_hair($attr, $allowed_protocols) {
733 $uris = array('xmlns', 'profile', 'href', 'src', 'cite', 'classid', 'codebase', 'data', 'usemap', 'longdesc', 'action');
735 # Loop through the whole attribute list
737 while (strlen($attr) != 0) {
738 $working = 0; # Was the last operation successful?
741 case 0 : # attribute name, href for instance
743 if (preg_match('/^([-a-zA-Z]+)/', $attr, $match)) {
744 $attrname = $match[1];
745 $working = $mode = 1;
746 $attr = preg_replace('/^[-a-zA-Z]+/', '', $attr);
751 case 1 : # equals sign or valueless ("selected")
753 if (preg_match('/^\s*=\s*/', $attr)) # equals sign
757 $attr = preg_replace('/^\s*=\s*/', '', $attr);
761 if (preg_match('/^\s+/', $attr)) # valueless
765 if(FALSE === array_key_exists($attrname, $attrarr)) {
766 $attrarr[$attrname] = array ('name' => $attrname, 'value' => '', 'whole' => $attrname, 'vless' => 'y');
768 $attr = preg_replace('/^\s+/', '', $attr);
773 case 2 : # attribute value, a URL after href= for instance
775 if (preg_match('%^"([^"]*)"(\s+|/?$)%', $attr, $match))
778 $thisval = $match[1];
779 if ( in_array(strtolower($attrname), $uris) )
780 $thisval = wp_kses_bad_protocol($thisval, $allowed_protocols);
782 if(FALSE === array_key_exists($attrname, $attrarr)) {
783 $attrarr[$attrname] = array ('name' => $attrname, 'value' => $thisval, 'whole' => "$attrname=\"$thisval\"", 'vless' => 'n');
787 $attr = preg_replace('/^"[^"]*"(\s+|$)/', '', $attr);
791 if (preg_match("%^'([^']*)'(\s+|/?$)%", $attr, $match))
794 $thisval = $match[1];
795 if ( in_array(strtolower($attrname), $uris) )
796 $thisval = wp_kses_bad_protocol($thisval, $allowed_protocols);
798 if(FALSE === array_key_exists($attrname, $attrarr)) {
799 $attrarr[$attrname] = array ('name' => $attrname, 'value' => $thisval, 'whole' => "$attrname='$thisval'", 'vless' => 'n');
803 $attr = preg_replace("/^'[^']*'(\s+|$)/", '', $attr);
807 if (preg_match("%^([^\s\"']+)(\s+|/?$)%", $attr, $match))
810 $thisval = $match[1];
811 if ( in_array(strtolower($attrname), $uris) )
812 $thisval = wp_kses_bad_protocol($thisval, $allowed_protocols);
814 if(FALSE === array_key_exists($attrname, $attrarr)) {
815 $attrarr[$attrname] = array ('name' => $attrname, 'value' => $thisval, 'whole' => "$attrname=\"$thisval\"", 'vless' => 'n');
817 # We add quotes to conform to W3C's HTML spec.
820 $attr = preg_replace("%^[^\s\"']+(\s+|$)%", '', $attr);
826 if ($working == 0) # not well formed, remove and try again
828 $attr = wp_kses_html_error($attr);
833 if ($mode == 1 && FALSE === array_key_exists($attrname, $attrarr))
834 # special case, for when the attribute list ends with a valueless
835 # attribute like "selected"
836 $attrarr[$attrname] = array ('name' => $attrname, 'value' => '', 'whole' => $attrname, 'vless' => 'y');
842 * Performs different checks for attribute values.
844 * The currently implemented checks are "maxlen", "minlen", "maxval", "minval"
845 * and "valueless" with even more checks to come soon.
849 * @param string $value Attribute value
850 * @param string $vless Whether the value is valueless. Use 'y' or 'n'
851 * @param string $checkname What $checkvalue is checking for.
852 * @param mixed $checkvalue What constraint the value should pass
853 * @return bool Whether check passes
855 function wp_kses_check_attr_val($value, $vless, $checkname, $checkvalue) {
858 switch (strtolower($checkname)) {
860 # The maxlen check makes sure that the attribute value has a length not
861 # greater than the given value. This can be used to avoid Buffer Overflows
862 # in WWW clients and various Internet servers.
864 if (strlen($value) > $checkvalue)
869 # The minlen check makes sure that the attribute value has a length not
870 # smaller than the given value.
872 if (strlen($value) < $checkvalue)
877 # The maxval check does two things: it checks that the attribute value is
878 # an integer from 0 and up, without an excessive amount of zeroes or
879 # whitespace (to avoid Buffer Overflows). It also checks that the attribute
880 # value is not greater than the given value.
881 # This check can be used to avoid Denial of Service attacks.
883 if (!preg_match('/^\s{0,6}[0-9]{1,6}\s{0,6}$/', $value))
885 if ($value > $checkvalue)
890 # The minval check checks that the attribute value is a positive integer,
891 # and that it is not smaller than the given value.
893 if (!preg_match('/^\s{0,6}[0-9]{1,6}\s{0,6}$/', $value))
895 if ($value < $checkvalue)
900 # The valueless check checks if the attribute has a value
901 # (like <a href="blah">) or not (<option selected>). If the given value
902 # is a "y" or a "Y", the attribute must not have a value.
903 # If the given value is an "n" or an "N", the attribute must have one.
905 if (strtolower($checkvalue) != $vless)
914 * Sanitize string from bad protocols.
916 * This function removes all non-allowed protocols from the beginning of
917 * $string. It ignores whitespace and the case of the letters, and it does
918 * understand HTML entities. It does its work in a while loop, so it won't be
919 * fooled by a string like "javascript:javascript:alert(57)".
923 * @param string $string Content to filter bad protocols from
924 * @param array $allowed_protocols Allowed protocols to keep
925 * @return string Filtered content
927 function wp_kses_bad_protocol($string, $allowed_protocols) {
928 $string = wp_kses_no_null($string);
929 $string2 = $string.'a';
931 while ($string != $string2) {
933 $string = wp_kses_bad_protocol_once($string, $allowed_protocols);
940 * Removes any NULL characters in $string.
944 * @param string $string
947 function wp_kses_no_null($string) {
948 $string = preg_replace('/\0+/', '', $string);
949 $string = preg_replace('/(\\\\0)+/', '', $string);
955 * Strips slashes from in front of quotes.
957 * This function changes the character sequence \" to just ". It leaves all
958 * other slashes alone. It's really weird, but the quoting from
959 * preg_replace(//e) seems to require this.
963 * @param string $string String to strip slashes
964 * @return string Fixed strings with quoted slashes
966 function wp_kses_stripslashes($string) {
967 return preg_replace('%\\\\"%', '"', $string);
971 * Goes through an array and changes the keys to all lower case.
975 * @param array $inarray Unfiltered array
976 * @return array Fixed array with all lowercase keys
978 function wp_kses_array_lc($inarray) {
979 $outarray = array ();
981 foreach ( (array) $inarray as $inkey => $inval) {
982 $outkey = strtolower($inkey);
983 $outarray[$outkey] = array ();
985 foreach ( (array) $inval as $inkey2 => $inval2) {
986 $outkey2 = strtolower($inkey2);
987 $outarray[$outkey][$outkey2] = $inval2;
995 * Removes the HTML JavaScript entities found in early versions of Netscape 4.
999 * @param string $string
1002 function wp_kses_js_entities($string) {
1003 return preg_replace('%&\s*\{[^}]*(\}\s*;?|$)%', '', $string);
1007 * Handles parsing errors in wp_kses_hair().
1009 * The general plan is to remove everything to and including some whitespace,
1010 * but it deals with quotes and apostrophes as well.
1014 * @param string $string
1017 function wp_kses_html_error($string) {
1018 return preg_replace('/^("[^"]*("|$)|\'[^\']*(\'|$)|\S)*\s*/', '', $string);
1022 * Sanitizes content from bad protocols and other characters.
1024 * This function searches for URL protocols at the beginning of $string, while
1025 * handling whitespace and HTML entities.
1029 * @param string $string Content to check for bad protocols
1030 * @param string $allowed_protocols Allowed protocols
1031 * @return string Sanitized content
1033 function wp_kses_bad_protocol_once($string, $allowed_protocols) {
1034 $string2 = preg_split( '/:|�*58;|�*3a;/i', $string, 2 );
1035 if ( isset($string2[1]) && ! preg_match('%/\?%', $string2[0]) )
1036 $string = wp_kses_bad_protocol_once2( $string2[0], $allowed_protocols ) . trim( $string2[1] );
1042 * Callback for wp_kses_bad_protocol_once() regular expression.
1044 * This function processes URL protocols, checks to see if they're in the
1045 * white-list or not, and returns different data depending on the answer.
1050 * @param string $string URI scheme to check against the whitelist
1051 * @param string $allowed_protocols Allowed protocols
1052 * @return string Sanitized content
1054 function wp_kses_bad_protocol_once2( $string, $allowed_protocols ) {
1055 $string2 = wp_kses_decode_entities($string);
1056 $string2 = preg_replace('/\s/', '', $string2);
1057 $string2 = wp_kses_no_null($string2);
1058 $string2 = strtolower($string2);
1061 foreach ( (array) $allowed_protocols as $one_protocol )
1062 if ( strtolower($one_protocol) == $string2 ) {
1074 * Converts and fixes HTML entities.
1076 * This function normalizes HTML entities. It will convert "AT&T" to the correct
1077 * "AT&T", ":" to ":", "&#XYZZY;" to "&#XYZZY;" and so on.
1081 * @param string $string Content to normalize entities
1082 * @return string Content with normalized entities
1084 function wp_kses_normalize_entities($string) {
1085 # Disarm all entities by converting & to &
1087 $string = str_replace('&', '&', $string);
1089 # Change back the allowed entities in our entity whitelist
1091 $string = preg_replace_callback('/&([A-Za-z]{2,8});/', 'wp_kses_named_entities', $string);
1092 $string = preg_replace_callback('/&#(0*[0-9]{1,7});/', 'wp_kses_normalize_entities2', $string);
1093 $string = preg_replace_callback('/&#[Xx](0*[0-9A-Fa-f]{1,6});/', 'wp_kses_normalize_entities3', $string);
1099 * Callback for wp_kses_normalize_entities() regular expression.
1101 * This function only accepts valid named entity references, which are finite,
1102 * case-sensitive, and highly scrutinized by HTML and XML validators.
1106 * @param array $matches preg_replace_callback() matches array
1107 * @return string Correctly encoded entity
1109 function wp_kses_named_entities($matches) {
1110 global $allowedentitynames;
1112 if ( empty($matches[1]) )
1116 return ( ( ! in_array($i, $allowedentitynames) ) ? "&$i;" : "&$i;" );
1120 * Callback for wp_kses_normalize_entities() regular expression.
1122 * This function helps wp_kses_normalize_entities() to only accept 16 bit values
1123 * and nothing more for &#number; entities.
1128 * @param array $matches preg_replace_callback() matches array
1129 * @return string Correctly encoded entity
1131 function wp_kses_normalize_entities2($matches) {
1132 if ( empty($matches[1]) )
1136 if (valid_unicode($i)) {
1137 $i = str_pad(ltrim($i,'0'), 3, '0', STR_PAD_LEFT);
1147 * Callback for wp_kses_normalize_entities() for regular expression.
1149 * This function helps wp_kses_normalize_entities() to only accept valid Unicode
1150 * numeric entities in hex form.
1154 * @param array $matches preg_replace_callback() matches array
1155 * @return string Correctly encoded entity
1157 function wp_kses_normalize_entities3($matches) {
1158 if ( empty($matches[1]) )
1161 $hexchars = $matches[1];
1162 return ( ( ! valid_unicode(hexdec($hexchars)) ) ? "&#x$hexchars;" : '&#x'.ltrim($hexchars,'0').';' );
1166 * Helper function to determine if a Unicode value is valid.
1168 * @param int $i Unicode value
1169 * @return bool true if the value was a valid Unicode number
1171 function valid_unicode($i) {
1172 return ( $i == 0x9 || $i == 0xa || $i == 0xd ||
1173 ($i >= 0x20 && $i <= 0xd7ff) ||
1174 ($i >= 0xe000 && $i <= 0xfffd) ||
1175 ($i >= 0x10000 && $i <= 0x10ffff) );
1179 * Convert all entities to their character counterparts.
1181 * This function decodes numeric HTML entities (A and A). It doesn't do
1182 * anything with other entities like ä, but we don't need them in the URL
1183 * protocol whitelisting system anyway.
1187 * @param string $string Content to change entities
1188 * @return string Content after decoded entities
1190 function wp_kses_decode_entities($string) {
1191 $string = preg_replace_callback('/&#([0-9]+);/', '_wp_kses_decode_entities_chr', $string);
1192 $string = preg_replace_callback('/&#[Xx]([0-9A-Fa-f]+);/', '_wp_kses_decode_entities_chr_hexdec', $string);
1198 * Regex callback for wp_kses_decode_entities()
1200 * @param array $match preg match
1203 function _wp_kses_decode_entities_chr( $match ) {
1204 return chr( $match[1] );
1208 * Regex callback for wp_kses_decode_entities()
1210 * @param array $match preg match
1213 function _wp_kses_decode_entities_chr_hexdec( $match ) {
1214 return chr( hexdec( $match[1] ) );
1218 * Sanitize content with allowed HTML Kses rules.
1221 * @uses $allowedtags
1223 * @param string $data Content to filter, expected to be escaped with slashes
1224 * @return string Filtered content
1226 function wp_filter_kses($data) {
1227 global $allowedtags;
1228 return addslashes( wp_kses(stripslashes( $data ), $allowedtags) );
1232 * Sanitize content with allowed HTML Kses rules.
1235 * @uses $allowedtags
1237 * @param string $data Content to filter, expected to not be escaped
1238 * @return string Filtered content
1240 function wp_kses_data($data) {
1241 global $allowedtags;
1242 return wp_kses( $data , $allowedtags );
1246 * Sanitize content for allowed HTML tags for post content.
1248 * Post content refers to the page contents of the 'post' type and not $_POST
1252 * @uses $allowedposttags
1254 * @param string $data Post content to filter, expected to be escaped with slashes
1255 * @return string Filtered post content with allowed HTML tags and attributes intact.
1257 function wp_filter_post_kses($data) {
1258 global $allowedposttags;
1259 return addslashes ( wp_kses(stripslashes( $data ), $allowedposttags) );
1263 * Sanitize content for allowed HTML tags for post content.
1265 * Post content refers to the page contents of the 'post' type and not $_POST
1269 * @uses $allowedposttags
1271 * @param string $data Post content to filter
1272 * @return string Filtered post content with allowed HTML tags and attributes intact.
1274 function wp_kses_post($data) {
1275 global $allowedposttags;
1276 return wp_kses( $data , $allowedposttags );
1280 * Strips all of the HTML in the content.
1284 * @param string $data Content to strip all HTML from
1285 * @return string Filtered content without any HTML
1287 function wp_filter_nohtml_kses($data) {
1288 return addslashes ( wp_kses(stripslashes( $data ), array()) );
1292 * Adds all Kses input form content filters.
1294 * All hooks have default priority. The wp_filter_kses() function is added to
1295 * the 'pre_comment_content' and 'title_save_pre' hooks.
1297 * The wp_filter_post_kses() function is added to the 'content_save_pre',
1298 * 'excerpt_save_pre', and 'content_filtered_save_pre' hooks.
1301 * @uses add_filter() See description for what functions are added to what hooks.
1303 function kses_init_filters() {
1304 // Normal filtering.
1305 add_filter('pre_comment_content', 'wp_filter_kses');
1306 add_filter('title_save_pre', 'wp_filter_kses');
1309 add_filter('content_save_pre', 'wp_filter_post_kses');
1310 add_filter('excerpt_save_pre', 'wp_filter_post_kses');
1311 add_filter('content_filtered_save_pre', 'wp_filter_post_kses');
1315 * Removes all Kses input form content filters.
1317 * A quick procedural method to removing all of the filters that kses uses for
1318 * content in WordPress Loop.
1320 * Does not remove the kses_init() function from 'init' hook (priority is
1321 * default). Also does not remove kses_init() function from 'set_current_user'
1322 * hook (priority is also default).
1326 function kses_remove_filters() {
1327 // Normal filtering.
1328 remove_filter('pre_comment_content', 'wp_filter_kses');
1329 remove_filter('title_save_pre', 'wp_filter_kses');
1332 remove_filter('content_save_pre', 'wp_filter_post_kses');
1333 remove_filter('excerpt_save_pre', 'wp_filter_post_kses');
1334 remove_filter('content_filtered_save_pre', 'wp_filter_post_kses');
1338 * Sets up most of the Kses filters for input form content.
1340 * If you remove the kses_init() function from 'init' hook and
1341 * 'set_current_user' (priority is default), then none of the Kses filter hooks
1344 * First removes all of the Kses filters in case the current user does not need
1345 * to have Kses filter the content. If the user does not have unfiltered html
1346 * capability, then Kses filters are added.
1348 * @uses kses_remove_filters() Removes the Kses filters
1349 * @uses kses_init_filters() Adds the Kses filters back if the user
1350 * does not have unfiltered HTML capability.
1353 function kses_init() {
1354 kses_remove_filters();
1356 if (current_user_can('unfiltered_html') == false)
1357 kses_init_filters();
1360 add_action('init', 'kses_init');
1361 add_action('set_current_user', 'kses_init');
1368 function safecss_filter_attr( $css, $deprecated = '' ) {
1369 if ( !empty( $deprecated ) )
1370 _deprecated_argument( __FUNCTION__, '2.8.1' ); // Never implemented
1372 $css = wp_kses_no_null($css);
1373 $css = str_replace(array("\n","\r","\t"), '', $css);
1375 if ( preg_match( '%[\\(&=}]|/\*%', $css ) ) // remove any inline css containing \ ( & } = or comments
1378 $css_array = explode( ';', trim( $css ) );
1379 $allowed_attr = apply_filters( 'safe_style_css', array( 'text-align', 'margin', 'color', 'float',
1380 'border', 'background', 'background-color', 'border-bottom', 'border-bottom-color',
1381 'border-bottom-style', 'border-bottom-width', 'border-collapse', 'border-color', 'border-left',
1382 'border-left-color', 'border-left-style', 'border-left-width', 'border-right', 'border-right-color',
1383 'border-right-style', 'border-right-width', 'border-spacing', 'border-style', 'border-top',
1384 'border-top-color', 'border-top-style', 'border-top-width', 'border-width', 'caption-side',
1385 'clear', 'cursor', 'direction', 'font', 'font-family', 'font-size', 'font-style',
1386 'font-variant', 'font-weight', 'height', 'letter-spacing', 'line-height', 'margin-bottom',
1387 'margin-left', 'margin-right', 'margin-top', 'overflow', 'padding', 'padding-bottom',
1388 'padding-left', 'padding-right', 'padding-top', 'text-decoration', 'text-indent', 'vertical-align',
1391 if ( empty($allowed_attr) )
1395 foreach ( $css_array as $css_item ) {
1396 if ( $css_item == '' )
1398 $css_item = trim( $css_item );
1400 if ( strpos( $css_item, ':' ) === false ) {
1403 $parts = split( ':', $css_item );
1404 if ( in_array( trim( $parts[0] ), $allowed_attr ) )