OSDN Git Service

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