MDL-20636 fix most of the remaining codechecker issues in mod/quiz and lib/questionli...
[moodle.git] / lib / kses.php
blob8d87c23928c5c53d65bf7cfba61efa3b9e7499c9
1 <?php
2 /**
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 3 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!]
32 * @package moodlecore
33 * @copyright Ulf Harnhammar {@link http://sourceforge.net/projects/kses}
34 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
37 /**
38 * This function makes sure that only the allowed HTML element names, attribute
39 * names and attribute values plus only sane HTML entities will occur in
40 * $string. You have to remove any slashes from PHP's magic quotes before you
41 * call this function.
43 * @param string $string
44 * @param string $allowed_html
45 * @param array $allowed_protocols
46 * @return string
48 function kses($string, $allowed_html, $allowed_protocols =
49 array('http', 'https', 'ftp', 'news', 'nntp', 'telnet',
50 'gopher', 'mailto'))
51 ###############################################################################
52 # This function makes sure that only the allowed HTML element names, attribute
53 # names and attribute values plus only sane HTML entities will occur in
54 # $string. You have to remove any slashes from PHP's magic quotes before you
55 # call this function.
56 ###############################################################################
58 $string = kses_no_null($string);
59 $string = kses_js_entities($string);
60 $string = kses_normalize_entities($string);
61 $string = kses_hook($string);
62 $allowed_html_fixed = kses_array_lc($allowed_html);
63 return kses_split($string, $allowed_html_fixed, $allowed_protocols);
64 } # function kses
67 /**
68 * You add any kses hooks here
70 * @param string $string
71 * @return string
73 function kses_hook($string)
74 ###############################################################################
75 # You add any kses hooks here.
76 ###############################################################################
78 return $string;
79 } # function kses_hook
81 /**
82 * This function returns kses' version number.
84 * @return string
86 function kses_version()
87 ###############################################################################
88 # This function returns kses' version number.
89 ###############################################################################
91 return '0.2.2';
92 } # function kses_version
95 /**
96 * This function searches for HTML tags, no matter how malformed. It also
97 * matches stray ">" characters.
99 * @param string $string
100 * @param string $allowed_html
101 * @param array $allowed_protocols
102 * @return string
104 function kses_split($string, $allowed_html, $allowed_protocols)
105 ###############################################################################
106 # This function searches for HTML tags, no matter how malformed. It also
107 # matches stray ">" characters.
108 ###############################################################################
110 return preg_replace('%(<'. # EITHER: <
111 '[^>]*'. # things that aren't >
112 '(>|$)'. # > or end of string
113 '|>)%e', # OR: just a >
114 "kses_split2('\\1', \$allowed_html, ".
115 '$allowed_protocols)',
116 $string);
117 } # function kses_split
120 * This function does a lot of work. It rejects some very malformed things
121 * like <:::>. It returns an empty string, if the element isn't allowed (look
122 * ma, no strip_tags()!). Otherwise it splits the tag into an element and an
123 * attribute list.
125 * @param string $string
126 * @param string $allowed_html
127 * @param array $allowed_protocols
128 * @return string
130 function kses_split2($string, $allowed_html, $allowed_protocols)
131 ###############################################################################
132 # This function does a lot of work. It rejects some very malformed things
133 # like <:::>. It returns an empty string, if the element isn't allowed (look
134 # ma, no strip_tags()!). Otherwise it splits the tag into an element and an
135 # attribute list.
136 ###############################################################################
138 $string = kses_stripslashes($string);
140 if (substr($string, 0, 1) != '<')
141 return '&gt;';
142 # It matched a ">" character
144 if (!preg_match('%^<\s*(/\s*)?([a-zA-Z0-9]+)([^>]*)>?$%', $string, $matches))
145 return '';
146 # It's seriously malformed
148 $slash = trim($matches[1]);
149 $elem = $matches[2];
150 $attrlist = $matches[3];
152 if (!@isset($allowed_html[strtolower($elem)]))
153 return '';
154 # They are using a not allowed HTML element
156 if ($slash != '')
157 return "<$slash$elem>";
158 # No attributes are allowed for closing elements
160 return kses_attr("$slash$elem", $attrlist, $allowed_html,
161 $allowed_protocols);
162 } # function kses_split2
165 * This function removes all attributes, if none are allowed for this element.
166 * If some are allowed it calls kses_hair() to split them further, and then it
167 * builds up new HTML code from the data that kses_hair() returns. It also
168 * removes "<" and ">" characters, if there are any left. One more thing it
169 * does is to check if the tag has a closing XHTML slash, and if it does,
170 * it puts one in the returned code as well.
172 * @param string $element
173 * @param string $attr
174 * @param string $allowed_html
175 * @param array $allowed_protocols
176 * @return string
178 function kses_attr($element, $attr, $allowed_html, $allowed_protocols)
179 ###############################################################################
180 # This function removes all attributes, if none are allowed for this element.
181 # If some are allowed it calls kses_hair() to split them further, and then it
182 # builds up new HTML code from the data that kses_hair() returns. It also
183 # removes "<" and ">" characters, if there are any left. One more thing it
184 # does is to check if the tag has a closing XHTML slash, and if it does,
185 # it puts one in the returned code as well.
186 ###############################################################################
188 # Is there a closing XHTML slash at the end of the attributes?
190 $xhtml_slash = '';
191 if (preg_match('%\s/\s*$%', $attr))
192 $xhtml_slash = ' /';
194 # Are any attributes allowed at all for this element?
196 if (@count($allowed_html[strtolower($element)]) == 0)
197 return "<$element$xhtml_slash>";
199 # Split it
201 $attrarr = kses_hair($attr, $allowed_protocols);
203 # Go through $attrarr, and save the allowed attributes for this element
204 # in $attr2
206 $attr2 = '';
208 foreach ($attrarr as $arreach)
210 if (!@isset($allowed_html[strtolower($element)]
211 [strtolower($arreach['name'])]))
212 continue; # the attribute is not allowed
214 $current = $allowed_html[strtolower($element)]
215 [strtolower($arreach['name'])];
217 if (!is_array($current))
218 $attr2 .= ' '.$arreach['whole'];
219 # there are no checks
221 else
223 # there are some checks
224 $ok = true;
225 foreach ($current as $currkey => $currval)
226 if (!kses_check_attr_val($arreach['value'], $arreach['vless'],
227 $currkey, $currval))
228 { $ok = false; break; }
230 if ($ok)
231 $attr2 .= ' '.$arreach['whole']; # it passed them
232 } # if !is_array($current)
233 } # foreach
235 # Remove any "<" or ">" characters
237 $attr2 = preg_replace('/[<>]/', '', $attr2);
239 return "<$element$attr2$xhtml_slash>";
240 } # function kses_attr
243 * This function does a lot of work. It parses an attribute list into an array
244 * with attribute data, and tries to do the right thing even if it gets weird
245 * input. It will add quotes around attribute values that don't have any quotes
246 * or apostrophes around them, to make it easier to produce HTML code that will
247 * conform to W3C's HTML specification. It will also remove bad URL protocols
248 * from attribute values.
250 * @param string $attr
251 * @param array $allowed_protocols
252 * @return array
254 function kses_hair($attr, $allowed_protocols)
255 ###############################################################################
256 # This function does a lot of work. It parses an attribute list into an array
257 # with attribute data, and tries to do the right thing even if it gets weird
258 # input. It will add quotes around attribute values that don't have any quotes
259 # or apostrophes around them, to make it easier to produce HTML code that will
260 # conform to W3C's HTML specification. It will also remove bad URL protocols
261 # from attribute values.
262 ###############################################################################
264 $attrarr = array();
265 $mode = 0;
266 $attrname = '';
268 # Loop through the whole attribute list
270 while (strlen($attr) != 0)
272 $working = 0; # Was the last operation successful?
274 switch ($mode)
276 case 0: # attribute name, href for instance
278 if (preg_match('/^([-a-zA-Z]+)/', $attr, $match))
280 $attrname = $match[1];
281 $working = $mode = 1;
282 $attr = preg_replace('/^[-a-zA-Z]+/', '', $attr);
285 break;
287 case 1: # equals sign or valueless ("selected")
289 if (preg_match('/^\s*=\s*/', $attr)) # equals sign
291 $working = 1; $mode = 2;
292 $attr = preg_replace('/^\s*=\s*/', '', $attr);
293 break;
296 if (preg_match('/^\s+/', $attr)) # valueless
298 $working = 1; $mode = 0;
299 $attrarr[] = array
300 ('name' => $attrname,
301 'value' => '',
302 'whole' => $attrname,
303 'vless' => 'y');
304 $attr = preg_replace('/^\s+/', '', $attr);
307 break;
309 case 2: # attribute value, a URL after href= for instance
311 if (preg_match('/^"([^"]*)"(\s+|$)/', $attr, $match))
312 # "value"
314 // MDL-2684 - kses stripping CSS styles that it thinks look like protocols
315 if ($attrname == 'style') {
316 $thisval = $match[1];
317 } else {
318 $thisval = kses_bad_protocol($match[1], $allowed_protocols);
321 $attrarr[] = array
322 ('name' => $attrname,
323 'value' => $thisval,
324 'whole' => "$attrname=\"$thisval\"",
325 'vless' => 'n');
326 $working = 1; $mode = 0;
327 $attr = preg_replace('/^"[^"]*"(\s+|$)/', '', $attr);
328 break;
331 if (preg_match("/^'([^']*)'(\s+|$)/", $attr, $match))
332 # 'value'
334 $thisval = kses_bad_protocol($match[1], $allowed_protocols);
336 $attrarr[] = array
337 ('name' => $attrname,
338 'value' => $thisval,
339 'whole' => "$attrname='$thisval'",
340 'vless' => 'n');
341 $working = 1; $mode = 0;
342 $attr = preg_replace("/^'[^']*'(\s+|$)/", '', $attr);
343 break;
346 if (preg_match("%^([^\s\"']+)(\s+|$)%", $attr, $match))
347 # value
349 $thisval = kses_bad_protocol($match[1], $allowed_protocols);
351 $attrarr[] = array
352 ('name' => $attrname,
353 'value' => $thisval,
354 'whole' => "$attrname=\"$thisval\"",
355 'vless' => 'n');
356 # We add quotes to conform to W3C's HTML spec.
357 $working = 1; $mode = 0;
358 $attr = preg_replace("%^[^\s\"']+(\s+|$)%", '', $attr);
361 break;
362 } # switch
364 if ($working == 0) # not well formed, remove and try again
366 $attr = kses_html_error($attr);
367 $mode = 0;
369 } # while
371 if ($mode == 1)
372 # special case, for when the attribute list ends with a valueless
373 # attribute like "selected"
374 $attrarr[] = array
375 ('name' => $attrname,
376 'value' => '',
377 'whole' => $attrname,
378 'vless' => 'y');
380 return $attrarr;
381 } # function kses_hair
384 * This function performs different checks for attribute values. The currently
385 * implemented checks are "maxlen", "minlen", "maxval", "minval" and "valueless"
386 * with even more checks to come soon.
388 * @param string $value
389 * @param string $vless
390 * @param string $checkname
391 * @param string $checkvalue
392 * @return bool
394 function kses_check_attr_val($value, $vless, $checkname, $checkvalue)
395 ###############################################################################
396 # This function performs different checks for attribute values. The currently
397 # implemented checks are "maxlen", "minlen", "maxval", "minval" and "valueless"
398 # with even more checks to come soon.
399 ###############################################################################
401 $ok = true;
403 switch (strtolower($checkname))
405 case 'maxlen':
406 # The maxlen check makes sure that the attribute value has a length not
407 # greater than the given value. This can be used to avoid Buffer Overflows
408 # in WWW clients and various Internet servers.
410 if (strlen($value) > $checkvalue)
411 $ok = false;
412 break;
414 case 'minlen':
415 # The minlen check makes sure that the attribute value has a length not
416 # smaller than the given value.
418 if (strlen($value) < $checkvalue)
419 $ok = false;
420 break;
422 case 'maxval':
423 # The maxval check does two things: it checks that the attribute value is
424 # an integer from 0 and up, without an excessive amount of zeroes or
425 # whitespace (to avoid Buffer Overflows). It also checks that the attribute
426 # value is not greater than the given value.
427 # This check can be used to avoid Denial of Service attacks.
429 if (!preg_match('/^\s{0,6}[0-9]{1,6}\s{0,6}$/', $value))
430 $ok = false;
431 if ($value > $checkvalue)
432 $ok = false;
433 break;
435 case 'minval':
436 # The minval check checks that the attribute value is a positive integer,
437 # and that it is not smaller than the given value.
439 if (!preg_match('/^\s{0,6}[0-9]{1,6}\s{0,6}$/', $value))
440 $ok = false;
441 if ($value < $checkvalue)
442 $ok = false;
443 break;
445 case 'valueless':
446 # The valueless check checks if the attribute has a value
447 # (like <a href="blah">) or not (<option selected>). If the given value
448 # is a "y" or a "Y", the attribute must not have a value.
449 # If the given value is an "n" or an "N", the attribute must have one.
451 if (strtolower($checkvalue) != $vless)
452 $ok = false;
453 break;
454 } # switch
456 return $ok;
457 } # function kses_check_attr_val
460 * This function removes all non-allowed protocols from the beginning of
461 * $string. It ignores whitespace and the case of the letters, and it does
462 * understand HTML entities. It does its work in a while loop, so it won't be
463 * fooled by a string like "javascript:javascript:alert(57)".
465 * @param string $string
466 * @param array $$allowed_protocols
467 * @return string
469 function kses_bad_protocol($string, $allowed_protocols)
470 ###############################################################################
471 # This function removes all non-allowed protocols from the beginning of
472 # $string. It ignores whitespace and the case of the letters, and it does
473 # understand HTML entities. It does its work in a while loop, so it won't be
474 # fooled by a string like "javascript:javascript:alert(57)".
475 ###############################################################################
477 $string = kses_no_null($string);
478 $string = preg_replace('/([^\xc3-\xcf])\xad+/', '\\1', $string); # deals with Opera "feature" -- moodle utf8 fix
479 $string2 = $string.'a';
481 while ($string != $string2)
483 $string2 = $string;
484 $string = kses_bad_protocol_once($string, $allowed_protocols);
485 } # while
487 return $string;
488 } # function kses_bad_protocol
491 * This function removes any NULL characters in $string.
493 * @param string $string
494 * @return string
496 function kses_no_null($string)
497 ###############################################################################
498 # This function removes any NULL characters in $string.
499 ###############################################################################
501 $string = preg_replace('/\0+/', '', $string);
502 $string = preg_replace('/(\\\\0)+/', '', $string);
504 return $string;
505 } # function kses_no_null
509 * This function changes the character sequence \" to just "
510 * It leaves all other slashes alone. It's really weird, but the quoting from
511 * preg_replace(//e) seems to require this.
513 * @param string $string
514 * @return string
516 function kses_stripslashes($string)
517 ###############################################################################
518 # This function changes the character sequence \" to just "
519 # It leaves all other slashes alone. It's really weird, but the quoting from
520 # preg_replace(//e) seems to require this.
521 ###############################################################################
523 return preg_replace('%\\\\"%', '"', $string);
524 } # function kses_stripslashes
528 * This function goes through an array, and changes the keys to all lower case.
530 * @param array $inarray
531 * @return array
533 function kses_array_lc($inarray)
534 ###############################################################################
535 # This function goes through an array, and changes the keys to all lower case.
536 ###############################################################################
538 $outarray = array();
540 foreach ($inarray as $inkey => $inval)
542 $outkey = strtolower($inkey);
543 $outarray[$outkey] = array();
545 foreach ($inval as $inkey2 => $inval2)
547 $outkey2 = strtolower($inkey2);
548 $outarray[$outkey][$outkey2] = $inval2;
549 } # foreach $inval
550 } # foreach $inarray
552 return $outarray;
553 } # function kses_array_lc
556 * This function removes the HTML JavaScript entities found in early versions of
557 * Netscape 4.
559 * @param string $string
561 function kses_js_entities($string)
562 ###############################################################################
563 # This function removes the HTML JavaScript entities found in early versions of
564 # Netscape 4.
565 ###############################################################################
567 return preg_replace('%&\s*\{[^}]*(\}\s*;?|$)%', '', $string);
568 } # function kses_js_entities
571 * This function deals with parsing errors in kses_hair(). The general plan is
572 * to remove everything to and including some whitespace, but it deals with
573 * quotes and apostrophes as well.
575 * @param string $string
576 * @return string
578 function kses_html_error($string)
579 ###############################################################################
580 # This function deals with parsing errors in kses_hair(). The general plan is
581 # to remove everything to and including some whitespace, but it deals with
582 # quotes and apostrophes as well.
583 ###############################################################################
585 return preg_replace('/^("[^"]*("|$)|\'[^\']*(\'|$)|\S)*\s*/', '', $string);
586 } # function kses_html_error
589 * This function searches for URL protocols at the beginning of $string, while
590 * handling whitespace and HTML entities.
592 * @param string $string
593 * @param string $allowed_protocols
594 * @return string
596 function kses_bad_protocol_once($string, $allowed_protocols)
597 ###############################################################################
598 # This function searches for URL protocols at the beginning of $string, while
599 # handling whitespace and HTML entities.
600 ###############################################################################
602 $string2 = preg_split('/:|&#58;|&#x3a;/i', $string, 2);
603 if(isset($string2[1]) && !preg_match('%/\?%',$string2[0]))
605 $string = kses_bad_protocol_once2($string2[0],$allowed_protocols).trim($string2[1]);
607 return $string;
608 } # function kses_bad_protocol_once
611 * This function processes URL protocols, checks to see if they're in the white-
612 * list or not, and returns different data depending on the answer.
614 * @param string $string
615 * @param string $allowed_protocols
616 * @return string
618 function kses_bad_protocol_once2($string, $allowed_protocols)
619 ###############################################################################
620 # This function processes URL protocols, checks to see if they're in the white-
621 # list or not, and returns different data depending on the answer.
622 ###############################################################################
624 $string2 = kses_decode_entities($string);
625 $string2 = preg_replace('/\s/', '', $string2);
626 $string2 = kses_no_null($string2);
627 $string2 = preg_replace('/\xad+/', '', $string2);
628 # deals with Opera "feature"
629 $string2 = strtolower($string2);
631 $allowed = false;
632 foreach ($allowed_protocols as $one_protocol)
633 if (strtolower($one_protocol) == $string2)
635 $allowed = true;
636 break;
639 if ($allowed)
640 return "$string2:";
641 else
642 return '';
643 } # function kses_bad_protocol_once2
646 * This function normalizes HTML entities. It will convert "AT&T" to the correct
647 * "AT&amp;T", "&#00058;" to "&#58;", "&#XYZZY;" to "&amp;#XYZZY;" and so on.
649 * @param string $string
650 * @return string
652 function kses_normalize_entities($string)
653 ###############################################################################
654 # This function normalizes HTML entities. It will convert "AT&T" to the correct
655 # "AT&amp;T", "&#00058;" to "&#58;", "&#XYZZY;" to "&amp;#XYZZY;" and so on.
656 ###############################################################################
658 # Disarm all entities by converting & to &amp;
660 $string = str_replace('&', '&amp;', $string);
662 # Change back the allowed entities in our entity whitelist
664 $string = preg_replace('/&amp;([A-Za-z][A-Za-z0-9]{0,19});/',
665 '&\\1;', $string);
666 $string = preg_replace('/&amp;#0*([0-9]{1,5});/e',
667 'kses_normalize_entities2("\\1")', $string);
668 $string = preg_replace('/&amp;#([Xx])0*(([0-9A-Fa-f]{2}){1,2});/',
669 '&#\\1\\2;', $string);
671 return $string;
672 } # function kses_normalize_entities
675 * This function helps kses_normalize_entities() to only accept 16 bit values
676 * and nothing more for &#number; entities.
678 * @param int $i
679 * @return string
681 function kses_normalize_entities2($i)
682 ###############################################################################
683 # This function helps kses_normalize_entities() to only accept 16 bit values
684 # and nothing more for &#number; entities.
685 ###############################################################################
687 return (($i > 65535) ? "&amp;#$i;" : "&#$i;");
688 } # function kses_normalize_entities2
691 * This function decodes numeric HTML entities (&#65; and &#x41;). It doesn't
692 * do anything with other entities like &auml;, but we don't need them in the
693 * URL protocol whitelisting system anyway.
695 * @param string $string
696 * @return string
698 function kses_decode_entities($string)
699 ###############################################################################
700 # This function decodes numeric HTML entities (&#65; and &#x41;). It doesn't
701 # do anything with other entities like &auml;, but we don't need them in the
702 # URL protocol whitelisting system anyway.
703 ###############################################################################
705 $string = preg_replace('/&#([0-9]+);/e', 'chr("\\1")', $string);
706 $string = preg_replace('/&#[Xx]([0-9A-Fa-f]+);/e', 'chr(hexdec("\\1"))',
707 $string);
709 return $string;
710 } # function kses_decode_entities