MDL-23726 fixed phpdocs - credit goes to Henning Bostelmann
[moodle.git] / lib / kses.php
blobf07c069ddb369be918940766f50803367e1af110
1 <?php
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
14 # more details.
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: Ulf Harnhammar
26 # Ymergatan 17 C
27 # 753 25 Uppsala
28 # SWEDEN
30 # [kses strips evil scripts!]
33 function kses($string, $allowed_html, $allowed_protocols =
34 array('http', 'https', 'ftp', 'news', 'nntp', 'telnet',
35 'gopher', 'mailto'))
36 ###############################################################################
37 # This function makes sure that only the allowed HTML element names, attribute
38 # names and attribute values plus only sane HTML entities will occur in
39 # $string. You have to remove any slashes from PHP's magic quotes before you
40 # call this function.
41 ###############################################################################
43 $string = kses_no_null($string);
44 $string = kses_js_entities($string);
45 $string = kses_normalize_entities($string);
46 $string = kses_hook($string);
47 $allowed_html_fixed = kses_array_lc($allowed_html);
48 return kses_split($string, $allowed_html_fixed, $allowed_protocols);
49 } # function kses
52 function kses_hook($string)
53 ###############################################################################
54 # You add any kses hooks here.
55 ###############################################################################
57 return $string;
58 } # function kses_hook
61 function kses_version()
62 ###############################################################################
63 # This function returns kses' version number.
64 ###############################################################################
66 return '0.2.2';
67 } # function kses_version
70 function kses_split($string, $allowed_html, $allowed_protocols)
71 ###############################################################################
72 # This function searches for HTML tags, no matter how malformed. It also
73 # matches stray ">" characters.
74 ###############################################################################
76 return preg_replace('%(<'. # EITHER: <
77 '[^>]*'. # things that aren't >
78 '(>|$)'. # > or end of string
79 '|>)%e', # OR: just a >
80 "kses_split2('\\1', \$allowed_html, ".
81 '$allowed_protocols)',
82 $string);
83 } # function kses_split
86 function kses_split2($string, $allowed_html, $allowed_protocols)
87 ###############################################################################
88 # This function does a lot of work. It rejects some very malformed things
89 # like <:::>. It returns an empty string, if the element isn't allowed (look
90 # ma, no strip_tags()!). Otherwise it splits the tag into an element and an
91 # attribute list.
92 ###############################################################################
94 $string = kses_stripslashes($string);
96 if (substr($string, 0, 1) != '<')
97 return '&gt;';
98 # It matched a ">" character
100 if (!preg_match('%^<\s*(/\s*)?([a-zA-Z0-9]+)([^>]*)>?$%', $string, $matches))
101 return '';
102 # It's seriously malformed
104 $slash = trim($matches[1]);
105 $elem = $matches[2];
106 $attrlist = $matches[3];
108 if (!@isset($allowed_html[strtolower($elem)]))
109 return '';
110 # They are using a not allowed HTML element
112 if ($slash != '')
113 return "<$slash$elem>";
114 # No attributes are allowed for closing elements
116 return kses_attr("$slash$elem", $attrlist, $allowed_html,
117 $allowed_protocols);
118 } # function kses_split2
121 function kses_attr($element, $attr, $allowed_html, $allowed_protocols)
122 ###############################################################################
123 # This function removes all attributes, if none are allowed for this element.
124 # If some are allowed it calls kses_hair() to split them further, and then it
125 # builds up new HTML code from the data that kses_hair() returns. It also
126 # removes "<" and ">" characters, if there are any left. One more thing it
127 # does is to check if the tag has a closing XHTML slash, and if it does,
128 # it puts one in the returned code as well.
129 ###############################################################################
131 # Is there a closing XHTML slash at the end of the attributes?
133 $xhtml_slash = '';
134 if (preg_match('%\s/\s*$%', $attr))
135 $xhtml_slash = ' /';
137 # Are any attributes allowed at all for this element?
139 if (@count($allowed_html[strtolower($element)]) == 0)
140 return "<$element$xhtml_slash>";
142 # Split it
144 $attrarr = kses_hair($attr, $allowed_protocols);
146 # Go through $attrarr, and save the allowed attributes for this element
147 # in $attr2
149 $attr2 = '';
151 foreach ($attrarr as $arreach)
153 if (!@isset($allowed_html[strtolower($element)]
154 [strtolower($arreach['name'])]))
155 continue; # the attribute is not allowed
157 $current = $allowed_html[strtolower($element)]
158 [strtolower($arreach['name'])];
160 if (!is_array($current))
161 $attr2 .= ' '.$arreach['whole'];
162 # there are no checks
164 else
166 # there are some checks
167 $ok = true;
168 foreach ($current as $currkey => $currval)
169 if (!kses_check_attr_val($arreach['value'], $arreach['vless'],
170 $currkey, $currval))
171 { $ok = false; break; }
173 if ($ok)
174 $attr2 .= ' '.$arreach['whole']; # it passed them
175 } # if !is_array($current)
176 } # foreach
178 # Remove any "<" or ">" characters
180 $attr2 = preg_replace('/[<>]/', '', $attr2);
182 return "<$element$attr2$xhtml_slash>";
183 } # function kses_attr
186 function kses_hair($attr, $allowed_protocols)
187 ###############################################################################
188 # This function does a lot of work. It parses an attribute list into an array
189 # with attribute data, and tries to do the right thing even if it gets weird
190 # input. It will add quotes around attribute values that don't have any quotes
191 # or apostrophes around them, to make it easier to produce HTML code that will
192 # conform to W3C's HTML specification. It will also remove bad URL protocols
193 # from attribute values.
194 ###############################################################################
196 $attrarr = array();
197 $mode = 0;
198 $attrname = '';
200 # Loop through the whole attribute list
202 while (strlen($attr) != 0)
204 $working = 0; # Was the last operation successful?
206 switch ($mode)
208 case 0: # attribute name, href for instance
210 if (preg_match('/^([-a-zA-Z]+)/', $attr, $match))
212 $attrname = $match[1];
213 $working = $mode = 1;
214 $attr = preg_replace('/^[-a-zA-Z]+/', '', $attr);
217 break;
219 case 1: # equals sign or valueless ("selected")
221 if (preg_match('/^\s*=\s*/', $attr)) # equals sign
223 $working = 1; $mode = 2;
224 $attr = preg_replace('/^\s*=\s*/', '', $attr);
225 break;
228 if (preg_match('/^\s+/', $attr)) # valueless
230 $working = 1; $mode = 0;
231 $attrarr[] = array
232 ('name' => $attrname,
233 'value' => '',
234 'whole' => $attrname,
235 'vless' => 'y');
236 $attr = preg_replace('/^\s+/', '', $attr);
239 break;
241 case 2: # attribute value, a URL after href= for instance
243 if (preg_match('/^"([^"]*)"(\s+|$)/', $attr, $match))
244 # "value"
246 // MDL-2684 - kses stripping CSS styles that it thinks look like protocols
247 if ($attrname == 'style') {
248 $thisval = $match[1];
249 } else {
250 $thisval = kses_bad_protocol($match[1], $allowed_protocols);
253 $attrarr[] = array
254 ('name' => $attrname,
255 'value' => $thisval,
256 'whole' => "$attrname=\"$thisval\"",
257 'vless' => 'n');
258 $working = 1; $mode = 0;
259 $attr = preg_replace('/^"[^"]*"(\s+|$)/', '', $attr);
260 break;
263 if (preg_match("/^'([^']*)'(\s+|$)/", $attr, $match))
264 # 'value'
266 $thisval = kses_bad_protocol($match[1], $allowed_protocols);
268 $attrarr[] = array
269 ('name' => $attrname,
270 'value' => $thisval,
271 'whole' => "$attrname='$thisval'",
272 'vless' => 'n');
273 $working = 1; $mode = 0;
274 $attr = preg_replace("/^'[^']*'(\s+|$)/", '', $attr);
275 break;
278 if (preg_match("%^([^\s\"']+)(\s+|$)%", $attr, $match))
279 # value
281 $thisval = kses_bad_protocol($match[1], $allowed_protocols);
283 $attrarr[] = array
284 ('name' => $attrname,
285 'value' => $thisval,
286 'whole' => "$attrname=\"$thisval\"",
287 'vless' => 'n');
288 # We add quotes to conform to W3C's HTML spec.
289 $working = 1; $mode = 0;
290 $attr = preg_replace("%^[^\s\"']+(\s+|$)%", '', $attr);
293 break;
294 } # switch
296 if ($working == 0) # not well formed, remove and try again
298 $attr = kses_html_error($attr);
299 $mode = 0;
301 } # while
303 if ($mode == 1)
304 # special case, for when the attribute list ends with a valueless
305 # attribute like "selected"
306 $attrarr[] = array
307 ('name' => $attrname,
308 'value' => '',
309 'whole' => $attrname,
310 'vless' => 'y');
312 return $attrarr;
313 } # function kses_hair
316 function kses_check_attr_val($value, $vless, $checkname, $checkvalue)
317 ###############################################################################
318 # This function performs different checks for attribute values. The currently
319 # implemented checks are "maxlen", "minlen", "maxval", "minval" and "valueless"
320 # with even more checks to come soon.
321 ###############################################################################
323 $ok = true;
325 switch (strtolower($checkname))
327 case 'maxlen':
328 # The maxlen check makes sure that the attribute value has a length not
329 # greater than the given value. This can be used to avoid Buffer Overflows
330 # in WWW clients and various Internet servers.
332 if (strlen($value) > $checkvalue)
333 $ok = false;
334 break;
336 case 'minlen':
337 # The minlen check makes sure that the attribute value has a length not
338 # smaller than the given value.
340 if (strlen($value) < $checkvalue)
341 $ok = false;
342 break;
344 case 'maxval':
345 # The maxval check does two things: it checks that the attribute value is
346 # an integer from 0 and up, without an excessive amount of zeroes or
347 # whitespace (to avoid Buffer Overflows). It also checks that the attribute
348 # value is not greater than the given value.
349 # This check can be used to avoid Denial of Service attacks.
351 if (!preg_match('/^\s{0,6}[0-9]{1,6}\s{0,6}$/', $value))
352 $ok = false;
353 if ($value > $checkvalue)
354 $ok = false;
355 break;
357 case 'minval':
358 # The minval check checks that the attribute value is a positive integer,
359 # and that it is not smaller than the given value.
361 if (!preg_match('/^\s{0,6}[0-9]{1,6}\s{0,6}$/', $value))
362 $ok = false;
363 if ($value < $checkvalue)
364 $ok = false;
365 break;
367 case 'valueless':
368 # The valueless check checks if the attribute has a value
369 # (like <a href="blah">) or not (<option selected>). If the given value
370 # is a "y" or a "Y", the attribute must not have a value.
371 # If the given value is an "n" or an "N", the attribute must have one.
373 if (strtolower($checkvalue) != $vless)
374 $ok = false;
375 break;
376 } # switch
378 return $ok;
379 } # function kses_check_attr_val
382 function kses_bad_protocol($string, $allowed_protocols)
383 ###############################################################################
384 # This function removes all non-allowed protocols from the beginning of
385 # $string. It ignores whitespace and the case of the letters, and it does
386 # understand HTML entities. It does its work in a while loop, so it won't be
387 # fooled by a string like "javascript:javascript:alert(57)".
388 ###############################################################################
390 $string = kses_no_null($string);
391 $string = preg_replace('/([^\xc3-\xcf])\xad+/', '\\1', $string); # deals with Opera "feature" -- moodle utf8 fix
392 $string2 = $string.'a';
394 while ($string != $string2)
396 $string2 = $string;
397 $string = kses_bad_protocol_once($string, $allowed_protocols);
398 } # while
400 return $string;
401 } # function kses_bad_protocol
404 function kses_no_null($string)
405 ###############################################################################
406 # This function removes any NULL characters in $string.
407 ###############################################################################
409 $string = preg_replace('/\0+/', '', $string);
410 $string = preg_replace('/(\\\\0)+/', '', $string);
412 return $string;
413 } # function kses_no_null
416 function kses_stripslashes($string)
417 ###############################################################################
418 # This function changes the character sequence \" to just "
419 # It leaves all other slashes alone. It's really weird, but the quoting from
420 # preg_replace(//e) seems to require this.
421 ###############################################################################
423 return preg_replace('%\\\\"%', '"', $string);
424 } # function kses_stripslashes
427 function kses_array_lc($inarray)
428 ###############################################################################
429 # This function goes through an array, and changes the keys to all lower case.
430 ###############################################################################
432 $outarray = array();
434 foreach ($inarray as $inkey => $inval)
436 $outkey = strtolower($inkey);
437 $outarray[$outkey] = array();
439 foreach ($inval as $inkey2 => $inval2)
441 $outkey2 = strtolower($inkey2);
442 $outarray[$outkey][$outkey2] = $inval2;
443 } # foreach $inval
444 } # foreach $inarray
446 return $outarray;
447 } # function kses_array_lc
450 function kses_js_entities($string)
451 ###############################################################################
452 # This function removes the HTML JavaScript entities found in early versions of
453 # Netscape 4.
454 ###############################################################################
456 return preg_replace('%&\s*\{[^}]*(\}\s*;?|$)%', '', $string);
457 } # function kses_js_entities
460 function kses_html_error($string)
461 ###############################################################################
462 # This function deals with parsing errors in kses_hair(). The general plan is
463 # to remove everything to and including some whitespace, but it deals with
464 # quotes and apostrophes as well.
465 ###############################################################################
467 return preg_replace('/^("[^"]*("|$)|\'[^\']*(\'|$)|\S)*\s*/', '', $string);
468 } # function kses_html_error
471 function kses_bad_protocol_once($string, $allowed_protocols)
472 ###############################################################################
473 # This function searches for URL protocols at the beginning of $string, while
474 # handling whitespace and HTML entities.
475 ###############################################################################
477 $string2 = preg_split('/:|&#58;|&#x3a;/i', $string, 2);
478 if(isset($string2[1]) && !preg_match('%/\?%',$string2[0]))
480 $string = kses_bad_protocol_once2($string2[0],$allowed_protocols).trim($string2[1]);
482 return $string;
483 } # function kses_bad_protocol_once
486 function kses_bad_protocol_once2($string, $allowed_protocols)
487 ###############################################################################
488 # This function processes URL protocols, checks to see if they're in the white-
489 # list or not, and returns different data depending on the answer.
490 ###############################################################################
492 $string2 = kses_decode_entities($string);
493 $string2 = preg_replace('/\s/', '', $string2);
494 $string2 = kses_no_null($string2);
495 $string2 = preg_replace('/\xad+/', '', $string2);
496 # deals with Opera "feature"
497 $string2 = strtolower($string2);
499 $allowed = false;
500 foreach ($allowed_protocols as $one_protocol)
501 if (strtolower($one_protocol) == $string2)
503 $allowed = true;
504 break;
507 if ($allowed)
508 return "$string2:";
509 else
510 return '';
511 } # function kses_bad_protocol_once2
514 function kses_normalize_entities($string)
515 ###############################################################################
516 # This function normalizes HTML entities. It will convert "AT&T" to the correct
517 # "AT&amp;T", "&#00058;" to "&#58;", "&#XYZZY;" to "&amp;#XYZZY;" and so on.
518 ###############################################################################
520 # Disarm all entities by converting & to &amp;
522 $string = str_replace('&', '&amp;', $string);
524 # Change back the allowed entities in our entity whitelist
526 $string = preg_replace('/&amp;([A-Za-z][A-Za-z0-9]{0,19});/',
527 '&\\1;', $string);
528 $string = preg_replace('/&amp;#0*([0-9]{1,5});/e',
529 'kses_normalize_entities2("\\1")', $string);
530 $string = preg_replace('/&amp;#([Xx])0*(([0-9A-Fa-f]{2}){1,2});/',
531 '&#\\1\\2;', $string);
533 return $string;
534 } # function kses_normalize_entities
537 function kses_normalize_entities2($i)
538 ###############################################################################
539 # This function helps kses_normalize_entities() to only accept 16 bit values
540 # and nothing more for &#number; entities.
541 ###############################################################################
543 return (($i > 65535) ? "&amp;#$i;" : "&#$i;");
544 } # function kses_normalize_entities2
547 function kses_decode_entities($string)
548 ###############################################################################
549 # This function decodes numeric HTML entities (&#65; and &#x41;). It doesn't
550 # do anything with other entities like &auml;, but we don't need them in the
551 # URL protocol whitelisting system anyway.
552 ###############################################################################
554 $string = preg_replace('/&#([0-9]+);/e', 'chr("\\1")', $string);
555 $string = preg_replace('/&#[Xx]([0-9A-Fa-f]+);/e', 'chr(hexdec("\\1"))',
556 $string);
558 return $string;
559 } # function kses_decode_entities