OSDN Git Service

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