OSDN Git Service

Import current code.
[osdn-codes/wiki-parser.git] / test / lib / kses.php
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
5 #
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.
10 #
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.
15 #
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
20 #
21 # *** CONTACT INFORMATION ***
22 #
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
29 #
30 # [kses strips evil scripts!]
31 #
32
33 #
34 # Changes:
35 #  * 2008-01-18 Tatsuki Sugiura <sugi@osdn.jp>
36 #    * add callback attribute filter
37 #
38
39
40 function kses($string, $allowed_html, $allowed_protocols =
41                array('http', 'https', 'ftp', 'news', 'nntp', 'telnet',
42                      'gopher', 'mailto'))
43 ###############################################################################
44 # This function makes sure that only the allowed HTML element names, attribute
45 # names and attribute values plus only sane HTML entities will occur in
46 # $string. You have to remove any slashes from PHP's magic quotes before you
47 # call this function.
48 ###############################################################################
49 {
50   $string = kses_no_null($string);
51   $string = kses_js_entities($string);
52   $string = kses_normalize_entities($string);
53   $string = kses_hook($string);
54   $allowed_html_fixed = kses_array_lc($allowed_html);
55   return kses_split($string, $allowed_html_fixed, $allowed_protocols);
56 } # function kses
57
58
59 function kses_hook($string)
60 ###############################################################################
61 # You add any kses hooks here.
62 ###############################################################################
63 {
64   return $string;
65 } # function kses_hook
66
67
68 function kses_version()
69 ###############################################################################
70 # This function returns kses' version number.
71 ###############################################################################
72 {
73   return '0.2.2';
74 } # function kses_version
75
76
77 function kses_split($string, $allowed_html, $allowed_protocols)
78 ###############################################################################
79 # This function searches for HTML tags, no matter how malformed. It also
80 # matches stray ">" characters.
81 ###############################################################################
82 {
83   return preg_replace_callback('%(<'.   # EITHER: <
84                       '[^>]*'. # things that aren't >
85                       '(>|$)'. # > or end of string
86                       '|>)%', # OR: just a >
87                       function ($m) use ($allowed_html, $allowed_protocols) { return kses_split2($m[1], $allowed_html, $allowed_protocols); },
88                       $string);
89 } # function kses_split
90
91
92 function kses_split2($string, $allowed_html, $allowed_protocols)
93 ###############################################################################
94 # This function does a lot of work. It rejects some very malformed things
95 # like <:::>. It returns an empty string, if the element isn't allowed (look
96 # ma, no strip_tags()!). Otherwise it splits the tag into an element and an
97 # attribute list.
98 ###############################################################################
99 {
100   $string = kses_stripslashes($string);
101
102   if (substr($string, 0, 1) != '<')
103     return '&gt;';
104     # It matched a ">" character
105
106   if (!preg_match('%^<\s*(/\s*)?([a-zA-Z0-9]+)([^>]*)>?$%', $string, $matches))
107     return '';
108     # It's seriously malformed
109
110   $slash = trim($matches[1]);
111   $elem = $matches[2];
112   $attrlist = $matches[3];
113
114   if (!@isset($allowed_html[strtolower($elem)]))
115     return '';
116     # They are using a not allowed HTML element
117
118   if ($slash != '')
119     return "<$slash$elem>";
120   # No attributes are allowed for closing elements
121
122   return kses_attr("$slash$elem", $attrlist, $allowed_html,
123                    $allowed_protocols);
124 } # function kses_split2
125
126
127 function kses_attr($element, $attr, $allowed_html, $allowed_protocols)
128 ###############################################################################
129 # This function removes all attributes, if none are allowed for this element.
130 # If some are allowed it calls kses_hair() to split them further, and then it
131 # builds up new HTML code from the data that kses_hair() returns. It also
132 # removes "<" and ">" characters, if there are any left. One more thing it
133 # does is to check if the tag has a closing XHTML slash, and if it does,
134 # it puts one in the returned code as well.
135 ###############################################################################
136 {
137 # Is there a closing XHTML slash at the end of the attributes?
138
139   $xhtml_slash = '';
140   if (preg_match('%\s/\s*$%', $attr))
141     $xhtml_slash = ' /';
142
143 # Are any attributes allowed at all for this element?
144
145   if (@count($allowed_html[strtolower($element)]) == 0)
146     return "<$element$xhtml_slash>";
147
148 # Split it
149
150   $attrarr = kses_hair($attr, $allowed_protocols);
151
152 # Go through $attrarr, and save the allowed attributes for this element
153 # in $attr2
154
155   $attr2 = '';
156
157   foreach ($attrarr as $arreach)
158   {
159     if (!@isset($allowed_html[strtolower($element)]
160                             [strtolower($arreach['name'])]))
161       continue; # the attribute is not allowed
162
163     $current = $allowed_html[strtolower($element)]
164                             [strtolower($arreach['name'])];
165
166     if (!is_array($current))
167       $attr2 .= ' '.$arreach['whole'];
168     # there are no checks
169
170     else
171     {
172     # there are some checks
173       $ok = true;
174       foreach ($current as $currkey => $currval)
175         if (!kses_check_attr_val($arreach['value'], $arreach['vless'],
176                                  $currkey, $currval))
177         { $ok = false; break; }
178
179       if ($ok)
180         $attr2 .= ' '.$arreach['whole']; # it passed them
181     } # if !is_array($current)
182   } # foreach
183
184 # Remove any "<" or ">" characters
185
186   $attr2 = preg_replace('/[<>]/', '', $attr2);
187
188   return "<$element$attr2$xhtml_slash>";
189 } # function kses_attr
190
191
192 function kses_hair($attr, $allowed_protocols)
193 ###############################################################################
194 # This function does a lot of work. It parses an attribute list into an array
195 # with attribute data, and tries to do the right thing even if it gets weird
196 # input. It will add quotes around attribute values that don't have any quotes
197 # or apostrophes around them, to make it easier to produce HTML code that will
198 # conform to W3C's HTML specification. It will also remove bad URL protocols
199 # from attribute values.
200 ###############################################################################
201 {
202   $attrarr = array();
203   $mode = 0;
204   $attrname = '';
205
206 # Loop through the whole attribute list
207
208   while (strlen($attr) != 0)
209   {
210     $working = 0; # Was the last operation successful?
211
212     switch ($mode)
213     {
214       case 0: # attribute name, href for instance
215
216         if (preg_match('/^([-a-zA-Z]+)/', $attr, $match))
217         {
218           $attrname = $match[1];
219           $working = $mode = 1;
220           $attr = preg_replace('/^[-a-zA-Z]+/', '', $attr);
221         }
222
223         break;
224
225       case 1: # equals sign or valueless ("selected")
226
227         if (preg_match('/^\s*=\s*/', $attr)) # equals sign
228         {
229           $working = 1; $mode = 2;
230           $attr = preg_replace('/^\s*=\s*/', '', $attr);
231           break;
232         }
233
234         if (preg_match('/^\s+/', $attr)) # valueless
235         {
236           $working = 1; $mode = 0;
237           $attrarr[] = array
238                         ('name'  => $attrname,
239                          'value' => '',
240                          'whole' => $attrname,
241                          'vless' => 'y');
242           $attr = preg_replace('/^\s+/', '', $attr);
243         }
244
245         break;
246
247       case 2: # attribute value, a URL after href= for instance
248
249         if (preg_match('/^"([^"]*)"(\s+|$)/', $attr, $match))
250          # "value"
251         {
252           if (strtolower($attrname) !== "style") {
253             $thisval = kses_bad_protocol($match[1], $allowed_protocols);
254           } else {
255             $thisval = $match[1];
256           }
257
258           $attrarr[] = array
259                         ('name'  => $attrname,
260                          'value' => $thisval,
261                          'whole' => "$attrname=\"$thisval\"",
262                          'vless' => 'n');
263           $working = 1; $mode = 0;
264           $attr = preg_replace('/^"[^"]*"(\s+|$)/', '', $attr);
265           break;
266         }
267
268         if (preg_match("/^'([^']*)'(\s+|$)/", $attr, $match))
269          # 'value'
270         {
271           if (strtolower($attrname) !== "style") {
272             $thisval = kses_bad_protocol($match[1], $allowed_protocols);
273           } else {
274             $thisval = $match[1];
275           }
276
277           $attrarr[] = array
278                         ('name'  => $attrname,
279                          'value' => $thisval,
280                          'whole' => "$attrname='$thisval'",
281                          'vless' => 'n');
282           $working = 1; $mode = 0;
283           $attr = preg_replace("/^'[^']*'(\s+|$)/", '', $attr);
284           break;
285         }
286
287         if (preg_match("%^([^\s\"']+)(\s+|$)%", $attr, $match))
288          # value
289         {
290           if (strtolower($attrname) !== "style") {
291             $thisval = kses_bad_protocol($match[1], $allowed_protocols);
292           } else {
293             $thisval = $match[1];
294           }
295
296           $attrarr[] = array
297                         ('name'  => $attrname,
298                          'value' => $thisval,
299                          'whole' => "$attrname=\"$thisval\"",
300                          'vless' => 'n');
301                          # We add quotes to conform to W3C's HTML spec.
302           $working = 1; $mode = 0;
303           $attr = preg_replace("%^[^\s\"']+(\s+|$)%", '', $attr);
304         }
305
306         break;
307     } # switch
308
309     if ($working == 0) # not well formed, remove and try again
310     {
311       $attr = kses_html_error($attr);
312       $mode = 0;
313     }
314   } # while
315
316   if ($mode == 1)
317   # special case, for when the attribute list ends with a valueless
318   # attribute like "selected"
319     $attrarr[] = array
320                   ('name'  => $attrname,
321                    'value' => '',
322                    'whole' => $attrname,
323                    'vless' => 'y');
324
325   return $attrarr;
326 } # function kses_hair
327
328
329 function kses_check_attr_val($value, $vless, $checkname, $checkvalue)
330 ###############################################################################
331 # This function performs different checks for attribute values. The currently
332 # implemented checks are "maxlen", "minlen", "maxval", "minval" and "valueless"
333 # with even more checks to come soon.
334 ###############################################################################
335 {
336   $ok = true;
337
338   switch (strtolower($checkname))
339   {
340     case 'maxlen':
341     # The maxlen check makes sure that the attribute value has a length not
342     # greater than the given value. This can be used to avoid Buffer Overflows
343     # in WWW clients and various Internet servers.
344
345       if (strlen($value) > $checkvalue)
346         $ok = false;
347       break;
348
349     case 'minlen':
350     # The minlen check makes sure that the attribute value has a length not
351     # smaller than the given value.
352
353       if (strlen($value) < $checkvalue)
354         $ok = false;
355       break;
356
357     case 'maxval':
358     # The maxval check does two things: it checks that the attribute value is
359     # an integer from 0 and up, without an excessive amount of zeroes or
360     # whitespace (to avoid Buffer Overflows). It also checks that the attribute
361     # value is not greater than the given value.
362     # This check can be used to avoid Denial of Service attacks.
363
364       if (!preg_match('/^\s{0,6}[0-9]{1,6}\s{0,6}$/', $value))
365         $ok = false;
366       if ($value > $checkvalue)
367         $ok = false;
368       break;
369
370     case 'minval':
371     # The minval check checks that the attribute value is a positive integer,
372     # and that it is not smaller than the given value.
373
374       if (!preg_match('/^\s{0,6}[0-9]{1,6}\s{0,6}$/', $value))
375         $ok = false;
376       if ($value < $checkvalue)
377         $ok = false;
378       break;
379
380     case 'valueless':
381     # The valueless check checks if the attribute has a value
382     # (like <a href="blah">) or not (<option selected>). If the given value
383     # is a "y" or a "Y", the attribute must not have a value.
384     # If the given value is an "n" or an "N", the attribute must have one.
385
386       if (strtolower($checkvalue) != $vless)
387         $ok = false;
388       break;
389
390     case 'cssfilter':
391     # The value is checked CSS expression
392       $ok = $checkvalue ? kses_verify_css($value) : true;
393       break;
394
395     case 'callback':
396     # The value is checked specified function
397       if (is_callable($checkvalue))
398       {
399         $ok = call_user_func($checkvalue, $value);
400       }
401       else
402       {
403         $ok = false;
404         trigger_error("can't call callback function '$checkvalue'");
405       }
406       break;
407   } # switch
408
409   return $ok;
410 } # function kses_check_attr_val
411
412
413 function kses_bad_protocol($string, $allowed_protocols)
414 ###############################################################################
415 # This function removes all non-allowed protocols from the beginning of
416 # $string. It ignores whitespace and the case of the letters, and it does
417 # understand HTML entities. It does its work in a while loop, so it won't be
418 # fooled by a string like "javascript:javascript:alert(57)".
419 ###############################################################################
420 {
421   $string = kses_no_null($string);
422   # commented out to stop breaking multibyte chars
423   # see http://groups.google.com/group/wp-ja-pkg/browse_thread/thread/36c994dbd9276754/c3c0adb86a8b725d for details.
424   # - sugi 2008-06-12
425
426   #$string = preg_replace('/\xad+/', '', $string); # deals with Opera "feature"
427   $string2 = $string.'a';
428
429   while ($string != $string2)
430   {
431     $string2 = $string;
432     $string = kses_bad_protocol_once($string, $allowed_protocols);
433   } # while
434
435   return $string;
436 } # function kses_bad_protocol
437
438
439 function kses_no_null($string)
440 ###############################################################################
441 # This function removes any NULL characters in $string.
442 ###############################################################################
443 {
444   $string = preg_replace('/\0+/', '', $string);
445   $string = preg_replace('/(\\\\0)+/', '', $string);
446
447   return $string;
448 } # function kses_no_null
449
450
451 function kses_stripslashes($string)
452 ###############################################################################
453 # This function changes the character sequence  \"  to just  "
454 # It leaves all other slashes alone. It's really weird, but the quoting from
455 # preg_replace(//e) seems to require this.
456 ###############################################################################
457 {
458   return preg_replace('%\\\\"%', '"', $string);
459 } # function kses_stripslashes
460
461
462 function kses_array_lc($inarray)
463 ###############################################################################
464 # This function goes through an array, and changes the keys to all lower case.
465 ###############################################################################
466 {
467   $outarray = array();
468
469   foreach ($inarray as $inkey => $inval)
470   {
471     $outkey = strtolower($inkey);
472     $outarray[$outkey] = array();
473
474     foreach ($inval as $inkey2 => $inval2)
475     {
476       $outkey2 = strtolower($inkey2);
477       $outarray[$outkey][$outkey2] = $inval2;
478     } # foreach $inval
479   } # foreach $inarray
480
481   return $outarray;
482 } # function kses_array_lc
483
484
485 function kses_js_entities($string)
486 ###############################################################################
487 # This function removes the HTML JavaScript entities found in early versions of
488 # Netscape 4.
489 ###############################################################################
490 {
491   return preg_replace('%&\s*\{[^}]*(\}\s*;?|$)%', '', $string);
492 } # function kses_js_entities
493
494
495 function kses_html_error($string)
496 ###############################################################################
497 # This function deals with parsing errors in kses_hair(). The general plan is
498 # to remove everything to and including some whitespace, but it deals with
499 # quotes and apostrophes as well.
500 ###############################################################################
501 {
502   return preg_replace('/^("[^"]*("|$)|\'[^\']*(\'|$)|\S)*\s*/', '', $string);
503 } # function kses_html_error
504
505
506 function kses_bad_protocol_once($string, $allowed_protocols)
507 ###############################################################################
508 # This function searches for URL protocols at the beginning of $string, while
509 # handling whitespace and HTML entities.
510 ###############################################################################
511 {
512   return preg_replace_callback('/^((&[^;]*;|[\sA-Za-z0-9])*)'.
513                       '(:|&#58;|&#[Xx]3[Aa];)\s*/',
514                       function ($m) { return kses_bad_protocol_once2($m[1], $allowed_protocols); },
515                       $string);
516 } # function kses_bad_protocol_once
517
518
519 function kses_bad_protocol_once2($string, $allowed_protocols)
520 ###############################################################################
521 # This function processes URL protocols, checks to see if they're in the white-
522 # list or not, and returns different data depending on the answer.
523 ###############################################################################
524 {
525   $string2 = kses_decode_entities($string);
526   $string2 = preg_replace('/\s/', '', $string2);
527   $string2 = kses_no_null($string2);
528   $string2 = preg_replace('/\xad+/', '', $string2);
529    # deals with Opera "feature"
530   $string2 = strtolower($string2);
531
532   $allowed = false;
533   foreach ($allowed_protocols as $one_protocol)
534     if (strtolower($one_protocol) == $string2)
535     {
536       $allowed = true;
537       break;
538     }
539
540   if ($allowed)
541     return "$string2:";
542   else
543     return '';
544 } # function kses_bad_protocol_once2
545
546
547 function kses_normalize_entities($string)
548 ###############################################################################
549 # This function normalizes HTML entities. It will convert "AT&T" to the correct
550 # "AT&amp;T", "&#00058;" to "&#58;", "&#XYZZY;" to "&amp;#XYZZY;" and so on.
551 ###############################################################################
552 {
553 # Disarm all entities by converting & to &amp;
554
555   $string = str_replace('&', '&amp;', $string);
556
557 # Change back the allowed entities in our entity whitelist
558
559   $string = preg_replace('/&amp;([A-Za-z][A-Za-z0-9]{0,19});/',
560                          '&\\1;', $string);
561   $string = preg_replace_callback('/&amp;#0*([0-9]{1,5});/',
562                          function ($m) { return kses_normalize_entities2($m[1]); },
563                          $string);
564   $string = preg_replace('/&amp;#([Xx])0*(([0-9A-Fa-f]{2}){1,2});/',
565                          '&#\\1\\2;', $string);
566
567   return $string;
568 } # function kses_normalize_entities
569
570
571 function kses_normalize_entities2($i)
572 ###############################################################################
573 # This function helps kses_normalize_entities() to only accept 16 bit values
574 # and nothing more for &#number; entities.
575 ###############################################################################
576 {
577   return (($i > 65535) ? "&amp;#$i;" : "&#$i;");
578 } # function kses_normalize_entities2
579
580
581 function kses_decode_entities($string)
582 ###############################################################################
583 # This function decodes numeric HTML entities (&#65; and &#x41;). It doesn't
584 # do anything with other entities like &auml;, but we don't need them in the
585 # URL protocol whitelisting system anyway.
586 ###############################################################################
587 {
588   $string = preg_replace('/&#([0-9]+);/', function($m){return chr($m[1]);}, $string);
589   $string = preg_replace('/&#[Xx]([0-9A-Fa-f]+);/', function($m){return chr(hexdec($m[1]));},
590                          $string);
591
592   return $string;
593 } # function kses_decode_entities
594
595 function _sanitize_hexentity($match) {
596   return '&#' . intval("0".substr($match[0], 2, strlen($match[0]) -3)) . ';';
597 }
598
599 function kses_verify_css($cssstr)
600 ###############################################################################
601 # CSS expression checker for IE.
602 # See URLs below for details;
603 #   - http://openmya.hacker.jp/hasegawa/security/expression.txt
604 #   - http://archive.openmya.devnull.jp/2006.08/msg00369.html
605 #   - https://www.webappsec.jp/modules/bwiki/index.php?IE%A4%CEexpression%A4%C8url
606 ###############################################################################
607 {
608   if (!$cssstr) return true;
609   $ok = false;
610   $cssstr = preg_replace_callback('/&#x[0-9A-F]+;/i', '_sanitize_hexentity', $cssstr);
611   $cssstr = mb_decode_numericentity($cssstr, array(0, 0xFFFFFF, 0, 0xFFFFFF), 'UTF-8');
612   $cssstr = preg_replace('/\x5c(\d+)/', '&#x\1;', $cssstr);
613   $cssstr = preg_replace_callback('/&#x[0-9A-F]+;/i', '_sanitize_hexentity', $cssstr);
614   $cssstr = mb_decode_numericentity($cssstr, array(0, 0xFFFFFF, 0, 0xFFFFFF), 'UTF-8');
615   $cssstr = preg_replace('{/\*.*?\*/|\x00+}', '', $cssstr);
616   $enc_orig = mb_regex_encoding();
617   mb_regex_encoding('UTF-8');
618   #   e    x    p    r    e    s    s    i    o    n
619   #  FF45 FF58 FF50 FF52 FF45 FF53 FF53 FF49 FF4F FF4E
620   #  FF25 FF38 FF30 FF32 FF25 FF33 FF33 FF29 FF2F FF2E
621   #                 0280                          0274
622   #                                               027F
623   $ok = !mb_eregi('javascript:|@import|[e\x{ff45}\x{ff25}][x\x{ff58}\x{ff38}][p\x{ff50}\x{ff30}][r\x{ff52}\x{ff32}\x{0280}][e\x{ff45}\x{ff25}][s\x{ff53}\x{ff33}]{2}[i\x{ff49}\x{ff29}][o\x{ff4f}\x{ff2f}][n\x{ff4e}\x{ff2e}\x{0274}\x{207f}]', $cssstr);
624   mb_regex_encoding($enc_orig);
625   return $ok;
626 }
627
628 ?>