3
# kses 0.2.1 - HTML/XHTML filter that only allows some elements and attributes
4
# Copyright (C) 2002, 2003 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
# 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA or visit
19
# http://www.gnu.org/licenses/gpl.html
21
# *** CONTACT INFORMATION ***
23
# E-mail: metaur at users dot sourceforge dot net
24
# Web page: http://sourceforge.net/projects/kses
25
# Paper mail: (not at the moment)
27
# [kses strips evil scripts!]
30
function kses($string, $allowed_html, $allowed_protocols =
31
array('http', 'https', 'ftp', 'news', 'nntp', 'telnet',
33
###############################################################################
34
# This function makes sure that only the allowed HTML element names, attribute
35
# names and attribute values plus only sane HTML entities will occur in
36
# $string. You have to remove any slashes from PHP's magic quotes before you
38
###############################################################################
40
$string = kses_no_null($string);
41
$string = kses_js_entities($string);
42
$string = kses_normalize_entities($string);
43
$string = kses_hook($string);
44
$allowed_html_fixed = kses_array_lc($allowed_html);
45
return kses_split($string, $allowed_html_fixed, $allowed_protocols);
49
function kses_hook($string)
50
###############################################################################
51
# You add any kses hooks here.
52
###############################################################################
55
} # function kses_hook
58
function kses_version()
59
###############################################################################
60
# This function returns kses' version number.
61
###############################################################################
64
} # function kses_version
67
function kses_split($string, $allowed_html, $allowed_protocols)
68
###############################################################################
69
# This function searches for HTML tags, no matter how malformed. It also
70
# matches stray ">" characters.
71
###############################################################################
73
return preg_replace('%(<'. # EITHER: <
74
'[^>]*'. # things that aren't >
75
'(>|$)'. # > or end of string
76
'|>)%e', # OR: just a >
77
"kses_split2('\\1', \$allowed_html, ".
78
'$allowed_protocols)',
80
} # function kses_split
83
function kses_split2($string, $allowed_html, $allowed_protocols)
84
###############################################################################
85
# This function does a lot of work. It rejects some very malformed things
86
# like <:::>. It returns an empty string, if the element isn't allowed (look
87
# ma, no strip_tags()!). Otherwise it splits the tag into an element and an
89
###############################################################################
91
$string = kses_stripslashes($string);
93
if (substr($string, 0, 1) != '<')
95
# It matched a ">" character
97
if (!preg_match('%^<\s*(/\s*)?([a-zA-Z0-9]+)([^>]*)>?$%', $string, $matches))
99
# It's seriously malformed
101
$slash = trim($matches[1]);
103
$attrlist = $matches[3];
106
if ( !is_array($allowed_html[strtolower($elem)]))
108
# They are using a not allowed HTML element
111
return kses_attr("$slash$elem", $attrlist, $allowed_html,
113
} # function kses_split2
116
function kses_attr($element, $attr, $allowed_html, $allowed_protocols)
117
###############################################################################
118
# This function removes all attributes, if none are allowed for this element.
119
# If some are allowed it calls kses_hair() to split them further, and then it
120
# builds up new HTML code from the data that kses_hair() returns. It also
121
# removes "<" and ">" characters, if there are any left. One more thing it
122
# does is to check if the tag has a closing XHTML slash, and if it does,
123
# it puts one in the returned code as well.
124
###############################################################################
126
# Is there a closing XHTML slash at the end of the attributes?
129
if (preg_match('%\s/\s*$%', $attr))
132
# Are any attributes allowed at all for this element?
134
if (count($allowed_html[strtolower($element)]) == 0)
135
return "<$element$xhtml_slash>";
139
$attrarr = kses_hair($attr, $allowed_protocols);
141
# Go through $attrarr, and save the allowed attributes for this element
146
foreach ($attrarr as $arreach)
148
$current = $allowed_html[strtolower($element)]
149
[strtolower($arreach['name'])];
151
continue; # the attribute is not allowed
153
if (!is_array($current))
154
$attr2 .= ' '.$arreach['whole'];
155
# there are no checks
159
# there are some checks
161
foreach ($current as $currkey => $currval)
162
if (!kses_check_attr_val($arreach['value'], $arreach['vless'],
164
{ $ok = false; break; }
167
$attr2 .= ' '.$arreach['whole']; # it passed them
168
} # if !is_array($current)
171
# Remove any "<" or ">" characters
173
$attr2 = preg_replace('/[<>]/', '', $attr2);
175
return "<$element$attr2$xhtml_slash>";
176
} # function kses_attr
179
function kses_hair($attr, $allowed_protocols)
180
###############################################################################
181
# This function does a lot of work. It parses an attribute list into an array
182
# with attribute data, and tries to do the right thing even if it gets weird
183
# input. It will add quotes around attribute values that don't have any quotes
184
# or apostrophes around them, to make it easier to produce HTML code that will
185
# conform to W3C's HTML specification. It will also remove bad URL protocols
186
# from attribute values.
187
###############################################################################
193
# Loop through the whole attribute list
195
while (strlen($attr) != 0)
197
$working = 0; # Was the last operation successful?
201
case 0: # attribute name, href for instance
203
if (preg_match('/^([-a-zA-Z]+)/', $attr, $match))
205
$attrname = $match[1];
206
$working = $mode = 1;
207
$attr = preg_replace('/^[-a-zA-Z]+/', '', $attr);
212
case 1: # equals sign or valueless ("selected")
214
if (preg_match('/^\s*=\s*/', $attr)) # equals sign
216
$working = 1; $mode = 2;
217
$attr = preg_replace('/^\s*=\s*/', '', $attr);
221
if (preg_match('/^\s+/', $attr)) # valueless
223
$working = 1; $mode = 0;
225
('name' => $attrname,
227
'whole' => $attrname,
229
$attr = preg_replace('/^\s+/', '', $attr);
234
case 2: # attribute value, a URL after href= for instance
236
if (preg_match('/^"([^"]*)"(\s+|$)/', $attr, $match))
239
$thisval = kses_bad_protocol($match[1], $allowed_protocols);
242
('name' => $attrname,
244
'whole' => "$attrname=\"$thisval\"",
246
$working = 1; $mode = 0;
247
$attr = preg_replace('/^"[^"]*"(\s+|$)/', '', $attr);
251
if (preg_match("/^'([^']*)'(\s+|$)/", $attr, $match))
254
$thisval = kses_bad_protocol($match[1], $allowed_protocols);
257
('name' => $attrname,
259
'whole' => "$attrname='$thisval'",
261
$working = 1; $mode = 0;
262
$attr = preg_replace("/^'[^']*'(\s+|$)/", '', $attr);
266
if (preg_match("%^([^\s\"']+)(\s+|$)%", $attr, $match))
269
$thisval = kses_bad_protocol($match[1], $allowed_protocols);
272
('name' => $attrname,
274
'whole' => "$attrname=\"$thisval\"",
276
# We add quotes to conform to W3C's HTML spec.
277
$working = 1; $mode = 0;
278
$attr = preg_replace("%^[^\s\"']+(\s+|$)%", '', $attr);
284
if ($working == 0) # not well formed, remove and try again
286
$attr = kses_html_error($attr);
292
# special case, for when the attribute list ends with a valueless
293
# attribute like "selected"
295
('name' => $attrname,
297
'whole' => $attrname,
301
} # function kses_hair
304
function kses_check_attr_val($value, $vless, $checkname, $checkvalue)
305
###############################################################################
306
# This function performs different checks for attribute values. The currently
307
# implemented checks are "maxlen", "minlen", "maxval", "minval" and "valueless"
308
# with even more checks to come soon.
309
###############################################################################
313
switch (strtolower($checkname))
316
# The maxlen check makes sure that the attribute value has a length not
317
# greater than the given value. This can be used to avoid Buffer Overflows
318
# in WWW clients and various Internet servers.
320
if (strlen($value) > $checkvalue)
325
# The minlen check makes sure that the attribute value has a length not
326
# smaller than the given value.
328
if (strlen($value) < $checkvalue)
333
# The maxval check does two things: it checks that the attribute value is
334
# an integer from 0 and up, without an excessive amount of zeroes or
335
# whitespace (to avoid Buffer Overflows). It also checks that the attribute
336
# value is not greater than the given value.
337
# This check can be used to avoid Denial of Service attacks.
339
if (!preg_match('/^\s{0,6}[0-9]{1,6}\s{0,6}$/', $value))
341
if ($value > $checkvalue)
346
# The minval check checks that the attribute value is a positive integer,
347
# and that it is not smaller than the given value.
349
if (!preg_match('/^\s{0,6}[0-9]{1,6}\s{0,6}$/', $value))
351
if ($value < $checkvalue)
356
# The valueless check checks if the attribute has a value
357
# (like <a href="blah">) or not (<option selected>). If the given value
358
# is a "y" or a "Y", the attribute must not have a value.
359
# If the given value is an "n" or an "N", the attribute must have one.
361
if (strtolower($checkvalue) != $vless)
367
} # function kses_check_attr_val
370
function kses_bad_protocol($string, $allowed_protocols)
371
###############################################################################
372
# This function removes all non-allowed protocols from the beginning of
373
# $string. It ignores whitespace and the case of the letters, and it does
374
# understand HTML entities. It does its work in a while loop, so it won't be
375
# fooled by a string like "javascript:javascript:alert(57)".
376
###############################################################################
378
$string = kses_no_null($string);
379
$string2 = $string.'a';
380
while ($string != $string2)
383
$string = kses_bad_protocol_once($string, $allowed_protocols);
387
} # function kses_bad_protocol
390
function kses_no_null($string)
391
###############################################################################
392
# This function removes any NULL or chr(173) characters in $string.
393
###############################################################################
395
$string = preg_replace('/\0+/', '', $string);
396
$string = preg_replace('/(\\\\0)+/', '', $string);
398
$string = preg_replace('/\xad+/', '', $string); # deals with Opera "feature"
401
} # function kses_no_null
404
function kses_stripslashes($string)
405
###############################################################################
406
# This function changes the character sequence \" to just "
407
# It leaves all other slashes alone. It's really weird, but the quoting from
408
# preg_replace(//e) seems to require this.
409
###############################################################################
411
return preg_replace('%\\\\"%', '"', $string);
412
} # function kses_stripslashes
415
function kses_array_lc($inarray)
416
###############################################################################
417
# This function goes through an array, and changes the keys to all lower case.
418
###############################################################################
422
foreach ($inarray as $inkey => $inval)
424
$outkey = strtolower($inkey);
425
$outarray[$outkey] = array();
427
foreach ($inval as $inkey2 => $inval2)
429
$outkey2 = strtolower($inkey2);
430
$outarray[$outkey][$outkey2] = $inval2;
435
} # function kses_array_lc
438
function kses_js_entities($string)
439
###############################################################################
440
# This function removes the HTML JavaScript entities found in early versions of
442
###############################################################################
444
return preg_replace('%&\s*\{[^}]*(\}\s*;?|$)%', '', $string);
445
} # function kses_js_entities
448
function kses_html_error($string)
449
###############################################################################
450
# This function deals with parsing errors in kses_hair(). The general plan is
451
# to remove everything to and including some whitespace, but it deals with
452
# quotes and apostrophes as well.
453
###############################################################################
455
return preg_replace('/^("[^"]*("|$)|\'[^\']*(\'|$)|\S)*\s*/', '', $string);
456
} # function kses_html_error
459
function kses_bad_protocol_once($string, $allowed_protocols)
460
###############################################################################
461
# This function searches for URL protocols at the beginning of $string, while
462
# handling whitespace and HTML entities.
463
###############################################################################
465
return preg_replace('/^((&[^;]*;|[\sA-Za-z0-9])*)'.
466
'(:|:|&#[Xx]3[Aa];)\s*/e',
467
'kses_bad_protocol_once2("\\1", $allowed_protocols)',
469
} # function kses_bad_protocol_once
472
function kses_bad_protocol_once2($string, $allowed_protocols)
473
###############################################################################
474
# This function processes URL protocols, checks to see if they're in the white-
475
# list or not, and returns different data depending on the answer.
476
###############################################################################
478
$string2 = kses_decode_entities($string);
479
$string2 = preg_replace('/\s/', '', $string2);
480
$string2 = kses_no_null($string2);
481
$string2 = strtolower($string2);
484
foreach ($allowed_protocols as $one_protocol)
485
if (strtolower($one_protocol) == $string2)
495
} # function kses_bad_protocol_once2
498
function kses_normalize_entities($string)
499
###############################################################################
500
# This function normalizes HTML entities. It will convert "AT&T" to the correct
501
# "AT&T", ":" to ":", "&#XYZZY;" to "&#XYZZY;" and so on.
502
###############################################################################
504
# Disarm all entities by converting & to &
506
$string = str_replace('&', '&', $string);
508
# Change back the allowed entities in our entity whitelist
510
$string = preg_replace('/&([A-Za-z][A-Za-z0-9]{0,19});/',
512
$string = preg_replace('/&#0*([0-9]{1,5});/e',
513
'kses_normalize_entities2("\\1")', $string);
514
$string = preg_replace('/&#([Xx])0*(([0-9A-Fa-f]{2}){1,2});/',
515
'&#\\1\\2;', $string);
518
} # function kses_normalize_entities
521
function kses_normalize_entities2($i)
522
###############################################################################
523
# This function helps kses_normalize_entities() to only accept 16 bit values
524
# and nothing more for &#number; entities.
525
###############################################################################
527
return (($i > 65535) ? "&#$i;" : "&#$i;");
528
} # function kses_normalize_entities2
531
function kses_decode_entities($string)
532
###############################################################################
533
# This function decodes numeric HTML entities (A and A). It doesn't
534
# do anything with other entities like ä, but we don't need them in the
535
# URL protocol whitelisting system anyway.
536
###############################################################################
538
$string = preg_replace('/&#([0-9]+);/e', 'chr("\\1")', $string);
539
$string = preg_replace('/&#[Xx]([0-9A-Fa-f]+);/e', 'chr(hexdec("\\1"))',
543
} # function kses_decode_entities