OSDN Git Service

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