OSDN Git Service

59b1989c8764d505f6be2f08fefae2158ecd6464
[pukiwiki/pukiwiki_sandbox.git] / spam / spam.php
1 <?php
2 // $Id: spam.php,v 1.134 2007/04/28 06:33:30 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[^>]*(>)#is';
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[^\]]*(\])#is';
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
935 // Blocklist metrics: Separate $host, to $blocked and not blocked
936 function blocklist_distiller(& $hosts, $keys = array('goodhost', 'badhost'), $asap = FALSE)
937 {
938         if (! is_array($hosts)) $hosts = array($hosts);
939         if (! is_array($keys))  $keys  = array($keys);
940
941         $list = get_blocklist('list');
942         $blocked = array();
943
944         foreach($keys as $key){
945                 foreach (get_blocklist($key) as $label => $regex) {
946                         if (is_array($regex)) {
947                                 foreach($regex as $_label => $_regex) {
948                                         $group = preg_grep($_regex, $hosts);
949                                         if ($group) {
950                                                 $hosts = array_diff($hosts, $group);
951                                                 $blocked[$key][$label][$_label] = $group;
952                                                 if ($asap && $list[$key]) break;
953                                         }
954                                 }
955                         } else {
956                                 $group = preg_grep($regex, $hosts);
957                                 if ($group) {
958                                         $hosts = array_diff($hosts, $group);
959                                         $blocked[$key][$label] = $group;
960                                         if ($asap && $list[$key]) break;
961                                 }
962                         }
963                 }
964         }
965
966         return $blocked;
967 }
968
969 function is_badhost($hosts = array(), $asap = TRUE, & $remains)
970 {
971         $remains = array();
972
973         if (! is_array($hosts)) $hosts = array($hosts);
974         foreach(array_keys($hosts) as $key) {
975                 if (! is_string($hosts[$key])) {
976                         unset($hosts[$key]);
977                 }
978         }
979         if (empty($hosts)) return $result;
980
981         $list = get_blocklist('list');
982         $blocked = blocklist_distiller($hosts, array_keys($list), $asap);
983         foreach($list as $key=>$type){
984                 if (! $type) {
985                         unset($blocked[$key]); // Ignore goodhost etc
986                 }
987         }
988         $remains = $hosts;
989
990         return $blocked;
991 }
992
993
994 // Default (enabled) methods and thresholds (for content insertion)
995 function check_uri_spam_method($times = 1, $t_area = 0, $rule = TRUE)
996 {
997         $times  = intval($times);
998         $t_area = intval($t_area);
999
1000         $positive = array(
1001                 // Thresholds
1002                 'quantity'     =>  8 * $times,  // Allow N URIs
1003                 'non_uniqhost' =>  3 * $times,  // Allow N duped (and normalized) Hosts
1004                 //'non_uniquri'=>  3 * $times,  // Allow N duped (and normalized) URIs
1005
1006                 // Areas
1007                 'area_anchor'  => $t_area,      // Using <a href> HTML tag
1008                 'area_bbcode'  => $t_area,      // Using [url] or [link] BBCode
1009                 //'uri_anchor' => $t_area,      // URI inside <a href> HTML tag
1010                 //'uri_bbcode' => $t_area,      // URI inside [url] or [link] BBCode
1011         );
1012         if ($rule) {
1013                 $bool = array(
1014                         // Rules
1015                         //'asap'   => TRUE,     // Quit or return As Soon As Possible
1016                         'uniqhost' => TRUE,     // Show uniq host (at block notification mail)
1017                         'badhost'  => TRUE,     // Check badhost
1018                 );
1019         } else {
1020                 $bool = array();
1021         }
1022
1023         // Remove non-$positive values
1024         foreach (array_keys($positive) as $key) {
1025                 if ($positive[$key] < 0) unset($positive[$key]);
1026         }
1027
1028         return $positive + $bool;
1029 }
1030
1031 // Simple/fast spam check
1032 function check_uri_spam($target = '', $method = array())
1033 {
1034         if (! is_array($method) || empty($method)) {
1035                 $method = check_uri_spam_method();
1036         }
1037         $progress = array(
1038                 'sum' => array(
1039                         'quantity'    => 0,
1040                         'uniqhost'    => 0,
1041                         'non_uniqhost'=> 0,
1042                         'non_uniquri' => 0,
1043                         'badhost'     => 0,
1044                         'area_anchor' => 0,
1045                         'area_bbcode' => 0,
1046                         'uri_anchor'  => 0,
1047                         'uri_bbcode'  => 0,
1048                 ),
1049                 'is_spam' => array(),
1050                 'method'  => & $method,
1051                 'remains' => array(),
1052                 'error'   => array(),
1053         );
1054         $sum     = & $progress['sum'];
1055         $is_spam = & $progress['is_spam'];
1056         $remains = & $progress['remains'];
1057         $error   = & $progress['error'];
1058         $asap    = isset($method['asap']);
1059
1060         // Recurse
1061         if (is_array($target)) {
1062                 foreach($target as $str) {
1063                         // Recurse
1064                         $_progress = check_uri_spam($str, $method);
1065                         $_sum      = & $_progress['sum'];
1066                         $_is_spam  = & $_progress['is_spam'];
1067                         $_remains  = & $_progress['remains'];
1068                         $_error    = & $_progress['error'];
1069                         foreach (array_keys($_sum) as $key) {
1070                                 $sum[$key] += $_sum[$key];
1071                         }
1072                         foreach (array_keys($_is_spam) as $key) {
1073                                 if (is_array($_is_spam[$key])) {
1074                                         // Marge keys (badhost)
1075                                         foreach(array_keys($_is_spam[$key]) as $_key) {
1076                                                 if (! isset($is_spam[$key][$_key])) {
1077                                                         $is_spam[$key][$_key] =  $_is_spam[$key][$_key];
1078                                                 } else {
1079                                                         $is_spam[$key][$_key] += $_is_spam[$key][$_key];
1080                                                 }
1081                                         }
1082                                 } else {
1083                                         $is_spam[$key] = TRUE;
1084                                 }
1085                         }
1086                         foreach ($_remains as $key=>$value) {
1087                                 foreach ($value as $_key=>$_value) {
1088                                         if (is_int($_key)) {
1089                                                 $remains[$key][]      = $_value;
1090                                         } else {
1091                                                 $remains[$key][$_key] = $_value;
1092                                         }
1093                                 }
1094                         }
1095                         if (! empty($_error)) $error += $_error;
1096                         if ($asap && $is_spam) break;
1097                 }
1098                 return $progress;
1099         }
1100
1101         // Area: There's HTML anchor tag
1102         if ((! $asap || ! $is_spam) && isset($method['area_anchor'])) {
1103                 $key = 'area_anchor';
1104                 $_asap = isset($method['asap']) ? array('asap' => TRUE) : array();
1105                 $result = area_pickup($target, array($key => TRUE) + $_asap);
1106                 if ($result) {
1107                         $sum[$key] = $result[$key];
1108                         if (isset($method[$key]) && $sum[$key] > $method[$key]) {
1109                                 $is_spam[$key] = TRUE;
1110                         }
1111                 }
1112         }
1113
1114         // Area: There's 'BBCode' linking tag
1115         if ((! $asap || ! $is_spam) && isset($method['area_bbcode'])) {
1116                 $key = 'area_bbcode';
1117                 $_asap = isset($method['asap']) ? array('asap' => TRUE) : array();
1118                 $result = area_pickup($target, array($key => TRUE) + $_asap);
1119                 if ($result) {
1120                         $sum[$key] = $result[$key];
1121                         if (isset($method[$key]) && $sum[$key] > $method[$key]) {
1122                                 $is_spam[$key] = TRUE;
1123                         }
1124                 }
1125         }
1126
1127         // Return if ...
1128         if ($asap && $is_spam) return $progress;
1129
1130         // URI: Pickup
1131         $pickups = uri_pickup_normalize(spam_uri_pickup($target, $method));
1132         //$remains['uri_pickup'] = & $pickups;
1133
1134         // Return if ...
1135         if (empty($pickups)) return $progress;
1136
1137         // URI: Check quantity
1138         $sum['quantity'] += count($pickups);
1139                 // URI quantity
1140         if ((! $asap || ! $is_spam) && isset($method['quantity']) &&
1141                 $sum['quantity'] > $method['quantity']) {
1142                 $is_spam['quantity'] = TRUE;
1143         }
1144
1145         // URI: used inside HTML anchor tag pair
1146         if ((! $asap || ! $is_spam) && isset($method['uri_anchor'])) {
1147                 $key = 'uri_anchor';
1148                 foreach($pickups as $pickup) {
1149                         if (isset($pickup['area'][$key])) {
1150                                 $sum[$key] += $pickup['area'][$key];
1151                                 if(isset($method[$key]) &&
1152                                         $sum[$key] > $method[$key]) {
1153                                         $is_spam[$key] = TRUE;
1154                                         if ($asap && $is_spam) break;
1155                                 }
1156                                 if ($asap && $is_spam) break;
1157                         }
1158                 }
1159         }
1160
1161         // URI: used inside 'BBCode' pair
1162         if ((! $asap || ! $is_spam) && isset($method['uri_bbcode'])) {
1163                 $key = 'uri_bbcode';
1164                 foreach($pickups as $pickup) {
1165                         if (isset($pickup['area'][$key])) {
1166                                 $sum[$key] += $pickup['area'][$key];
1167                                 if(isset($method[$key]) &&
1168                                         $sum[$key] > $method[$key]) {
1169                                         $is_spam[$key] = TRUE;
1170                                         if ($asap && $is_spam) break;
1171                                 }
1172                                 if ($asap && $is_spam) break;
1173                         }
1174                 }
1175         }
1176
1177         // URI: Uniqueness (and removing non-uniques)
1178         if ((! $asap || ! $is_spam) && isset($method['non_uniquri'])) {
1179
1180                 $uris = array();
1181                 foreach (array_keys($pickups) as $key) {
1182                         $uris[$key] = uri_pickup_implode($pickups[$key]);
1183                 }
1184                 $count = count($uris);
1185                 $uris  = array_unique($uris);
1186                 $sum['non_uniquri'] += $count - count($uris);
1187                 if ($sum['non_uniquri'] > $method['non_uniquri']) {
1188                         $is_spam['non_uniquri'] = TRUE;
1189                 }
1190                 if (! $asap || ! $is_spam) {
1191                         foreach (array_diff(array_keys($pickups),
1192                                 array_keys($uris)) as $remove) {
1193                                 unset($pickups[$remove]);
1194                         }
1195                 }
1196                 unset($uris);
1197         }
1198
1199         // Return if ...
1200         if ($asap && $is_spam) return $progress;
1201
1202         // Host: Uniqueness (uniq / non-uniq)
1203         $hosts = array();
1204         foreach ($pickups as $pickup) $hosts[] = & $pickup['host'];
1205         $hosts = array_unique($hosts);
1206         //$remains['uniqhost'] = & $hosts;
1207         $sum['uniqhost'] += count($hosts);
1208         if ((! $asap || ! $is_spam) && isset($method['non_uniqhost'])) {
1209                 $sum['non_uniqhost'] = $sum['quantity'] - $sum['uniqhost'];
1210                 if ($sum['non_uniqhost'] > $method['non_uniqhost']) {
1211                         $is_spam['non_uniqhost'] = TRUE;
1212                 }
1213         }
1214
1215         // Return if ...
1216         if ($asap && $is_spam) return $progress;
1217
1218         // URI: Bad host
1219         if ((! $asap || ! $is_spam) && isset($method['badhost'])) {
1220                 $__remains = array();
1221                 $badhost = is_badhost($hosts, $asap, $__remains);
1222                 if (! $asap) {
1223                         if ($__remains) {
1224                                 $remains['badhost'] = array();
1225                                 foreach ($__remains as $value) {
1226                                         $remains['badhost'][$value] = TRUE;
1227                                 }
1228                         }
1229                 }
1230                 unset($__remains);
1231                 if (! empty($badhost)) {
1232
1233                         //var_dump($badhost);   // BADHOST detail
1234
1235                         $sum['badhost'] += array_count_leaves($badhost);
1236                         foreach(array_keys($badhost) as $keys) {
1237                                 $is_spam['badhost'][$keys] =
1238                                         array_count_leaves($badhost[$keys]);
1239                         }
1240                         unset($badhost);
1241                 }
1242         }
1243
1244         return $progress;
1245 }
1246
1247 // Count leaves (A leaf = value that is not an array, or an empty array)
1248 function array_count_leaves($array = array(), $count_empty = FALSE)
1249 {
1250         if (! is_array($array) || (empty($array) && $count_empty)) return 1;
1251
1252         // Recurse
1253         $count = 0;
1254         foreach ($array as $part) {
1255                 $count += array_count_leaves($part, $count_empty);
1256         }
1257         return $count;
1258 }
1259
1260 // ---------------------
1261 // Reporting
1262
1263 // TODO: Don't show unused $method!
1264 // Summarize $progress (blocked only)
1265 function summarize_spam_progress($progress = array(), $blockedonly = FALSE)
1266 {
1267         if ($blockedonly) {
1268                 $tmp = array_keys($progress['is_spam']);
1269         } else {
1270                 $tmp = array();
1271                 $method = & $progress['method'];
1272                 if (isset($progress['sum'])) {
1273                         foreach ($progress['sum'] as $key => $value) {
1274                                 if (isset($method[$key])) {
1275                                         $tmp[] = $key . '(' . $value . ')';
1276                                 }
1277                         }
1278                 }
1279         }
1280
1281         return implode(', ', $tmp);
1282 }
1283
1284 // ---------------------
1285 // Exit
1286
1287 // Common bahavior for blocking
1288 // NOTE: Call this function from various blocking feature, to disgueise the reason 'why blocked'
1289 function spam_exit($mode = '', $data = array())
1290 {
1291         switch ($mode) {
1292                 case '':        echo("\n");     break;
1293                 case 'dump':
1294                         echo('<pre>' . "\n");
1295                         echo htmlspecialchars(var_export($data, TRUE));
1296                         echo('</pre>' . "\n");
1297                         break;
1298         };
1299
1300         // Force exit
1301         exit;
1302 }
1303
1304
1305 // ---------------------
1306 // Simple filtering
1307
1308 // TODO: Record them
1309 // Simple/fast spam filter ($target: 'a string' or an array())
1310 function pkwk_spamfilter($action, $page, $target = array('title' => ''), $method = array(), $exitmode = '')
1311 {
1312         $progress = check_uri_spam($target, $method);
1313
1314         if (! empty($progress['is_spam'])) {
1315                 // Mail to administrator(s)
1316                 pkwk_spamnotify($action, $page, $target, $progress, $method);
1317
1318                 // Exit
1319                 spam_exit($exitmode, $progress);
1320         }
1321 }
1322
1323 // ---------------------
1324 // PukiWiki original
1325
1326 // Mail to administrator(s)
1327 function pkwk_spamnotify($action, $page, $target = array('title' => ''), $progress = array(), $method = array())
1328 {
1329         global $notify, $notify_subject;
1330
1331         if (! $notify) return;
1332
1333         $asap = isset($method['asap']);
1334
1335         $summary['ACTION']  = 'Blocked by: ' . summarize_spam_progress($progress, TRUE);
1336         if (! $asap) {
1337                 $summary['METRICS'] = summarize_spam_progress($progress);
1338         }
1339         if (isset($progress['is_spam']['badhost'])) {
1340                 $badhost = array();
1341                 foreach($progress['is_spam']['badhost'] as $glob=>$number) {
1342                         $badhost[] = $glob . '(' . $number . ')';
1343                 }
1344                 $summary['DETAIL_BADHOST'] = implode(', ', $badhost);
1345         }
1346         if (! $asap && $progress['remains']['badhost']) {
1347                 $count = count($progress['remains']['badhost']);
1348                 $summary['DETAIL_NEUTRAL_HOST'] = $count .
1349                         ' (' .
1350                                 preg_replace(
1351                                         '/[^, a-z0-9.-]/i', '',
1352                                         implode(', ', array_keys($progress['remains']['badhost']))
1353                                 ) .
1354                         ')';
1355         }
1356         $summary['COMMENT'] = $action;
1357         $summary['PAGE']    = '[blocked] ' . (is_pagename($page) ? $page : '');
1358         $summary['URI']     = get_script_uri() . '?' . rawurlencode($page);
1359         $summary['USER_AGENT']  = TRUE;
1360         $summary['REMOTE_ADDR'] = TRUE;
1361         pkwk_mail_notify($notify_subject,  var_export($target, TRUE), $summary, TRUE);
1362 }
1363
1364 ?>