3 // Added wp_ prefix to avoid conflicts with existing kses users
4 # kses 0.2.2 - HTML/XHTML filter that only allows some elements and attributes
5 # Copyright (C) 2002, 2003, 2005 Ulf Harnhammar
6 # *** CONTACT INFORMATION ***
8 # E-mail: metaur at users dot sourceforge dot net
9 # Web page: http://sourceforge.net/projects/kses
10 # Paper mail: Ulf Harnhammar
15 # [kses strips evil scripts!]
16 if (!defined('CUSTOM_TAGS'))
17 define('CUSTOM_TAGS', false);
19 // You can override this in your my-hacks.php file
21 $allowedposttags = array(
24 'href' => array(), 'title' => array(),
25 'rel' => array(), 'rev' => array(),
29 'title' => array(), 'class' => array()
36 'blockquote' => array(
37 'cite' => array(), 'xml:lang' => array(),
42 'disabled' => array(), 'name' => array(),
43 'type' => array(), 'value' => array()
50 'align' => array(), 'char' => array(),
51 'charoff' => array(), 'span' => array(),
52 'valign' => array(), 'width' => array()
59 'align' => array(), 'xml:lang' => array(),
65 'fieldset' => array(),
67 'color' => array(), 'face' => array(),
71 'action' => array(), 'accept' => array(),
72 'accept-charset' => array(), 'enctype' => array(),
73 'method' => array(), 'name' => array(),
95 'align' => array(), 'noshade' => array(),
96 'size' => array(), 'width' => array()
100 'alt' => array(), 'align' => array(),
101 'border' => array(), 'height' => array(),
102 'hspace' => array(), 'longdesc' => array(),
103 'vspace' => array(), 'src' => array(),
107 'datetime' => array(), 'cite' => array()
118 'align' => array(), 'xml:lang' => array(),
133 'align' => array(), 'bgcolor' => array(),
134 'border' => array(), 'cellpadding' => array(),
135 'cellspacing' => array(), 'rules' => array(),
136 'summary' => array(), 'width' => array()
139 'align' => array(), 'char' => array(),
140 'charoff' => array(), 'valign' => array()
143 'abbr' => array(), 'align' => array(),
144 'axis' => array(), 'bgcolor' => array(),
145 'char' => array(), 'charoff' => array(),
146 'colspan' => array(), 'headers' => array(),
147 'height' => array(), 'nowrap' => array(),
148 'rowspan' => array(), 'scope' => array(),
149 'valign' => array(), 'width' => array()
152 'cols' => array(), 'rows' => array(),
153 'disabled' => array(), 'name' => array(),
154 'readonly' => array()
157 'align' => array(), 'char' => array(),
158 'charoff' => array(), 'valign' => array()
161 'abbr' => array(), 'align' => array(),
162 'axis' => array(), 'bgcolor' => array(),
163 'char' => array(), 'charoff' => array(),
164 'colspan' => array(), 'headers' => array(),
165 'height' => array(), 'nowrap' => array(),
166 'rowspan' => array(), 'scope' => array(),
167 'valign' => array(), 'width' => array()
170 'align' => array(), 'char' => array(),
171 'charoff' => array(), 'valign' => array()
175 'align' => array(), 'bgcolor' => array(),
176 'char' => array(), 'charoff' => array(),
186 $allowedtags = array(
188 'href' => array(), 'title' => array()
197 'blockquote' => array(
202 // 'del' => array('datetime' => array()),
208 // 'ins' => array('datetime' => array(), 'cite' => array()),
222 function wp_kses($string, $allowed_html, $allowed_protocols = array ('http', 'https', 'ftp', 'ftps', 'mailto', 'news', 'irc', 'gopher', 'nntp', 'feed', 'telnet'))
223 ###############################################################################
224 # This function makes sure that only the allowed HTML element names, attribute
225 # names and attribute values plus only sane HTML entities will occur in
226 # $string. You have to remove any slashes from PHP's magic quotes before you
227 # call this function.
228 ###############################################################################
230 $string = wp_kses_no_null($string);
231 $string = wp_kses_js_entities($string);
232 $string = wp_kses_normalize_entities($string);
233 $allowed_html_fixed = wp_kses_array_lc($allowed_html);
234 $string = wp_kses_hook($string, $allowed_html_fixed, $allowed_protocols); // WP changed the order of these funcs and added args to wp_kses_hook
235 return wp_kses_split($string, $allowed_html_fixed, $allowed_protocols);
238 function wp_kses_hook($string, $allowed_html, $allowed_protocols)
239 ###############################################################################
240 # You add any kses hooks here.
241 ###############################################################################
243 $string = apply_filters('pre_kses', $string, $allowed_html, $allowed_protocols);
245 } # function wp_kses_hook
247 function wp_kses_version()
248 ###############################################################################
249 # This function returns kses' version number.
250 ###############################################################################
253 } # function wp_kses_version
255 function wp_kses_split($string, $allowed_html, $allowed_protocols)
256 ###############################################################################
257 # This function searches for HTML tags, no matter how malformed. It also
258 # matches stray ">" characters.
259 ###############################################################################
261 return preg_replace('%((<!--.*?(-->|$))|(<[^>]*(>|$)|>))%e',
262 "wp_kses_split2('\\1', \$allowed_html, ".'$allowed_protocols)', $string);
263 } # function wp_kses_split
265 function wp_kses_split2($string, $allowed_html, $allowed_protocols)
266 ###############################################################################
267 # This function does a lot of work. It rejects some very malformed things
268 # like <:::>. It returns an empty string, if the element isn't allowed (look
269 # ma, no strip_tags()!). Otherwise it splits the tag into an element and an
271 ###############################################################################
273 $string = wp_kses_stripslashes($string);
275 if (substr($string, 0, 1) != '<')
277 # It matched a ">" character
279 if (preg_match('%^<!--(.*?)(-->)?$%', $string, $matches)) {
280 $string = str_replace(array('<!--', '-->'), '', $matches[1]);
281 while ( $string != $newstring = wp_kses($string, $allowed_html, $allowed_protocols) )
282 $string = $newstring;
285 return "<!--{$string}-->";
287 # Allow HTML comments
289 if (!preg_match('%^<\s*(/\s*)?([a-zA-Z0-9]+)([^>]*)>?$%', $string, $matches))
291 # It's seriously malformed
293 $slash = trim($matches[1]);
295 $attrlist = $matches[3];
297 if (!@isset($allowed_html[strtolower($elem)]))
299 # They are using a not allowed HTML element
302 return "<$slash$elem>";
303 # No attributes are allowed for closing elements
305 return wp_kses_attr("$slash$elem", $attrlist, $allowed_html, $allowed_protocols);
306 } # function wp_kses_split2
308 function wp_kses_attr($element, $attr, $allowed_html, $allowed_protocols)
309 ###############################################################################
310 # This function removes all attributes, if none are allowed for this element.
311 # If some are allowed it calls wp_kses_hair() to split them further, and then it
312 # builds up new HTML code from the data that kses_hair() returns. It also
313 # removes "<" and ">" characters, if there are any left. One more thing it
314 # does is to check if the tag has a closing XHTML slash, and if it does,
315 # it puts one in the returned code as well.
316 ###############################################################################
318 # Is there a closing XHTML slash at the end of the attributes?
321 if (preg_match('%\s/\s*$%', $attr))
324 # Are any attributes allowed at all for this element?
326 if (@ count($allowed_html[strtolower($element)]) == 0)
327 return "<$element$xhtml_slash>";
331 $attrarr = wp_kses_hair($attr, $allowed_protocols);
333 # Go through $attrarr, and save the allowed attributes for this element
338 foreach ($attrarr as $arreach) {
339 if (!@ isset ($allowed_html[strtolower($element)][strtolower($arreach['name'])]))
340 continue; # the attribute is not allowed
342 $current = $allowed_html[strtolower($element)][strtolower($arreach['name'])];
344 continue; # the attribute is not allowed
346 if (!is_array($current))
347 $attr2 .= ' '.$arreach['whole'];
348 # there are no checks
351 # there are some checks
353 foreach ($current as $currkey => $currval)
354 if (!wp_kses_check_attr_val($arreach['value'], $arreach['vless'], $currkey, $currval)) {
360 $attr2 .= ' '.$arreach['whole']; # it passed them
361 } # if !is_array($current)
364 # Remove any "<" or ">" characters
366 $attr2 = preg_replace('/[<>]/', '', $attr2);
368 return "<$element$attr2$xhtml_slash>";
369 } # function wp_kses_attr
371 function wp_kses_hair($attr, $allowed_protocols)
372 ###############################################################################
373 # This function does a lot of work. It parses an attribute list into an array
374 # with attribute data, and tries to do the right thing even if it gets weird
375 # input. It will add quotes around attribute values that don't have any quotes
376 # or apostrophes around them, to make it easier to produce HTML code that will
377 # conform to W3C's HTML specification. It will also remove bad URL protocols
378 # from attribute values.
379 ###############################################################################
385 # Loop through the whole attribute list
387 while (strlen($attr) != 0) {
388 $working = 0; # Was the last operation successful?
391 case 0 : # attribute name, href for instance
393 if (preg_match('/^([-a-zA-Z]+)/', $attr, $match)) {
394 $attrname = $match[1];
395 $working = $mode = 1;
396 $attr = preg_replace('/^[-a-zA-Z]+/', '', $attr);
401 case 1 : # equals sign or valueless ("selected")
403 if (preg_match('/^\s*=\s*/', $attr)) # equals sign
407 $attr = preg_replace('/^\s*=\s*/', '', $attr);
411 if (preg_match('/^\s+/', $attr)) # valueless
415 $attrarr[] = array ('name' => $attrname, 'value' => '', 'whole' => $attrname, 'vless' => 'y');
416 $attr = preg_replace('/^\s+/', '', $attr);
421 case 2 : # attribute value, a URL after href= for instance
423 if (preg_match('/^"([^"]*)"(\s+|$)/', $attr, $match))
426 $thisval = wp_kses_bad_protocol($match[1], $allowed_protocols);
428 $attrarr[] = array ('name' => $attrname, 'value' => $thisval, 'whole' => "$attrname=\"$thisval\"", 'vless' => 'n');
431 $attr = preg_replace('/^"[^"]*"(\s+|$)/', '', $attr);
435 if (preg_match("/^'([^']*)'(\s+|$)/", $attr, $match))
438 $thisval = wp_kses_bad_protocol($match[1], $allowed_protocols);
440 $attrarr[] = array ('name' => $attrname, 'value' => $thisval, 'whole' => "$attrname='$thisval'", 'vless' => 'n');
443 $attr = preg_replace("/^'[^']*'(\s+|$)/", '', $attr);
447 if (preg_match("%^([^\s\"']+)(\s+|$)%", $attr, $match))
450 $thisval = wp_kses_bad_protocol($match[1], $allowed_protocols);
452 $attrarr[] = array ('name' => $attrname, 'value' => $thisval, 'whole' => "$attrname=\"$thisval\"", 'vless' => 'n');
453 # We add quotes to conform to W3C's HTML spec.
456 $attr = preg_replace("%^[^\s\"']+(\s+|$)%", '', $attr);
462 if ($working == 0) # not well formed, remove and try again
464 $attr = wp_kses_html_error($attr);
470 # special case, for when the attribute list ends with a valueless
471 # attribute like "selected"
472 $attrarr[] = array ('name' => $attrname, 'value' => '', 'whole' => $attrname, 'vless' => 'y');
475 } # function wp_kses_hair
477 function wp_kses_check_attr_val($value, $vless, $checkname, $checkvalue)
478 ###############################################################################
479 # This function performs different checks for attribute values. The currently
480 # implemented checks are "maxlen", "minlen", "maxval", "minval" and "valueless"
481 # with even more checks to come soon.
482 ###############################################################################
486 switch (strtolower($checkname)) {
488 # The maxlen check makes sure that the attribute value has a length not
489 # greater than the given value. This can be used to avoid Buffer Overflows
490 # in WWW clients and various Internet servers.
492 if (strlen($value) > $checkvalue)
497 # The minlen check makes sure that the attribute value has a length not
498 # smaller than the given value.
500 if (strlen($value) < $checkvalue)
505 # The maxval check does two things: it checks that the attribute value is
506 # an integer from 0 and up, without an excessive amount of zeroes or
507 # whitespace (to avoid Buffer Overflows). It also checks that the attribute
508 # value is not greater than the given value.
509 # This check can be used to avoid Denial of Service attacks.
511 if (!preg_match('/^\s{0,6}[0-9]{1,6}\s{0,6}$/', $value))
513 if ($value > $checkvalue)
518 # The minval check checks that the attribute value is a positive integer,
519 # and that it is not smaller than the given value.
521 if (!preg_match('/^\s{0,6}[0-9]{1,6}\s{0,6}$/', $value))
523 if ($value < $checkvalue)
528 # The valueless check checks if the attribute has a value
529 # (like <a href="blah">) or not (<option selected>). If the given value
530 # is a "y" or a "Y", the attribute must not have a value.
531 # If the given value is an "n" or an "N", the attribute must have one.
533 if (strtolower($checkvalue) != $vless)
539 } # function wp_kses_check_attr_val
541 function wp_kses_bad_protocol($string, $allowed_protocols)
542 ###############################################################################
543 # This function removes all non-allowed protocols from the beginning of
544 # $string. It ignores whitespace and the case of the letters, and it does
545 # understand HTML entities. It does its work in a while loop, so it won't be
546 # fooled by a string like "javascript:javascript:alert(57)".
547 ###############################################################################
549 $string = wp_kses_no_null($string);
550 $string = preg_replace('/\xad+/', '', $string); # deals with Opera "feature"
551 $string2 = $string.'a';
553 while ($string != $string2) {
555 $string = wp_kses_bad_protocol_once($string, $allowed_protocols);
559 } # function wp_kses_bad_protocol
561 function wp_kses_no_null($string)
562 ###############################################################################
563 # This function removes any NULL characters in $string.
564 ###############################################################################
566 $string = preg_replace('/\0+/', '', $string);
567 $string = preg_replace('/(\\\\0)+/', '', $string);
570 } # function wp_kses_no_null
572 function wp_kses_stripslashes($string)
573 ###############################################################################
574 # This function changes the character sequence \" to just "
575 # It leaves all other slashes alone. It's really weird, but the quoting from
576 # preg_replace(//e) seems to require this.
577 ###############################################################################
579 return preg_replace('%\\\\"%', '"', $string);
580 } # function wp_kses_stripslashes
582 function wp_kses_array_lc($inarray)
583 ###############################################################################
584 # This function goes through an array, and changes the keys to all lower case.
585 ###############################################################################
587 $outarray = array ();
589 foreach ($inarray as $inkey => $inval) {
590 $outkey = strtolower($inkey);
591 $outarray[$outkey] = array ();
593 foreach ($inval as $inkey2 => $inval2) {
594 $outkey2 = strtolower($inkey2);
595 $outarray[$outkey][$outkey2] = $inval2;
600 } # function wp_kses_array_lc
602 function wp_kses_js_entities($string)
603 ###############################################################################
604 # This function removes the HTML JavaScript entities found in early versions of
606 ###############################################################################
608 return preg_replace('%&\s*\{[^}]*(\}\s*;?|$)%', '', $string);
609 } # function wp_kses_js_entities
611 function wp_kses_html_error($string)
612 ###############################################################################
613 # This function deals with parsing errors in wp_kses_hair(). The general plan is
614 # to remove everything to and including some whitespace, but it deals with
615 # quotes and apostrophes as well.
616 ###############################################################################
618 return preg_replace('/^("[^"]*("|$)|\'[^\']*(\'|$)|\S)*\s*/', '', $string);
619 } # function wp_kses_html_error
621 function wp_kses_bad_protocol_once($string, $allowed_protocols)
622 ###############################################################################
623 # This function searches for URL protocols at the beginning of $string, while
624 # handling whitespace and HTML entities.
625 ###############################################################################
627 return preg_replace('/^((&[^;]*;|[\sA-Za-z0-9])*)'.'(:|:|&#[Xx]3[Aa];)\s*/e', 'wp_kses_bad_protocol_once2("\\1", $allowed_protocols)', $string);
628 } # function wp_kses_bad_protocol_once
630 function wp_kses_bad_protocol_once2($string, $allowed_protocols)
631 ###############################################################################
632 # This function processes URL protocols, checks to see if they're in the white-
633 # list or not, and returns different data depending on the answer.
634 ###############################################################################
636 $string2 = wp_kses_decode_entities($string);
637 $string2 = preg_replace('/\s/', '', $string2);
638 $string2 = wp_kses_no_null($string2);
639 $string2 = preg_replace('/\xad+/', '', $string2);
640 # deals with Opera "feature"
641 $string2 = strtolower($string2);
644 foreach ($allowed_protocols as $one_protocol)
645 if (strtolower($one_protocol) == $string2) {
654 } # function wp_kses_bad_protocol_once2
656 function wp_kses_normalize_entities($string)
657 ###############################################################################
658 # This function normalizes HTML entities. It will convert "AT&T" to the correct
659 # "AT&T", ":" to ":", "&#XYZZY;" to "&#XYZZY;" and so on.
660 ###############################################################################
662 # Disarm all entities by converting & to &
664 $string = str_replace('&', '&', $string);
666 # Change back the allowed entities in our entity whitelist
668 $string = preg_replace('/&([A-Za-z][A-Za-z0-9]{0,19});/', '&\\1;', $string);
669 $string = preg_replace('/&#0*([0-9]{1,5});/e', 'wp_kses_normalize_entities2("\\1")', $string);
670 $string = preg_replace('/&#([Xx])0*(([0-9A-Fa-f]{2}){1,2});/', '&#\\1\\2;', $string);
673 } # function wp_kses_normalize_entities
675 function wp_kses_normalize_entities2($i)
676 ###############################################################################
677 # This function helps wp_kses_normalize_entities() to only accept 16 bit values
678 # and nothing more for &#number; entities.
679 ###############################################################################
681 return (($i > 65535) ? "&#$i;" : "&#$i;");
682 } # function wp_kses_normalize_entities2
684 function wp_kses_decode_entities($string)
685 ###############################################################################
686 # This function decodes numeric HTML entities (A and A). It doesn't
687 # do anything with other entities like ä, but we don't need them in the
688 # URL protocol whitelisting system anyway.
689 ###############################################################################
691 $string = preg_replace('/&#([0-9]+);/e', 'chr("\\1")', $string);
692 $string = preg_replace('/&#[Xx]([0-9A-Fa-f]+);/e', 'chr(hexdec("\\1"))', $string);
695 } # function wp_kses_decode_entities
697 function wp_filter_kses($data) {
699 return addslashes( wp_kses(stripslashes( $data ), $allowedtags) );
702 function wp_filter_post_kses($data) {
703 global $allowedposttags;
704 return addslashes ( wp_kses(stripslashes( $data ), $allowedposttags) );
707 function wp_filter_nohtml_kses($data) {
708 return addslashes ( wp_kses(stripslashes( $data ), array()) );
711 function kses_init_filters() {
713 add_filter('pre_comment_content', 'wp_filter_kses');
714 add_filter('title_save_pre', 'wp_filter_kses');
717 add_filter('content_save_pre', 'wp_filter_post_kses');
718 add_filter('excerpt_save_pre', 'wp_filter_post_kses');
719 add_filter('content_filtered_save_pre', 'wp_filter_post_kses');
722 function kses_remove_filters() {
724 remove_filter('pre_comment_content', 'wp_filter_kses');
725 remove_filter('title_save_pre', 'wp_filter_kses');
728 remove_filter('content_save_pre', 'wp_filter_post_kses');
729 remove_filter('excerpt_save_pre', 'wp_filter_post_kses');
730 remove_filter('content_filtered_save_pre', 'wp_filter_post_kses');
733 function kses_init() {
734 kses_remove_filters();
736 if (current_user_can('unfiltered_html') == false)
740 add_action('init', 'kses_init');
741 add_action('set_current_user', 'kses_init');