OSDN Git Service

Very roughly strings(1)
[pukiwiki/pukiwiki_sandbox.git] / spam / spam.php
1 <?php
2 // $Id: spam.php,v 1.132 2007/04/22 21:49:08 henoheno Exp $
3 // Copyright (C) 2006-2007 PukiWiki Developers Team
4 // License: GPL v2 or (at your option) any later version
5 //
6 // Functions for Concept-work of spam-uri metrics
7 //
8 // (PHP 4 >= 4.3.0): preg_match_all(PREG_OFFSET_CAPTURE): $method['uri_XXX'] related feature
9
10 if (! defined('SPAM_INI_FILE')) define('SPAM_INI_FILE', 'spam.ini.php');
11
12 // ---------------------
13 // Compat etc
14
15 // (PHP 4 >= 4.2.0): var_export(): mail-reporting and dump related
16 if (! function_exists('var_export')) {
17         function var_export() {
18                 return 'var_export() is not found on this server' . "\n";
19         }
20 }
21
22 // (PHP 4 >= 4.2.0): preg_grep() enables invert option
23 function preg_grep_invert($pattern = '//', $input = array())
24 {
25         static $invert;
26         if (! isset($invert)) $invert = defined('PREG_GREP_INVERT');
27
28         if ($invert) {
29                 return preg_grep($pattern, $input, PREG_GREP_INVERT);
30         } else {
31                 $result = preg_grep($pattern, $input);
32                 if ($result) {
33                         return array_diff($input, preg_grep($pattern, $input));
34                 } else {
35                         return $input;
36                 }
37         }
38 }
39
40 // Very roughly strings(1)
41 function strings($binary = '')
42 {
43         // http://www.pcre.org/pcre.txt
44         return preg_replace('/[[:^graph:]]+/', "\n", $binary);
45 }
46
47
48 // ---------------------
49 // URI pickup
50
51 // Return an array of URIs in the $string
52 // [OK] http://nasty.example.org#nasty_string
53 // [OK] http://nasty.example.org:80/foo/xxx#nasty_string/bar
54 // [OK] ftp://nasty.example.org:80/dfsdfs
55 // [OK] ftp://cnn.example.com&story=breaking_news@10.0.0.1/top_story.htm (from RFC3986)
56 function uri_pickup($string = '')
57 {
58         if (! is_string($string)) return array();
59
60         // Not available for: IDN(ignored)
61         $array = array();
62         preg_match_all(
63                 // scheme://userinfo@host:port/path/or/pathinfo/maybefile.and?query=string#fragment
64                 // Refer RFC3986 (Regex below is not strict)
65                 '#(\b[a-z][a-z0-9.+-]{1,8}):/+' .       // 1: Scheme
66                 '(?:' .
67                         '([^\s<>"\'\[\]/\#?@]*)' .              // 2: Userinfo (Username)
68                 '@)?' .
69                 '(' .
70                         // 3: Host
71                         '\[[0-9a-f:.]+\]' . '|' .                               // IPv6([colon-hex and dot]): RFC2732
72                         '(?:[0-9]{1,3}\.){3}[0-9]{1,3}' . '|' . // IPv4(dot-decimal): 001.22.3.44
73                         '[a-z0-9.-]+' .                                                 // hostname(FQDN) : foo.example.org
74                 ')' .
75                 '(?::([0-9]*))?' .                                      // 4: Port
76                 '((?:/+[^\s<>"\'\[\]/\#]+)*/+)?' .      // 5: Directory path or path-info
77                 '([^\s<>"\'\[\]\#?]+)?' .                       // 6: File?
78                 '(?:\?([^\s<>"\'\[\]\#]+))?' .          // 7: Query string
79                 '(?:\#([a-z0-9._~%!$&\'()*+,;=:@-]*))?' .       // 8: Fragment
80                 '#i',
81                  $string, $array, PREG_SET_ORDER | PREG_OFFSET_CAPTURE
82         );
83
84         // Format the $array
85         static $parts = array(
86                 1 => 'scheme', 2 => 'userinfo', 3 => 'host', 4 => 'port',
87                 5 => 'path', 6 => 'file', 7 => 'query', 8 => 'fragment'
88         );
89         $default = array('');
90         foreach(array_keys($array) as $uri) {
91                 $_uri = & $array[$uri];
92                 array_rename_keys($_uri, $parts, TRUE, $default);
93                 $offset = $_uri['scheme'][1]; // Scheme's offset = URI's offset
94                 foreach(array_keys($_uri) as $part) {
95                         $_uri[$part] = & $_uri[$part][0];       // Remove offsets
96                 }
97         }
98
99         foreach(array_keys($array) as $uri) {
100                 $_uri = & $array[$uri];
101                 if ($_uri['scheme'] === '') {
102                         unset($array[$uri]);    // Considererd harmless
103                         continue;
104                 }
105                 unset($_uri[0]); // Matched string itself
106                 $_uri['area']['offset'] = $offset;      // Area offset for area_measure()
107         }
108
109         return $array;
110 }
111
112 // Normalize an array of URI arrays
113 // NOTE: Give me the uri_pickup() results
114 function uri_pickup_normalize(& $pickups, $destructive = TRUE)
115 {
116         if (! is_array($pickups)) return $pickups;
117
118         if ($destructive) {
119                 foreach (array_keys($pickups) as $key) {
120                         $_key = & $pickups[$key];
121                         $_key['scheme']   = isset($_key['scheme']) ? scheme_normalize($_key['scheme']) : '';
122                         $_key['host']     = isset($_key['host'])     ? host_normalize($_key['host']) : '';
123                         $_key['port']     = isset($_key['port'])       ? port_normalize($_key['port'], $_key['scheme'], FALSE) : '';
124                         $_key['path']     = isset($_key['path'])     ? strtolower(path_normalize($_key['path'])) : '';
125                         $_key['file']     = isset($_key['file'])     ? file_normalize($_key['file']) : '';
126                         $_key['query']    = isset($_key['query'])    ? query_normalize($_key['query']) : '';
127                         $_key['fragment'] = isset($_key['fragment']) ? strtolower($_key['fragment']) : '';
128                 }
129         } else {
130                 foreach (array_keys($pickups) as $key) {
131                         $_key = & $pickups[$key];
132                         $_key['scheme']   = isset($_key['scheme']) ? scheme_normalize($_key['scheme']) : '';
133                         $_key['host']     = isset($_key['host'])   ? strtolower($_key['host']) : '';
134                         $_key['port']     = isset($_key['port'])   ? port_normalize($_key['port'], $_key['scheme'], FALSE) : '';
135                         $_key['path']     = isset($_key['path'])   ? path_normalize($_key['path']) : '';
136                 }
137         }
138
139         return $pickups;
140 }
141
142 // An URI array => An URI (See uri_pickup())
143 // USAGE:
144 //      $pickups = uri_pickup('a string include some URIs');
145 //      $uris = array();
146 //      foreach (array_keys($pickups) as $key) {
147 //              $uris[$key] = uri_pickup_implode($pickups[$key]);
148 //      }
149 function uri_pickup_implode($uri = array())
150 {
151         if (empty($uri) || ! is_array($uri)) return NULL;
152
153         $tmp = array();
154         if (isset($uri['scheme']) && $uri['scheme'] !== '') {
155                 $tmp[] = & $uri['scheme'];
156                 $tmp[] = '://';
157         }
158         if (isset($uri['userinfo']) && $uri['userinfo'] !== '') {
159                 $tmp[] = & $uri['userinfo'];
160                 $tmp[] = '@';
161         }
162         if (isset($uri['host']) && $uri['host'] !== '') {
163                 $tmp[] = & $uri['host'];
164         }
165         if (isset($uri['port']) && $uri['port'] !== '') {
166                 $tmp[] = ':';
167                 $tmp[] = & $uri['port'];
168         }
169         if (isset($uri['path']) && $uri['path'] !== '') {
170                 $tmp[] = & $uri['path'];
171         }
172         if (isset($uri['file']) && $uri['file'] !== '') {
173                 $tmp[] = & $uri['file'];
174         }
175         if (isset($uri['query']) && $uri['query'] !== '') {
176                 $tmp[] = '?';
177                 $tmp[] = & $uri['query'];
178         }
179         if (isset($uri['fragment']) && $uri['fragment'] !== '') {
180                 $tmp[] = '#';
181                 $tmp[] = & $uri['fragment'];
182         }
183
184         return implode('', $tmp);
185 }
186
187 // $array['something'] => $array['wanted']
188 function array_rename_keys(& $array, $keys = array('from' => 'to'), $force = FALSE, $default = '')
189 {
190         if (! is_array($array) || ! is_array($keys)) return FALSE;
191
192         // Nondestructive test
193         if (! $force)
194                 foreach(array_keys($keys) as $from)
195                         if (! isset($array[$from]))
196                                 return FALSE;
197
198         foreach($keys as $from => $to) {
199                 if ($from === $to) continue;
200                 if (! $force || isset($array[$from])) {
201                         $array[$to] = & $array[$from];
202                         unset($array[$from]);
203                 } else  {
204                         $array[$to] = $default;
205                 }
206         }
207
208         return TRUE;
209 }
210
211 // ---------------------
212 // Area pickup
213
214 // Pickup all of markup areas
215 function area_pickup($string = '', $method = array())
216 {
217         $area = array();
218         if (empty($method)) return $area;
219
220         // Anchor tag pair by preg_match and preg_match_all()
221         // [OK] <a href></a>
222         // [OK] <a href=  >Good site!</a>
223         // [OK] <a href= "#" >test</a>
224         // [OK] <a href="http://nasty.example.com">visit http://nasty.example.com/</a>
225         // [OK] <a href=\'http://nasty.example.com/\' >discount foobar</a> 
226         // [NG] <a href="http://ng.example.com">visit http://ng.example.com _not_ended_
227         $regex = '#<a\b[^>]*\bhref\b[^>]*>.*?</a\b[^>]*(>)#i';
228         if (isset($method['area_anchor'])) {
229                 $areas = array();
230                 $count = isset($method['asap']) ?
231                         preg_match($regex, $string) :
232                         preg_match_all($regex, $string, $areas);
233                 if (! empty($count)) $area['area_anchor'] = $count;
234         }
235         if (isset($method['uri_anchor'])) {
236                 $areas = array();
237                 preg_match_all($regex, $string, $areas, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
238                 foreach(array_keys($areas) as $_area) {
239                         $areas[$_area] =  array(
240                                 $areas[$_area][0][1], // Area start (<a href>)
241                                 $areas[$_area][1][1], // Area end   (</a>)
242                         );
243                 }
244                 if (! empty($areas)) $area['uri_anchor'] = $areas;
245         }
246
247         // phpBB's "BBCode" pair by preg_match and preg_match_all()
248         // [OK] [url][/url]
249         // [OK] [url]http://nasty.example.com/[/url]
250         // [OK] [link]http://nasty.example.com/[/link]
251         // [OK] [url=http://nasty.example.com]visit http://nasty.example.com/[/url]
252         // [OK] [link http://nasty.example.com/]buy something[/link]
253         $regex = '#\[(url|link)\b[^\]]*\].*?\[/\1\b[^\]]*(\])#i';
254         if (isset($method['area_bbcode'])) {
255                 $areas = array();
256                 $count = isset($method['asap']) ?
257                         preg_match($regex, $string) :
258                         preg_match_all($regex, $string, $areas, PREG_SET_ORDER);
259                 if (! empty($count)) $area['area_bbcode'] = $count;
260         }
261         if (isset($method['uri_bbcode'])) {
262                 $areas = array();
263                 preg_match_all($regex, $string, $areas, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
264                 foreach(array_keys($areas) as $_area) {
265                         $areas[$_area] = array(
266                                 $areas[$_area][0][1], // Area start ([url])
267                                 $areas[$_area][2][1], // Area end   ([/url])
268                         );
269                 }
270                 if (! empty($areas)) $area['uri_bbcode'] = $areas;
271         }
272
273         // Various Wiki syntax
274         // [text_or_uri>text_or_uri]
275         // [text_or_uri:text_or_uri]
276         // [text_or_uri|text_or_uri]
277         // [text_or_uri->text_or_uri]
278         // [text_or_uri text_or_uri] // MediaWiki
279         // MediaWiki: [http://nasty.example.com/ visit http://nasty.example.com/]
280
281         return $area;
282 }
283
284 // If in doubt, it's a little doubtful
285 // if (Area => inside <= Area) $brief += -1
286 function area_measure($areas, & $array, $belief = -1, $a_key = 'area', $o_key = 'offset')
287 {
288         if (! is_array($areas) || ! is_array($array)) return;
289
290         $areas_keys = array_keys($areas);
291         foreach(array_keys($array) as $u_index) {
292                 $offset = isset($array[$u_index][$o_key]) ?
293                         intval($array[$u_index][$o_key]) : 0;
294                 foreach($areas_keys as $a_index) {
295                         if (isset($array[$u_index][$a_key])) {
296                                 $offset_s = intval($areas[$a_index][0]);
297                                 $offset_e = intval($areas[$a_index][1]);
298                                 // [Area => inside <= Area]
299                                 if ($offset_s < $offset && $offset < $offset_e) {
300                                         $array[$u_index][$a_key] += $belief;
301                                 }
302                         }
303                 }
304         }
305 }
306
307 // ---------------------
308 // Spam-uri pickup
309
310 // Domain exposure callback (See spam_uri_pickup_preprocess())
311 // http://victim.example.org/?foo+site:nasty.example.com+bar
312 // => http://nasty.example.com/?refer=victim.example.org
313 // NOTE: 'refer=' is not so good for (at this time).
314 // Consider about using IP address of the victim, try to avoid that.
315 function _preg_replace_callback_domain_exposure($matches = array())
316 {
317         $result = '';
318
319         // Preserve the victim URI as a complicity or ...
320         if (isset($matches[5])) {
321                 $result =
322                         $matches[1] . '://' .   // scheme
323                         $matches[2] . '/' .             // victim.example.org
324                         $matches[3];                    // The rest of all (before victim)
325         }
326
327         // Flipped URI
328         if (isset($matches[4])) {
329                 $result = 
330                         $matches[1] . '://' .   // scheme
331                         $matches[4] .                   // nasty.example.com
332                         '/?refer=' . strtolower($matches[2]) .  // victim.example.org
333                         ' ' . $result;
334         }
335
336         return $result;
337 }
338
339 // Preprocess: rawurldecode() and adding space(s) and something
340 // to detect/count some URIs _if possible_
341 // NOTE: It's maybe danger to var_dump(result). [e.g. 'javascript:']
342 // [OK] http://victim.example.org/go?http%3A%2F%2Fnasty.example.org
343 // [OK] http://victim.example.org/http://nasty.example.org
344 // TODO: link.toolbot.com, urlx.org
345 function spam_uri_pickup_preprocess($string = '')
346 {
347         if (! is_string($string)) return '';
348
349         $string = rawurldecode($string);
350
351         // Domain exposure (See _preg_replace_callback_domain_exposure())
352         $string = preg_replace_callback(
353                 array(
354                         '#(http)://' .
355                         '(' .
356                                 // Something Google: http://www.google.com/supported_domains
357                                 '(?:[a-z0-9.]+\.)?google\.[a-z]{2,3}(?:\.[a-z]{2})?' .
358                                 '|' .
359                                 // AltaVista
360                                 '(?:[a-z0-9.]+\.)?altavista.com' .
361                                 
362                         ')' .
363                         '/' .
364                         '([a-z0-9?=&.%_/\'\\\+-]+)' .                           // path/?query=foo+bar+
365                         '\bsite:([a-z0-9.%_-]+\.[a-z0-9.%_-]+)' .       // site:nasty.example.com
366                         //'()' .        // Preserve or remove?
367                         '#i',
368                 ),
369                 '_preg_replace_callback_domain_exposure',
370                 $string
371         );
372
373         // URI exposure (uriuri => uri uri)
374         $string = preg_replace(
375                 array(
376                         '#(?<! )(?:https?|ftp):/#i',
377                 //      '#[a-z][a-z0-9.+-]{1,8}://#i',
378                 //      '#[a-z][a-z0-9.+-]{1,8}://#i'
379                 ),
380                 ' $0',
381                 $string
382         );
383
384         return $string;
385 }
386
387 // Main function of spam-uri pickup,
388 // A wrapper function of uri_pickup()
389 function spam_uri_pickup($string = '', $method = array())
390 {
391         if (! is_array($method) || empty($method)) {
392                 $method = check_uri_spam_method();
393         }
394
395         $string = spam_uri_pickup_preprocess($string);
396
397         $array  = uri_pickup($string);
398
399         // Area elevation of URIs, for '(especially external)link' intension
400         if (! empty($array)) {
401                 $_method = array();
402                 if (isset($method['uri_anchor'])) $_method['uri_anchor'] = & $method['uri_anchor'];
403                 if (isset($method['uri_bbcode'])) $_method['uri_bbcode'] = & $method['uri_bbcode'];
404                 $areas = area_pickup($string, $_method, TRUE);
405                 if (! empty($areas)) {
406                         $area_shadow = array();
407                         foreach (array_keys($array) as $key) {
408                                 $area_shadow[$key] = & $array[$key]['area'];
409                                 foreach (array_keys($_method) as $_key) {
410                                         $area_shadow[$key][$_key] = 0;
411                                 }
412                         }
413                         foreach (array_keys($_method) as $_key) {
414                                 if (isset($areas[$_key])) {
415                                         area_measure($areas[$_key], $area_shadow, 1, $_key);
416                                 }
417                         }
418                 }
419         }
420
421         // Remove 'offset's for area_measure()
422         foreach(array_keys($array) as $key)
423                 unset($array[$key]['area']['offset']);
424
425         return $array;
426 }
427
428
429 // ---------------------
430 // Normalization
431
432 // Scheme normalization: Renaming the schemes
433 // snntp://example.org =>  nntps://example.org
434 // NOTE: Keep the static lists simple. See also port_normalize().
435 function scheme_normalize($scheme = '', $abbrevs_harmfull = TRUE)
436 {
437         // Abbreviations they have no intention of link
438         static $abbrevs = array(
439                 'ttp'   => 'http',
440                 'ttps'  => 'https',
441         );
442
443         // Aliases => normalized ones
444         static $aliases = array(
445                 'pop'   => 'pop3',
446                 'news'  => 'nntp',
447                 'imap4' => 'imap',
448                 'snntp' => 'nntps',
449                 'snews' => 'nntps',
450                 'spop3' => 'pop3s',
451                 'pops'  => 'pop3s',
452         );
453
454         if (! is_string($scheme)) return '';
455
456         $scheme = strtolower($scheme);
457         if (isset($abbrevs[$scheme])) {
458                 $scheme = $abbrevs_harmfull ? $abbrevs[$scheme] : '';
459         }
460         if (isset($aliases[$scheme])) {
461                 $scheme = $aliases[$scheme];
462         }
463
464         return $scheme;
465 }
466
467 // Hostname normlization (Destructive)
468 // www.foo     => www.foo   ('foo' seems TLD)
469 // www.foo.bar => foo.bar
470 // www.10.20   => www.10.20 (Invalid hostname)
471 // NOTE:
472 //   'www' is  mostly used as traditional hostname of WWW server.
473 //   'www.foo.bar' may be identical with 'foo.bar'.
474 function host_normalize($host = '')
475 {
476         if (! is_string($host)) return '';
477
478         $host = strtolower($host);
479         $matches = array();
480         if (preg_match('/^www\.(.+\.[a-z]+)$/', $host, $matches)) {
481                 return $matches[1];
482         } else {
483                 return $host;
484         }
485 }
486
487 // Port normalization: Suppress the (redundant) default port
488 // HTTP://example.org:80/ => http://example.org/
489 // HTTP://example.org:8080/ => http://example.org:8080/
490 // HTTPS://example.org:443/ => https://example.org/
491 function port_normalize($port, $scheme, $scheme_normalize = FALSE)
492 {
493         // Schemes that users _maybe_ want to add protocol-handlers
494         // to their web browsers. (and attackers _maybe_ want to use ...)
495         // Reference: http://www.iana.org/assignments/port-numbers
496         static $array = array(
497                 // scheme => default port
498                 'ftp'     =>    21,
499                 'ssh'     =>    22,
500                 'telnet'  =>    23,
501                 'smtp'    =>    25,
502                 'tftp'    =>    69,
503                 'gopher'  =>    70,
504                 'finger'  =>    79,
505                 'http'    =>    80,
506                 'pop3'    =>   110,
507                 'sftp'    =>   115,
508                 'nntp'    =>   119,
509                 'imap'    =>   143,
510                 'irc'     =>   194,
511                 'wais'    =>   210,
512                 'https'   =>   443,
513                 'nntps'   =>   563,
514                 'rsync'   =>   873,
515                 'ftps'    =>   990,
516                 'telnets' =>   992,
517                 'imaps'   =>   993,
518                 'ircs'    =>   994,
519                 'pop3s'   =>   995,
520                 'mysql'   =>  3306,
521         );
522
523         // intval() converts '0-1' to '0', so preg_match() rejects these invalid ones
524         if (! is_numeric($port) || $port < 0 || preg_match('/[^0-9]/i', $port))
525                 return '';
526
527         $port = intval($port);
528         if ($scheme_normalize) $scheme = scheme_normalize($scheme);
529         if (isset($array[$scheme]) && $port == $array[$scheme])
530                 $port = ''; // Ignore the defaults
531
532         return $port;
533 }
534
535 // Path normalization
536 // http://example.org => http://example.org/
537 // http://example.org#hoge => http://example.org/#hoge
538 // http://example.org/path/a/b/./c////./d => http://example.org/path/a/b/c/d
539 // http://example.org/path/../../a/../back => http://example.org/back
540 function path_normalize($path = '', $divider = '/', $add_root = TRUE)
541 {
542         if (! is_string($divider)) return is_string($path) ? $path : '';
543
544         if ($add_root) {
545                 $first_div = & $divider;
546         } else {
547                 $first_div = '';
548         }
549         if (! is_string($path) || $path == '') return $first_div;
550
551         if (strpos($path, $divider, strlen($path) - strlen($divider)) === FALSE) {
552                 $last_div = '';
553         } else {
554                 $last_div = & $divider;
555         }
556
557         $array = explode($divider, $path);
558
559         // Remove paddings ('//' and '/./')
560         foreach(array_keys($array) as $key) {
561                 if ($array[$key] == '' || $array[$key] == '.') {
562                          unset($array[$key]);
563                 }
564         }
565
566         // Remove back-tracks ('/../')
567         $tmp = array();
568         foreach($array as $value) {
569                 if ($value == '..') {
570                         array_pop($tmp);
571                 } else {
572                         array_push($tmp, $value);
573                 }
574         }
575         $array = & $tmp;
576
577         if (empty($array)) {
578                 return $first_div;
579         } else {
580                 return $first_div . implode($divider, $array) . $last_div;
581         }
582 }
583
584 // DirectoryIndex normalize (Destructive and rough)
585 // TODO: sample.en.ja.html.gz => sample.html
586 function file_normalize($file = 'index.html.en')
587 {
588         static $simple_defaults = array(
589                 'default.htm'   => TRUE,
590                 'default.html'  => TRUE,
591                 'default.asp'   => TRUE,
592                 'default.aspx'  => TRUE,
593                 'index'                 => TRUE,        // Some system can omit the suffix
594         );
595
596         static $content_suffix = array(
597                 // index.xxx, sample.xxx
598                 'htm'   => TRUE,
599                 'html'  => TRUE,
600                 'shtml' => TRUE,
601                 'jsp'   => TRUE,
602                 'php'   => TRUE,
603                 'php3'  => TRUE,
604                 'php4'  => TRUE,
605                 'pl'    => TRUE,
606                 'py'    => TRUE,
607                 'rb'    => TRUE,
608                 'cgi'   => TRUE,
609                 'xml'   => TRUE,
610         );
611
612         static $language_suffix = array(
613                 // Reference: Apache 2.0.59 'AddLanguage' default
614                 'ca'    => TRUE,
615                 'cs'    => TRUE,        // cs
616                 'cz'    => TRUE,        // cs
617                 'de'    => TRUE,
618                 'dk'    => TRUE,        // da
619                 'el'    => TRUE,
620                 'en'    => TRUE,
621                 'eo'    => TRUE,
622                 'es'    => TRUE,
623                 'et'    => TRUE,
624                 'fr'    => TRUE,
625                 'he'    => TRUE,
626                 'hr'    => TRUE,
627                 'it'    => TRUE,
628                 'ja'    => TRUE,
629                 'ko'    => TRUE,
630                 'ltz'   => TRUE,
631                 'nl'    => TRUE,
632                 'nn'    => TRUE,
633                 'no'    => TRUE,
634                 'po'    => TRUE,
635                 'pt'    => TRUE,
636                 'pt-br' => TRUE,
637                 'ru'    => TRUE,
638                 'sv'    => TRUE,
639                 'zh-cn' => TRUE,
640                 'zh-tw' => TRUE,
641
642                 // Reference: Apache 2.0.59 default 'index.html' variants
643                 'ee'    => TRUE,
644                 'lb'    => TRUE,
645                 'var'   => TRUE,
646         );
647
648         static $charset_suffix = array(
649                 // Reference: Apache 2.0.59 'AddCharset' default
650                 'iso8859-1'     => TRUE, // ISO-8859-1
651                 'latin1'        => TRUE, // ISO-8859-1
652                 'iso8859-2'     => TRUE, // ISO-8859-2
653                 'latin2'        => TRUE, // ISO-8859-2
654                 'cen'           => TRUE, // ISO-8859-2
655                 'iso8859-3'     => TRUE, // ISO-8859-3
656                 'latin3'        => TRUE, // ISO-8859-3
657                 'iso8859-4'     => TRUE, // ISO-8859-4
658                 'latin4'        => TRUE, // ISO-8859-4
659                 'iso8859-5'     => TRUE, // ISO-8859-5
660                 'latin5'        => TRUE, // ISO-8859-5
661                 'cyr'           => TRUE, // ISO-8859-5
662                 'iso-ru'        => TRUE, // ISO-8859-5
663                 'iso8859-6'     => TRUE, // ISO-8859-6
664                 'latin6'        => TRUE, // ISO-8859-6
665                 'arb'           => TRUE, // ISO-8859-6
666                 'iso8859-7'     => TRUE, // ISO-8859-7
667                 'latin7'        => TRUE, // ISO-8859-7
668                 'grk'           => TRUE, // ISO-8859-7
669                 'iso8859-8'     => TRUE, // ISO-8859-8
670                 'latin8'        => TRUE, // ISO-8859-8
671                 'heb'           => TRUE, // ISO-8859-8
672                 'iso8859-9'     => TRUE, // ISO-8859-9
673                 'latin9'        => TRUE, // ISO-8859-9
674                 'trk'           => TRUE, // ISO-8859-9
675                 'iso2022-jp'=> TRUE, // ISO-2022-JP
676                 'jis'           => TRUE, // ISO-2022-JP
677                 'iso2022-kr'=> TRUE, // ISO-2022-KR
678                 'kis'           => TRUE, // ISO-2022-KR
679                 'iso2022-cn'=> TRUE, // ISO-2022-CN
680                 'cis'           => TRUE, // ISO-2022-CN
681                 'big5'          => TRUE,
682                 'cp-1251'       => TRUE, // ru, WINDOWS-1251
683                 'win-1251'      => TRUE, // ru, WINDOWS-1251
684                 'cp866'         => TRUE, // ru
685                 'koi8-r'        => TRUE, // ru, KOI8-r
686                 'koi8-ru'       => TRUE, // ru, KOI8-r
687                 'koi8-uk'       => TRUE, // ru, KOI8-ru
688                 'ua'            => TRUE, // ru, KOI8-ru
689                 'ucs2'          => TRUE, // ru, ISO-10646-UCS-2
690                 'ucs4'          => TRUE, // ru, ISO-10646-UCS-4
691                 'utf8'          => TRUE,
692
693                 // Reference: Apache 2.0.59 default 'index.html' variants
694                 'euc-kr'        => TRUE,
695                 'gb2312'        => TRUE,
696         );
697
698         // May uncompress by web browsers on the fly
699         // Must be at the last of the filename
700         // Reference: Apache 2.0.59 'AddEncoding'
701         static $encoding_suffix = array(
702                 'z'             => TRUE,
703                 'gz'    => TRUE,
704         );
705
706         if (! is_string($file)) return '';
707         $_file = strtolower($file);
708         if (isset($simple_defaults[$_file])) return '';
709
710
711         // Roughly removing language/character-set/encoding suffixes
712         // References:
713         //  * Apache 2 document about 'Content-negotiaton', 'mod_mime' and 'mod_negotiation'
714         //    http://httpd.apache.org/docs/2.0/content-negotiation.html
715         //    http://httpd.apache.org/docs/2.0/mod/mod_mime.html
716         //    http://httpd.apache.org/docs/2.0/mod/mod_negotiation.html
717         //  * http://www.iana.org/assignments/character-sets
718         //  * RFC3066: Tags for the Identification of Languages
719         //    http://www.ietf.org/rfc/rfc3066.txt
720         //  * ISO 639: codes of 'language names'
721         $suffixes = explode('.', $_file);
722         $body = array_shift($suffixes);
723         if ($suffixes) {
724                 // Remove the last .gz/.z
725                 $last_key = end(array_keys($suffixes));
726                 if (isset($encoding_suffix[$suffixes[$last_key]])) {
727                         unset($suffixes[$last_key]);
728                 }
729         }
730         // Cut language and charset suffixes
731         foreach($suffixes as $key => $value){
732                 if (isset($language_suffix[$value]) || isset($charset_suffix[$value])) {
733                         unset($suffixes[$key]);
734                 }
735         }
736         if (empty($suffixes)) return $body;
737
738         // Index.xxx
739         $count = count($suffixes);
740         reset($suffixes);
741         $current = current($suffixes);
742         if ($body == 'index' && $count == 1 && isset($content_suffix[$current])) return '';
743
744         return $file;
745 }
746
747 // Sort query-strings if possible (Destructive and rough)
748 // [OK] &&&&f=d&b&d&c&a=0dd  =>  a=0dd&b&c&d&f=d
749 // [OK] nothing==&eg=dummy&eg=padding&eg=foobar  =>  eg=foobar
750 function query_normalize($string = '', $equal = TRUE, $equal_cutempty = TRUE, $stortolower = TRUE)
751 {
752         if (! is_string($string)) return '';
753         if ($stortolower) $string = strtolower($string);
754
755         $array = explode('&', $string);
756
757         // Remove '&' paddings
758         foreach(array_keys($array) as $key) {
759                 if ($array[$key] == '') {
760                          unset($array[$key]);
761                 }
762         }
763
764         // Consider '='-sepalated input and paddings
765         if ($equal) {
766                 $equals = $not_equals = array();
767                 foreach ($array as $part) {
768                         if (strpos($part, '=') === FALSE) {
769                                  $not_equals[] = $part;
770                         } else {
771                                 list($key, $value) = explode('=', $part, 2);
772                                 $value = ltrim($value, '=');
773                                 if (! $equal_cutempty || $value != '') {
774                                         $equals[$key] = $value;
775                                 }
776                         }
777                 }
778
779                 $array = & $not_equals;
780                 foreach ($equals as $key => $value) {
781                         $array[] = $key . '=' . $value;
782                 }
783                 unset($equals);
784         }
785
786         natsort($array);
787         return implode('&', $array);
788 }
789
790 // ---------------------
791 // Part One : Checker
792
793 // Rough implementation of globbing
794 //
795 // USAGE: $regex = '/^' . generate_glob_regex('*.txt', '/') . '$/i';
796 //
797 function generate_glob_regex($string = '', $divider = '/')
798 {
799         static $from = array(
800                          1 => '*',
801                         11 => '?',
802         //              22 => '[',      // Maybe cause regex compilation error (e.g. '[]')
803         //              23 => ']',      //
804                 );
805         static $mid = array(
806                          1 => '_AST_',
807                         11 => '_QUE_',
808         //              22 => '_RBR_',
809         //              23 => '_LBR_',
810                 );
811         static $to = array(
812                          1 => '.*',
813                         11 => '.',
814         //              22 => '[',
815         //              23 => ']',
816                 );
817
818         if (! is_string($string)) return '';
819
820         $string = str_replace($from, $mid, $string); // Hide
821         $string = preg_quote($string, $divider);
822         $string = str_replace($mid, $to, $string);   // Unhide
823
824         return $string;
825 }
826
827 // Rough hostname checker
828 // [OK] 192.168.
829 // TODO: Strict digit, 0x, CIDR, IPv6
830 function is_ip($string = '')
831 {
832         if (preg_match('/^' .
833                 '(?:[0-9]{1,3}\.){3}[0-9]{1,3}' . '|' .
834                 '(?:[0-9]{1,3}\.){1,3}' . '$/',
835                 $string)) {
836                 return 4;       // Seems IPv4(dot-decimal)
837         } else {
838                 return 0;       // Seems not IP
839         }
840 }
841
842 // Generate host (FQDN, IPv4, ...) regex
843 // 'localhost'     : Matches with 'localhost' only
844 // 'example.org'   : Matches with 'example.org' only (See host_normalize() about 'www')
845 // '.example.org'  : Matches with ALL FQDN ended with '.example.org'
846 // '*.example.org' : Almost the same of '.example.org' except 'www.example.org'
847 // '10.20.30.40'   : Matches with IPv4 address '10.20.30.40' only
848 // [TODO] '192.'   : Matches with all IPv4 hosts started with '192.'
849 // TODO: IPv4, CIDR?, IPv6
850 function generate_host_regex($string = '', $divider = '/')
851 {
852         if (! is_string($string)) return '';
853
854         if (mb_strpos($string, '.') === FALSE)
855                 return generate_glob_regex($string, $divider);
856
857         $result = '';
858         if (is_ip($string)) {
859                 // IPv4
860                 return generate_glob_regex($string, $divider);
861         } else {
862                 // FQDN or something
863                 $part = explode('.', $string, 2);
864                 if ($part[0] == '') {
865                         $part[0] = '(?:.*\.)?'; // And all related FQDN
866                 } else if ($part[0] == '*') {
867                         $part[0] = '.*\.';      // All subdomains/hosts only
868                 } else {
869                         return generate_glob_regex($string, $divider);
870                 }
871                 $part[1] = generate_glob_regex($part[1], $divider);
872                 return implode('', $part);
873         }
874 }
875
876 function get_blocklist($list = '')
877 {
878         static $regexs;
879
880         if (! isset($regexs)) {
881                 $regexs = array();
882                 if (file_exists(SPAM_INI_FILE)) {
883                         $blocklist = array();
884                         include(SPAM_INI_FILE);
885                         //      $blocklist['badhost'] = array(
886                         //              '*.blogspot.com',       // Blog services's subdomains (only)
887                         //              'IANA-examples' => '#^(?:.*\.)?example\.(?:com|net|org)$#',
888                         //      );
889                         if (isset($blocklist['list'])) {
890                                 $regexs['list'] = & $blocklist['list'];
891                         } else {
892                                 // Default
893                                 $blocklist['list'] = array(
894                                         'goodhost' => FALSE,
895                                         'badhost'  => TRUE,
896                                 );
897                         }
898                         foreach(array_keys($blocklist['list']) as $_list) {
899                                 if (! isset($blocklist[$_list])) continue;
900                                 foreach ($blocklist[$_list] as $key => $value) {
901                                         if (is_array($value)) {
902                                                 $regexs[$_list][$key] = array();
903                                                 foreach($value as $_key => $_value) {
904                                                         get_blocklist_add($regexs[$_list][$key], $_key, $_value);
905                                                 }
906                                         } else {
907                                                 get_blocklist_add($regexs[$_list], $key, $value);
908                                         }
909                                 }
910                                 unset($blocklist[$_list]);
911                         }
912                 }
913         }
914
915         if ($list == '') {
916                 return $regexs; // ALL
917         } else if (isset($regexs[$list])) {
918                 return $regexs[$list];
919         } else {        
920                 return array();
921         }
922 }
923
924 // Subroutine of get_blocklist()
925 function get_blocklist_add(& $array, $key = 0, $value = '*.example.org')
926 {
927         if (is_string($key)) {
928                 $array[$key] = & $value; // Treat $value as a regex
929         } else {
930                 $array[$value] = '/^' . generate_host_regex($value, '/') . '$/i';
931         }
932 }
933
934 function is_badhost($hosts = array(), $asap = TRUE, & $remains)
935 {
936         $result = array();
937         if (! is_array($hosts)) $hosts = array($hosts);
938         foreach(array_keys($hosts) as $key) {
939                 if (! is_string($hosts[$key])) {
940                         unset($hosts[$key]);
941                 }
942         }
943         if (empty($hosts)) return $result;
944
945         foreach(get_blocklist('list') as $key=>$value){
946                 if ($value) {
947                         foreach (get_blocklist($key) as $label => $regex) {
948                                 if (is_array($regex)) {
949                                         $result[$label] = array();
950                                         foreach($regex as $_label => $_regex) {
951                                                 if (is_badhost_avail($_label, $_regex, $hosts, $result[$label]) && $asap) {
952                                                         break;
953                                                 }
954                                         }
955                                         if (empty($result[$label])) unset($result[$label]);
956                                 } else {
957                                         if (is_badhost_avail($label, $regex, $hosts, $result) && $asap) {
958                                                 break;
959                                         }
960                                 }
961                         }
962                 } else {
963                         foreach (get_blocklist($key) as $regex) {
964                                 $hosts = preg_grep_invert($regex, $hosts);
965                         }
966                         if (empty($hosts)) return $result;
967                 }
968         }
969
970         $remains = $hosts;
971         return $result;
972 }
973
974 // Subroutine for is_badhost()
975 function is_badhost_avail($label = '*.example.org', $regex = '/^.*\.example\.org$/', & $hosts, & $result)
976 {
977         $group = preg_grep($regex, $hosts);
978         if ($group) {
979
980                 // DEBUG var_dump($group); // badhost detail
981
982                 $result[$label] = & $group;
983                 $hosts = array_diff($hosts, $result[$label]);
984                 return TRUE;
985         } else {
986                 return FALSE;
987         }
988 }
989
990 // Default (enabled) methods and thresholds (for content insertion)
991 function check_uri_spam_method($times = 1, $t_area = 0, $rule = TRUE)
992 {
993         $times  = intval($times);
994         $t_area = intval($t_area);
995
996         $positive = array(
997                 // Thresholds
998                 'quantity'     =>  8 * $times,  // Allow N URIs
999                 'non_uniqhost' =>  3 * $times,  // Allow N duped (and normalized) Hosts
1000                 //'non_uniquri'=>  3 * $times,  // Allow N duped (and normalized) URIs
1001
1002                 // Areas
1003                 'area_anchor'  => $t_area,      // Using <a href> HTML tag
1004                 'area_bbcode'  => $t_area,      // Using [url] or [link] BBCode
1005                 //'uri_anchor' => $t_area,      // URI inside <a href> HTML tag
1006                 //'uri_bbcode' => $t_area,      // URI inside [url] or [link] BBCode
1007         );
1008         if ($rule) {
1009                 $bool = array(
1010                         // Rules
1011                         //'asap'   => TRUE,     // Quit or return As Soon As Possible
1012                         'uniqhost' => TRUE,     // Show uniq host (at block notification mail)
1013                         'badhost'  => TRUE,     // Check badhost
1014                 );
1015         } else {
1016                 $bool = array();
1017         }
1018
1019         // Remove non-$positive values
1020         foreach (array_keys($positive) as $key) {
1021                 if ($positive[$key] < 0) unset($positive[$key]);
1022         }
1023
1024         return $positive + $bool;
1025 }
1026
1027 // Simple/fast spam check
1028 function check_uri_spam($target = '', $method = array())
1029 {
1030         if (! is_array($method) || empty($method)) {
1031                 $method = check_uri_spam_method();
1032         }
1033         $progress = array(
1034                 'sum' => array(
1035                         'quantity'    => 0,
1036                         'uniqhost'    => 0,
1037                         'non_uniqhost'=> 0,
1038                         'non_uniquri' => 0,
1039                         'badhost'     => 0,
1040                         'area_anchor' => 0,
1041                         'area_bbcode' => 0,
1042                         'uri_anchor'  => 0,
1043                         'uri_bbcode'  => 0,
1044                 ),
1045                 'is_spam' => array(),
1046                 'method'  => & $method,
1047                 'remains' => array(),
1048                 'error'   => array(),
1049         );
1050         $sum     = & $progress['sum'];
1051         $is_spam = & $progress['is_spam'];
1052         $remains = & $progress['remains'];
1053         $error   = & $progress['error'];
1054         $asap    = isset($method['asap']);
1055
1056         // Recurse
1057         if (is_array($target)) {
1058                 foreach($target as $str) {
1059                         // Recurse
1060                         $_progress = check_uri_spam($str, $method);
1061                         $_sum      = & $_progress['sum'];
1062                         $_is_spam  = & $_progress['is_spam'];
1063                         $_remains  = & $_progress['remains'];
1064                         $_error    = & $_progress['error'];
1065                         foreach (array_keys($_sum) as $key) {
1066                                 $sum[$key] += $_sum[$key];
1067                         }
1068                         foreach (array_keys($_is_spam) as $key) {
1069                                 if (is_array($_is_spam[$key])) {
1070                                         // Marge keys (badhost)
1071                                         foreach(array_keys($_is_spam[$key]) as $_key) {
1072                                                 if (! isset($is_spam[$key][$_key])) {
1073                                                         $is_spam[$key][$_key] =  $_is_spam[$key][$_key];
1074                                                 } else {
1075                                                         $is_spam[$key][$_key] += $_is_spam[$key][$_key];
1076                                                 }
1077                                         }
1078                                 } else {
1079                                         $is_spam[$key] = TRUE;
1080                                 }
1081                         }
1082                         foreach ($_remains as $key=>$value) {
1083                                 foreach ($value as $_key=>$_value) {
1084                                         if (is_int($_key)) {
1085                                                 $remains[$key][]      = $_value;
1086                                         } else {
1087                                                 $remains[$key][$_key] = $_value;
1088                                         }
1089                                 }
1090                         }
1091                         if (! empty($_error)) $error += $_error;
1092                         if ($asap && $is_spam) break;
1093                 }
1094                 return $progress;
1095         }
1096
1097         // Area: There's HTML anchor tag
1098         if ((! $asap || ! $is_spam) && isset($method['area_anchor'])) {
1099                 $key = 'area_anchor';
1100                 $_asap = isset($method['asap']) ? array('asap' => TRUE) : array();
1101                 $result = area_pickup($target, array($key => TRUE) + $_asap);
1102                 if ($result) {
1103                         $sum[$key] = $result[$key];
1104                         if (isset($method[$key]) && $sum[$key] > $method[$key]) {
1105                                 $is_spam[$key] = TRUE;
1106                         }
1107                 }
1108         }
1109
1110         // Area: There's 'BBCode' linking tag
1111         if ((! $asap || ! $is_spam) && isset($method['area_bbcode'])) {
1112                 $key = 'area_bbcode';
1113                 $_asap = isset($method['asap']) ? array('asap' => TRUE) : array();
1114                 $result = area_pickup($target, array($key => TRUE) + $_asap);
1115                 if ($result) {
1116                         $sum[$key] = $result[$key];
1117                         if (isset($method[$key]) && $sum[$key] > $method[$key]) {
1118                                 $is_spam[$key] = TRUE;
1119                         }
1120                 }
1121         }
1122
1123         // Return if ...
1124         if ($asap && $is_spam) return $progress;
1125
1126         // URI: Pickup
1127         $pickups = uri_pickup_normalize(spam_uri_pickup($target, $method));
1128         //$remains['uri_pickup'] = & $pickups;
1129
1130         // Return if ...
1131         if (empty($pickups)) return $progress;
1132
1133         // URI: Check quantity
1134         $sum['quantity'] += count($pickups);
1135                 // URI quantity
1136         if ((! $asap || ! $is_spam) && isset($method['quantity']) &&
1137                 $sum['quantity'] > $method['quantity']) {
1138                 $is_spam['quantity'] = TRUE;
1139         }
1140
1141         // URI: used inside HTML anchor tag pair
1142         if ((! $asap || ! $is_spam) && isset($method['uri_anchor'])) {
1143                 $key = 'uri_anchor';
1144                 foreach($pickups as $pickup) {
1145                         if (isset($pickup['area'][$key])) {
1146                                 $sum[$key] += $pickup['area'][$key];
1147                                 if(isset($method[$key]) &&
1148                                         $sum[$key] > $method[$key]) {
1149                                         $is_spam[$key] = TRUE;
1150                                         if ($asap && $is_spam) break;
1151                                 }
1152                                 if ($asap && $is_spam) break;
1153                         }
1154                 }
1155         }
1156
1157         // URI: used inside 'BBCode' pair
1158         if ((! $asap || ! $is_spam) && isset($method['uri_bbcode'])) {
1159                 $key = 'uri_bbcode';
1160                 foreach($pickups as $pickup) {
1161                         if (isset($pickup['area'][$key])) {
1162                                 $sum[$key] += $pickup['area'][$key];
1163                                 if(isset($method[$key]) &&
1164                                         $sum[$key] > $method[$key]) {
1165                                         $is_spam[$key] = TRUE;
1166                                         if ($asap && $is_spam) break;
1167                                 }
1168                                 if ($asap && $is_spam) break;
1169                         }
1170                 }
1171         }
1172
1173         // URI: Uniqueness (and removing non-uniques)
1174         if ((! $asap || ! $is_spam) && isset($method['non_uniquri'])) {
1175
1176                 $uris = array();
1177                 foreach (array_keys($pickups) as $key) {
1178                         $uris[$key] = uri_pickup_implode($pickups[$key]);
1179                 }
1180                 $count = count($uris);
1181                 $uris  = array_unique($uris);
1182                 $sum['non_uniquri'] += $count - count($uris);
1183                 if ($sum['non_uniquri'] > $method['non_uniquri']) {
1184                         $is_spam['non_uniquri'] = TRUE;
1185                 }
1186                 if (! $asap || ! $is_spam) {
1187                         foreach (array_diff(array_keys($pickups),
1188                                 array_keys($uris)) as $remove) {
1189                                 unset($pickups[$remove]);
1190                         }
1191                 }
1192                 unset($uris);
1193         }
1194
1195         // Return if ...
1196         if ($asap && $is_spam) return $progress;
1197
1198         // Host: Uniqueness (uniq / non-uniq)
1199         $hosts = array();
1200         foreach ($pickups as $pickup) $hosts[] = & $pickup['host'];
1201         $hosts = array_unique($hosts);
1202         //$remains['uniqhost'] = & $hosts;
1203         $sum['uniqhost'] += count($hosts);
1204         if ((! $asap || ! $is_spam) && isset($method['non_uniqhost'])) {
1205                 $sum['non_uniqhost'] = $sum['quantity'] - $sum['uniqhost'];
1206                 if ($sum['non_uniqhost'] > $method['non_uniqhost']) {
1207                         $is_spam['non_uniqhost'] = TRUE;
1208                 }
1209         }
1210
1211         // Return if ...
1212         if ($asap && $is_spam) return $progress;
1213
1214         // URI: Bad host
1215         if ((! $asap || ! $is_spam) && isset($method['badhost'])) {
1216                 $__remains = array();
1217                 $badhost = is_badhost($hosts, $asap, $__remains);
1218                 if (! $asap) {
1219                         if ($__remains) {
1220                                 $remains['badhost'] = array();
1221                                 foreach ($__remains as $value) {
1222                                         $remains['badhost'][$value] = TRUE;
1223                                 }
1224                         }
1225                 }
1226                 unset($__remains);
1227                 if (! empty($badhost)) {
1228                         //var_dump($badhost);   // BADHOST detail
1229                         $sum['badhost'] += array_count_leaves($badhost);
1230                         foreach(array_keys($badhost) as $keys) {
1231                                 $is_spam['badhost'][$keys] =
1232                                         array_count_leaves($badhost[$keys]);
1233                         }
1234                         unset($badhost);
1235                 }
1236         }
1237
1238         return $progress;
1239 }
1240
1241 // Count leaves
1242 function array_count_leaves($array = array(), $count_empty_array = FALSE)
1243 {
1244         if (! is_array($array) || (empty($array) && $count_empty_array))
1245                 return 1;
1246
1247         // Recurse
1248         $result = 0;
1249         foreach ($array as $part) {
1250                 $result += array_count_leaves($part, $count_empty_array);
1251         }
1252         return $result;
1253 }
1254
1255 // ---------------------
1256 // Reporting
1257
1258 // TODO: Don't show unused $method!
1259 // Summarize $progress (blocked only)
1260 function summarize_spam_progress($progress = array(), $blockedonly = FALSE)
1261 {
1262         if ($blockedonly) {
1263                 $tmp = array_keys($progress['is_spam']);
1264         } else {
1265                 $tmp = array();
1266                 $method = & $progress['method'];
1267                 if (isset($progress['sum'])) {
1268                         foreach ($progress['sum'] as $key => $value) {
1269                                 if (isset($method[$key])) {
1270                                         $tmp[] = $key . '(' . $value . ')';
1271                                 }
1272                         }
1273                 }
1274         }
1275
1276         return implode(', ', $tmp);
1277 }
1278
1279 // ---------------------
1280 // Exit
1281
1282 // Common bahavior for blocking
1283 // NOTE: Call this function from various blocking feature, to disgueise the reason 'why blocked'
1284 function spam_exit($mode = '', $data = array())
1285 {
1286         switch ($mode) {
1287                 case '':        echo("\n");     break;
1288                 case 'dump':
1289                         echo('<pre>' . "\n");
1290                         echo htmlspecialchars(var_export($data, TRUE));
1291                         echo('</pre>' . "\n");
1292                         break;
1293         };
1294
1295         // Force exit
1296         exit;
1297 }
1298
1299
1300 // ---------------------
1301 // Simple filtering
1302
1303 // TODO: Record them
1304 // Simple/fast spam filter ($target: 'a string' or an array())
1305 function pkwk_spamfilter($action, $page, $target = array('title' => ''), $method = array(), $exitmode = '')
1306 {
1307         $progress = check_uri_spam($target, $method);
1308
1309         if (! empty($progress['is_spam'])) {
1310                 // Mail to administrator(s)
1311                 pkwk_spamnotify($action, $page, $target, $progress, $method);
1312
1313                 // Exit
1314                 spam_exit($exitmode, $progress);
1315         }
1316 }
1317
1318 // ---------------------
1319 // PukiWiki original
1320
1321 // Mail to administrator(s)
1322 function pkwk_spamnotify($action, $page, $target = array('title' => ''), $progress = array(), $method = array())
1323 {
1324         global $notify, $notify_subject;
1325
1326         if (! $notify) return;
1327
1328         $asap = isset($method['asap']);
1329
1330         $summary['ACTION']  = 'Blocked by: ' . summarize_spam_progress($progress, TRUE);
1331         if (! $asap) {
1332                 $summary['METRICS'] = summarize_spam_progress($progress);
1333         }
1334         if (isset($progress['is_spam']['badhost'])) {
1335                 $badhost = array();
1336                 foreach($progress['is_spam']['badhost'] as $glob=>$number) {
1337                         $badhost[] = $glob . '(' . $number . ')';
1338                 }
1339                 $summary['DETAIL_BADHOST'] = implode(', ', $badhost);
1340         }
1341         if (! $asap && $progress['remains']['badhost']) {
1342                 $count = count($progress['remains']['badhost']);
1343                 $summary['DETAIL_NEUTRAL_HOST'] = $count .
1344                         ' (' .
1345                                 preg_replace(
1346                                         '/[^, a-z0-9.-]/i', '',
1347                                         implode(', ', array_keys($progress['remains']['badhost']))
1348                                 ) .
1349                         ')';
1350         }
1351         $summary['COMMENT'] = $action;
1352         $summary['PAGE']    = '[blocked] ' . (is_pagename($page) ? $page : '');
1353         $summary['URI']     = get_script_uri() . '?' . rawurlencode($page);
1354         $summary['USER_AGENT']  = TRUE;
1355         $summary['REMOTE_ADDR'] = TRUE;
1356         pkwk_mail_notify($notify_subject,  var_export($target, TRUE), $summary, TRUE);
1357 }
1358
1359 ?>