OSDN Git Service

* Added spam_uri_removing_hocus_pocus().
[pukiwiki/pukiwiki_sandbox.git] / spam / spam.php
1 <?php
2 // $Id: spam.php,v 1.179 2007/06/16 03:39:39 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
42 // Very roughly, shrink the lines of var_export()
43 // NOTE: If the same data exists, it must be corrupted.
44 function var_export_shrink($expression, $return = FALSE, $ignore_numeric_keys = FALSE)
45 {
46         $result = var_export($expression, TRUE);
47
48         $result = preg_replace(
49                 // Remove a newline and spaces
50                 '# => \n *array \(#', ' => array (',
51                 $result
52         );
53
54         if ($ignore_numeric_keys) {
55                 $result =preg_replace(
56                         // Remove numeric keys
57                         '#^( *)[0-9]+ => #m', '$1',
58                         $result
59                 );
60         }
61
62         if ($return) {
63                 return $result;
64         } else {
65                 echo   $result;
66                 return NULL;
67         }
68 }
69
70 // Remove redundant values from array()
71 function array_unique_recursive($array = array())
72 {
73         if (! is_array($array)) return $array;
74
75         $tmp = array();
76         foreach($array as $key => $value){
77                 if (is_array($value)) {
78                         $array[$key] = array_unique_recursive($value);
79                 } else {
80                         if (isset($tmp[$value])) {
81                                 unset($array[$key]);
82                         } else {
83                                 $tmp[$value] = TRUE;
84                         }
85                 }
86         }
87
88         return $array;
89 }
90
91 // Renumber all numeric keys from 0
92 function array_renumber_numeric_keys(& $array)
93 {
94         if (! is_array($array)) return $array;
95
96         $count = -1;
97         $tmp = array();
98         foreach($array as $key => $value){
99                 if (is_array($value)) array_renumber_numeric_keys($array[$key]);        // Recurse
100                 if (is_numeric($key)) $tmp[$key] = ++$count;
101         }
102         array_rename_keys($array, $tmp);
103
104         return $array;
105 }
106
107 // Roughly strings(1) using PCRE
108 // This function is useful to:
109 //   * Reduce the size of data, from removing unprintable binary data
110 //   * Detect _bare_strings_ from binary data
111 // References:
112 //   http://www.freebsd.org/cgi/man.cgi?query=strings (Man-page of GNU strings)
113 //   http://www.pcre.org/pcre.txt
114 function strings($binary = '', $min_len = 4, $ignore_space = FALSE, $multibyte = TRUE)
115 {
116         // String only
117         $binary = (is_array($binary) || $binary === TRUE) ? '' : strval($binary);
118
119         $regex = $ignore_space ?
120                 '[^[:graph:] \t\n]+' :          // Remove "\0" etc, and readable spaces
121                 '[^[:graph:][:space:]]+';       // Preserve readable spaces if possible
122
123         $binary = $multibyte ?
124                 mb_ereg_replace($regex,           "\n",  $binary) :
125                 preg_replace('/' . $regex . '/s', "\n",  $binary);
126
127         if ($ignore_space) {
128                 $binary = preg_replace(
129                         array(
130                                 '/[ \t]{2,}/',
131                                 '/^[ \t]/m',
132                                 '/[ \t]$/m',
133                         ),
134                         array(
135                                 ' ',
136                                 '',
137                                 ''
138                         ),
139                          $binary);
140         }
141
142         if ($min_len > 1) {
143                 // The last character seems "\n" or not
144                 $br = (! empty($binary) && $binary[strlen($binary) - 1] == "\n") ? "\n" : '';
145
146                 $min_len = min(1024, intval($min_len));
147                 $regex = '/^.{' . $min_len . ',}/S';
148                 $binary = implode("\n", preg_grep($regex, explode("\n", $binary))) . $br;
149         }
150
151         return $binary;
152 }
153
154 // Reverse $string with specified delimiter
155 function delimiter_reverse($string = 'foo.bar.example.com', $from_delim = '.', $to_delim = '.')
156 {
157         if (! is_string($string) || ! is_string($from_delim) || ! is_string($to_delim))
158                 return $string;
159
160         // com.example.bar.foo
161         return implode($to_delim, array_reverse(explode($from_delim, $string)));
162 }
163
164
165 // ---------------------
166 // URI pickup
167
168 // Return an array of URIs in the $string
169 // [OK] http://nasty.example.org#nasty_string
170 // [OK] http://nasty.example.org:80/foo/xxx#nasty_string/bar
171 // [OK] ftp://nasty.example.org:80/dfsdfs
172 // [OK] ftp://cnn.example.com&story=breaking_news@10.0.0.1/top_story.htm (from RFC3986)
173 function uri_pickup($string = '')
174 {
175         if (! is_string($string)) return array();
176
177         // Not available for: IDN(ignored)
178         $array = array();
179         preg_match_all(
180                 // scheme://userinfo@host:port/path/or/pathinfo/maybefile.and?query=string#fragment
181                 // Refer RFC3986 (Regex below is not strict)
182                 '#(\b[a-z][a-z0-9.+-]{1,8}):[/\\\]+' .  // 1: Scheme
183                 '(?:' .
184                         '([^\s<>"\'\[\]/\#?@]*)' .              // 2: Userinfo (Username)
185                 '@)?' .
186                 '(' .
187                         // 3: Host
188                         '\[[0-9a-f:.]+\]' . '|' .                               // IPv6([colon-hex and dot]): RFC2732
189                         '(?:[0-9]{1,3}\.){3}[0-9]{1,3}' . '|' . // IPv4(dot-decimal): 001.22.3.44
190                         '[a-z0-9][a-z0-9.-]+[a-z0-9]' .                 // hostname(FQDN) : foo.example.org
191                 ')' .
192                 '(?::([0-9]*))?' .                                      // 4: Port
193                 '((?:/+[^\s<>"\'\[\]/\#]+)*/+)?' .      // 5: Directory path or path-info
194                 '([^\s<>"\'\[\]\#?]+)?' .                       // 6: File?
195                 '(?:\?([^\s<>"\'\[\]\#]+))?' .          // 7: Query string
196                 '(?:\#([a-z0-9._~%!$&\'()*+,;=:@-]*))?' .       // 8: Fragment
197                 '#i',
198                  $string, $array, PREG_SET_ORDER | PREG_OFFSET_CAPTURE
199         );
200
201         // Format the $array
202         static $parts = array(
203                 1 => 'scheme', 2 => 'userinfo', 3 => 'host', 4 => 'port',
204                 5 => 'path', 6 => 'file', 7 => 'query', 8 => 'fragment'
205         );
206         $default = array('');
207         foreach(array_keys($array) as $uri) {
208                 $_uri = & $array[$uri];
209                 array_rename_keys($_uri, $parts, TRUE, $default);
210                 $offset = $_uri['scheme'][1]; // Scheme's offset = URI's offset
211                 foreach(array_keys($_uri) as $part) {
212                         $_uri[$part] = & $_uri[$part][0];       // Remove offsets
213                 }
214         }
215
216         foreach(array_keys($array) as $uri) {
217                 $_uri = & $array[$uri];
218                 if ($_uri['scheme'] === '') {
219                         unset($array[$uri]);    // Considererd harmless
220                         continue;
221                 }
222                 unset($_uri[0]); // Matched string itself
223                 $_uri['area']['offset'] = $offset;      // Area offset for area_measure()
224         }
225
226         return $array;
227 }
228
229 // Normalize an array of URI arrays
230 // NOTE: Give me the uri_pickup() results
231 function uri_pickup_normalize(& $pickups, $destructive = TRUE)
232 {
233         if (! is_array($pickups)) return $pickups;
234
235         if ($destructive) {
236                 foreach (array_keys($pickups) as $key) {
237                         $_key = & $pickups[$key];
238                         $_key['scheme']   = isset($_key['scheme']) ? scheme_normalize($_key['scheme']) : '';
239                         $_key['host']     = isset($_key['host'])     ? host_normalize($_key['host']) : '';
240                         $_key['port']     = isset($_key['port'])       ? port_normalize($_key['port'], $_key['scheme'], FALSE) : '';
241                         $_key['path']     = isset($_key['path'])     ? strtolower(path_normalize($_key['path'])) : '';
242                         $_key['file']     = isset($_key['file'])     ? file_normalize($_key['file']) : '';
243                         $_key['query']    = isset($_key['query'])    ? query_normalize($_key['query']) : '';
244                         $_key['fragment'] = isset($_key['fragment']) ? strtolower($_key['fragment']) : '';
245                 }
246         } else {
247                 foreach (array_keys($pickups) as $key) {
248                         $_key = & $pickups[$key];
249                         $_key['scheme']   = isset($_key['scheme']) ? scheme_normalize($_key['scheme']) : '';
250                         $_key['host']     = isset($_key['host'])   ? strtolower($_key['host']) : '';
251                         $_key['port']     = isset($_key['port'])   ? port_normalize($_key['port'], $_key['scheme'], FALSE) : '';
252                         $_key['path']     = isset($_key['path'])   ? path_normalize($_key['path']) : '';
253                 }
254         }
255
256         return $pickups;
257 }
258
259 // An URI array => An URI (See uri_pickup())
260 // USAGE:
261 //      $pickups = uri_pickup('a string include some URIs');
262 //      $uris = array();
263 //      foreach (array_keys($pickups) as $key) {
264 //              $uris[$key] = uri_pickup_implode($pickups[$key]);
265 //      }
266 function uri_pickup_implode($uri = array())
267 {
268         if (empty($uri) || ! is_array($uri)) return NULL;
269
270         $tmp = array();
271         if (isset($uri['scheme']) && $uri['scheme'] !== '') {
272                 $tmp[] = & $uri['scheme'];
273                 $tmp[] = '://';
274         }
275         if (isset($uri['userinfo']) && $uri['userinfo'] !== '') {
276                 $tmp[] = & $uri['userinfo'];
277                 $tmp[] = '@';
278         }
279         if (isset($uri['host']) && $uri['host'] !== '') {
280                 $tmp[] = & $uri['host'];
281         }
282         if (isset($uri['port']) && $uri['port'] !== '') {
283                 $tmp[] = ':';
284                 $tmp[] = & $uri['port'];
285         }
286         if (isset($uri['path']) && $uri['path'] !== '') {
287                 $tmp[] = & $uri['path'];
288         }
289         if (isset($uri['file']) && $uri['file'] !== '') {
290                 $tmp[] = & $uri['file'];
291         }
292         if (isset($uri['query']) && $uri['query'] !== '') {
293                 $tmp[] = '?';
294                 $tmp[] = & $uri['query'];
295         }
296         if (isset($uri['fragment']) && $uri['fragment'] !== '') {
297                 $tmp[] = '#';
298                 $tmp[] = & $uri['fragment'];
299         }
300
301         return implode('', $tmp);
302 }
303
304 // $array['something'] => $array['wanted']
305 function array_rename_keys(& $array, $keys = array('from' => 'to'), $force = FALSE, $default = '')
306 {
307         if (! is_array($array) || ! is_array($keys)) return FALSE;
308
309         // Nondestructive test
310         if (! $force)
311                 foreach(array_keys($keys) as $from)
312                         if (! isset($array[$from]))
313                                 return FALSE;
314
315         foreach($keys as $from => $to) {
316                 if ($from === $to) continue;
317                 if (! $force || isset($array[$from])) {
318                         $array[$to] = & $array[$from];
319                         unset($array[$from]);
320                 } else  {
321                         $array[$to] = $default;
322                 }
323         }
324
325         return TRUE;
326 }
327
328 // ---------------------
329 // Area pickup
330
331 // Pickup all of markup areas
332 function area_pickup($string = '', $method = array())
333 {
334         $area = array();
335         if (empty($method)) return $area;
336
337         // Anchor tag pair by preg_match and preg_match_all()
338         // [OK] <a href></a>
339         // [OK] <a href=  >Good site!</a>
340         // [OK] <a href= "#" >test</a>
341         // [OK] <a href="http://nasty.example.com">visit http://nasty.example.com/</a>
342         // [OK] <a href=\'http://nasty.example.com/\' >discount foobar</a> 
343         // [NG] <a href="http://ng.example.com">visit http://ng.example.com _not_ended_
344         $regex = '#<a\b[^>]*\bhref\b[^>]*>.*?</a\b[^>]*(>)#is';
345         if (isset($method['area_anchor'])) {
346                 $areas = array();
347                 $count = isset($method['asap']) ?
348                         preg_match($regex, $string) :
349                         preg_match_all($regex, $string, $areas);
350                 if (! empty($count)) $area['area_anchor'] = $count;
351         }
352         if (isset($method['uri_anchor'])) {
353                 $areas = array();
354                 preg_match_all($regex, $string, $areas, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
355                 foreach(array_keys($areas) as $_area) {
356                         $areas[$_area] =  array(
357                                 $areas[$_area][0][1], // Area start (<a href>)
358                                 $areas[$_area][1][1], // Area end   (</a>)
359                         );
360                 }
361                 if (! empty($areas)) $area['uri_anchor'] = $areas;
362         }
363
364         // phpBB's "BBCode" pair by preg_match and preg_match_all()
365         // [OK] [url][/url]
366         // [OK] [url]http://nasty.example.com/[/url]
367         // [OK] [link]http://nasty.example.com/[/link]
368         // [OK] [url=http://nasty.example.com]visit http://nasty.example.com/[/url]
369         // [OK] [link http://nasty.example.com/]buy something[/link]
370         $regex = '#\[(url|link)\b[^\]]*\].*?\[/\1\b[^\]]*(\])#is';
371         if (isset($method['area_bbcode'])) {
372                 $areas = array();
373                 $count = isset($method['asap']) ?
374                         preg_match($regex, $string) :
375                         preg_match_all($regex, $string, $areas, PREG_SET_ORDER);
376                 if (! empty($count)) $area['area_bbcode'] = $count;
377         }
378         if (isset($method['uri_bbcode'])) {
379                 $areas = array();
380                 preg_match_all($regex, $string, $areas, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
381                 foreach(array_keys($areas) as $_area) {
382                         $areas[$_area] = array(
383                                 $areas[$_area][0][1], // Area start ([url])
384                                 $areas[$_area][2][1], // Area end   ([/url])
385                         );
386                 }
387                 if (! empty($areas)) $area['uri_bbcode'] = $areas;
388         }
389
390         // Various Wiki syntax
391         // [text_or_uri>text_or_uri]
392         // [text_or_uri:text_or_uri]
393         // [text_or_uri|text_or_uri]
394         // [text_or_uri->text_or_uri]
395         // [text_or_uri text_or_uri] // MediaWiki
396         // MediaWiki: [http://nasty.example.com/ visit http://nasty.example.com/]
397
398         return $area;
399 }
400
401 // If in doubt, it's a little doubtful
402 // if (Area => inside <= Area) $brief += -1
403 function area_measure($areas, & $array, $belief = -1, $a_key = 'area', $o_key = 'offset')
404 {
405         if (! is_array($areas) || ! is_array($array)) return;
406
407         $areas_keys = array_keys($areas);
408         foreach(array_keys($array) as $u_index) {
409                 $offset = isset($array[$u_index][$o_key]) ?
410                         intval($array[$u_index][$o_key]) : 0;
411                 foreach($areas_keys as $a_index) {
412                         if (isset($array[$u_index][$a_key])) {
413                                 $offset_s = intval($areas[$a_index][0]);
414                                 $offset_e = intval($areas[$a_index][1]);
415                                 // [Area => inside <= Area]
416                                 if ($offset_s < $offset && $offset < $offset_e) {
417                                         $array[$u_index][$a_key] += $belief;
418                                 }
419                         }
420                 }
421         }
422 }
423
424 // ---------------------
425 // Spam-uri pickup
426
427 // Domain exposure callback (See spam_uri_pickup_preprocess())
428 // http://victim.example.org/?foo+site:nasty.example.com+bar
429 // => http://nasty.example.com/?refer=victim.example.org
430 // NOTE: 'refer=' is not so good for (at this time).
431 // Consider about using IP address of the victim, try to avoid that.
432 function _preg_replace_callback_domain_exposure($matches = array())
433 {
434         $result = '';
435
436         // Preserve the victim URI as a complicity or ...
437         if (isset($matches[5])) {
438                 $result =
439                         $matches[1] . '://' .   // scheme
440                         $matches[2] . '/' .             // victim.example.org
441                         $matches[3];                    // The rest of all (before victim)
442         }
443
444         // Flipped URI
445         if (isset($matches[4])) {
446                 $result = 
447                         $matches[1] . '://' .   // scheme
448                         $matches[4] .                   // nasty.example.com
449                         '/?refer=' . strtolower($matches[2]) .  // victim.example.org
450                         ' ' . $result;
451         }
452
453         return $result;
454 }
455
456 // Preprocess: Removing uninterest part for URI detection
457 function spam_uri_removing_hocus_pocus($binary = '', $method = array())
458 {
459         $length = 4 ; // 'http'(1) and '://'(2) and 'fqdn'(1)
460         if (is_array($method)) {
461                 // '<a'(2) or 'href='(5) or '>'(1) or '</a>'(4)
462                 // '[uri'(4) or ']'(1) or '[/uri]'(6) 
463                 if (isset($method['area_anchor']) || isset($method['uri_anchor']) ||
464                     isset($method['area_bbcode']) || isset($method['uri_bbcode']))
465                                 $length = 1;    // Seems not effective
466         }
467
468         // Removing sequential spaces and too short lines
469         $binary = strings($binary, $length, TRUE, TRUE);
470
471         // Remove words (has no '<>[]:') between spaces
472         $binary = preg_replace('/[ \t][\w.,()\ \t]+[ \t]/', ' ', $binary);
473
474         return $binary;
475 }
476
477 // Preprocess: rawurldecode() and adding space(s) and something
478 // to detect/count some URIs _if possible_
479 // NOTE: It's maybe danger to var_dump(result). [e.g. 'javascript:']
480 // [OK] http://victim.example.org/?site:nasty.example.org
481 // [OK] http://victim.example.org/nasty.example.org
482 // [OK] http://victim.example.org/go?http%3A%2F%2Fnasty.example.org
483 // [OK] http://victim.example.org/http://nasty.example.org
484 function spam_uri_pickup_preprocess($string = '', $method = array())
485 {
486         if (! is_string($string)) return '';
487
488         $string = spam_uri_removing_hocus_pocus(rawurldecode($string), $method);
489         //var_dump(htmlspecialchars($string));
490
491         // Domain exposure (simple)
492         // http://victim.example.org/nasty.example.org/path#frag
493         // => http://nasty.example.org/?refer=victim.example.org and original
494         $string = preg_replace(
495                 '#h?ttp://' .
496                 '(' .
497                         'ime\.nu' . '|' .       // 2ch.net
498                         'ime\.st' . '|' .       // 2ch.net
499                         'link\.toolbot\.com' . '|' .
500                         'urlx\.org' .
501                 ')' .
502                 '/([a-z0-9.%_-]+\.[a-z0-9.%_-]+)#i',    // nasty.example.org
503                 'http://$2/?refer=$1 $0',                               // Preserve $0 or remove?
504                 $string
505         );
506
507         // Domain exposure (gate-big5)
508         // http://victim.example.org/gate/big5/nasty.example.org/path
509         // => http://nasty.example.org/?refer=victim.example.org and original
510         $string = preg_replace(
511                 '#h?ttp://' .
512                 '(' .
513                         'big5.51job.com'         . '|' .
514                         'big5.china.com'         . '|' .
515                         'big5.xinhuanet.com' . '|' .
516                 ')' .
517                 '/gate/big5' .
518                 '/([a-z0-9.%_-]+\.[a-z0-9.%_-]+)' .
519                  '#i',  // nasty.example.org
520                 'http://$2/?refer=$1 $0',                               // Preserve $0 or remove?
521                 $string
522         );
523
524         // Domain exposure (See _preg_replace_callback_domain_exposure())
525         $string = preg_replace_callback(
526                 array(
527                         '#(http)://' .
528                         '(' .
529                                 // Something Google: http://www.google.com/supported_domains
530                                 '(?:[a-z0-9.]+\.)?google\.[a-z]{2,3}(?:\.[a-z]{2})?' .
531                                 '|' .
532                                 // AltaVista
533                                 '(?:[a-z0-9.]+\.)?altavista.com' .
534                                 
535                         ')' .
536                         '/' .
537                         '([a-z0-9?=&.%_/\'\\\+-]+)' .                           // path/?query=foo+bar+
538                         '\bsite:([a-z0-9.%_-]+\.[a-z0-9.%_-]+)' .       // site:nasty.example.com
539                         //'()' .        // Preserve or remove?
540                         '#i',
541                 ),
542                 '_preg_replace_callback_domain_exposure',
543                 $string
544         );
545
546         // URI exposure (uriuri => uri uri)
547         $string = preg_replace(
548                 array(
549                         '#(?<! )(?:https?|ftp):/#i',
550                 //      '#[a-z][a-z0-9.+-]{1,8}://#i',
551                 //      '#[a-z][a-z0-9.+-]{1,8}://#i'
552                 ),
553                 ' $0',
554                 $string
555         );
556
557         return $string;
558 }
559
560 // Main function of spam-uri pickup,
561 // A wrapper function of uri_pickup()
562 function spam_uri_pickup($string = '', $method = array())
563 {
564         if (! is_array($method) || empty($method)) {
565                 $method = check_uri_spam_method();
566         }
567
568         $string = spam_uri_pickup_preprocess($string, $method);
569
570         $array  = uri_pickup($string);
571
572         // Area elevation of URIs, for '(especially external)link' intension
573         if (! empty($array)) {
574                 $_method = array();
575                 if (isset($method['uri_anchor'])) $_method['uri_anchor'] = & $method['uri_anchor'];
576                 if (isset($method['uri_bbcode'])) $_method['uri_bbcode'] = & $method['uri_bbcode'];
577                 $areas = area_pickup($string, $_method, TRUE);
578                 if (! empty($areas)) {
579                         $area_shadow = array();
580                         foreach (array_keys($array) as $key) {
581                                 $area_shadow[$key] = & $array[$key]['area'];
582                                 foreach (array_keys($_method) as $_key) {
583                                         $area_shadow[$key][$_key] = 0;
584                                 }
585                         }
586                         foreach (array_keys($_method) as $_key) {
587                                 if (isset($areas[$_key])) {
588                                         area_measure($areas[$_key], $area_shadow, 1, $_key);
589                                 }
590                         }
591                 }
592         }
593
594         // Remove 'offset's for area_measure()
595         foreach(array_keys($array) as $key)
596                 unset($array[$key]['area']['offset']);
597
598         return $array;
599 }
600
601
602 // ---------------------
603 // Normalization
604
605 // Scheme normalization: Renaming the schemes
606 // snntp://example.org =>  nntps://example.org
607 // NOTE: Keep the static lists simple. See also port_normalize().
608 function scheme_normalize($scheme = '', $abbrevs_harmfull = TRUE)
609 {
610         // Abbreviations they have no intention of link
611         static $abbrevs = array(
612                 'ttp'   => 'http',
613                 'ttps'  => 'https',
614         );
615
616         // Aliases => normalized ones
617         static $aliases = array(
618                 'pop'   => 'pop3',
619                 'news'  => 'nntp',
620                 'imap4' => 'imap',
621                 'snntp' => 'nntps',
622                 'snews' => 'nntps',
623                 'spop3' => 'pop3s',
624                 'pops'  => 'pop3s',
625         );
626
627         if (! is_string($scheme)) return '';
628
629         $scheme = strtolower($scheme);
630         if (isset($abbrevs[$scheme])) {
631                 $scheme = $abbrevs_harmfull ? $abbrevs[$scheme] : '';
632         }
633         if (isset($aliases[$scheme])) {
634                 $scheme = $aliases[$scheme];
635         }
636
637         return $scheme;
638 }
639
640 // Hostname normlization (Destructive)
641 // www.foo     => www.foo   ('foo' seems TLD)
642 // www.foo.bar => foo.bar
643 // www.10.20   => www.10.20 (Invalid hostname)
644 // NOTE:
645 //   'www' is  mostly used as traditional hostname of WWW server.
646 //   'www.foo.bar' may be identical with 'foo.bar'.
647 function host_normalize($host = '')
648 {
649         if (! is_string($host)) return '';
650
651         $host = strtolower($host);
652         $matches = array();
653         if (preg_match('/^www\.(.+\.[a-z]+)$/', $host, $matches)) {
654                 return $matches[1];
655         } else {
656                 return $host;
657         }
658 }
659
660 // Port normalization: Suppress the (redundant) default port
661 // HTTP://example.org:80/ => http://example.org/
662 // HTTP://example.org:8080/ => http://example.org:8080/
663 // HTTPS://example.org:443/ => https://example.org/
664 function port_normalize($port, $scheme, $scheme_normalize = FALSE)
665 {
666         // Schemes that users _maybe_ want to add protocol-handlers
667         // to their web browsers. (and attackers _maybe_ want to use ...)
668         // Reference: http://www.iana.org/assignments/port-numbers
669         static $array = array(
670                 // scheme => default port
671                 'ftp'     =>    21,
672                 'ssh'     =>    22,
673                 'telnet'  =>    23,
674                 'smtp'    =>    25,
675                 'tftp'    =>    69,
676                 'gopher'  =>    70,
677                 'finger'  =>    79,
678                 'http'    =>    80,
679                 'pop3'    =>   110,
680                 'sftp'    =>   115,
681                 'nntp'    =>   119,
682                 'imap'    =>   143,
683                 'irc'     =>   194,
684                 'wais'    =>   210,
685                 'https'   =>   443,
686                 'nntps'   =>   563,
687                 'rsync'   =>   873,
688                 'ftps'    =>   990,
689                 'telnets' =>   992,
690                 'imaps'   =>   993,
691                 'ircs'    =>   994,
692                 'pop3s'   =>   995,
693                 'mysql'   =>  3306,
694         );
695
696         // intval() converts '0-1' to '0', so preg_match() rejects these invalid ones
697         if (! is_numeric($port) || $port < 0 || preg_match('/[^0-9]/i', $port))
698                 return '';
699
700         $port = intval($port);
701         if ($scheme_normalize) $scheme = scheme_normalize($scheme);
702         if (isset($array[$scheme]) && $port == $array[$scheme])
703                 $port = ''; // Ignore the defaults
704
705         return $port;
706 }
707
708 // Path normalization
709 // http://example.org => http://example.org/
710 // http://example.org#hoge => http://example.org/#hoge
711 // http://example.org/path/a/b/./c////./d => http://example.org/path/a/b/c/d
712 // http://example.org/path/../../a/../back => http://example.org/back
713 function path_normalize($path = '', $divider = '/', $add_root = TRUE)
714 {
715         if (! is_string($divider)) return is_string($path) ? $path : '';
716
717         if ($add_root) {
718                 $first_div = & $divider;
719         } else {
720                 $first_div = '';
721         }
722         if (! is_string($path) || $path == '') return $first_div;
723
724         if (strpos($path, $divider, strlen($path) - strlen($divider)) === FALSE) {
725                 $last_div = '';
726         } else {
727                 $last_div = & $divider;
728         }
729
730         $array = explode($divider, $path);
731
732         // Remove paddings ('//' and '/./')
733         foreach(array_keys($array) as $key) {
734                 if ($array[$key] == '' || $array[$key] == '.') {
735                          unset($array[$key]);
736                 }
737         }
738
739         // Remove back-tracks ('/../')
740         $tmp = array();
741         foreach($array as $value) {
742                 if ($value == '..') {
743                         array_pop($tmp);
744                 } else {
745                         array_push($tmp, $value);
746                 }
747         }
748         $array = & $tmp;
749
750         if (empty($array)) {
751                 return $first_div;
752         } else {
753                 return $first_div . implode($divider, $array) . $last_div;
754         }
755 }
756
757 // DirectoryIndex normalize (Destructive and rough)
758 // TODO: sample.en.ja.html.gz => sample.html
759 function file_normalize($file = 'index.html.en')
760 {
761         static $simple_defaults = array(
762                 'default.htm'   => TRUE,
763                 'default.html'  => TRUE,
764                 'default.asp'   => TRUE,
765                 'default.aspx'  => TRUE,
766                 'index'                 => TRUE,        // Some system can omit the suffix
767         );
768
769         static $content_suffix = array(
770                 // index.xxx, sample.xxx
771                 'htm'   => TRUE,
772                 'html'  => TRUE,
773                 'shtml' => TRUE,
774                 'jsp'   => TRUE,
775                 'php'   => TRUE,
776                 'php3'  => TRUE,
777                 'php4'  => TRUE,
778                 'pl'    => TRUE,
779                 'py'    => TRUE,
780                 'rb'    => TRUE,
781                 'cgi'   => TRUE,
782                 'xml'   => TRUE,
783         );
784
785         static $language_suffix = array(
786                 // Reference: Apache 2.0.59 'AddLanguage' default
787                 'ca'    => TRUE,
788                 'cs'    => TRUE,        // cs
789                 'cz'    => TRUE,        // cs
790                 'de'    => TRUE,
791                 'dk'    => TRUE,        // da
792                 'el'    => TRUE,
793                 'en'    => TRUE,
794                 'eo'    => TRUE,
795                 'es'    => TRUE,
796                 'et'    => TRUE,
797                 'fr'    => TRUE,
798                 'he'    => TRUE,
799                 'hr'    => TRUE,
800                 'it'    => TRUE,
801                 'ja'    => TRUE,
802                 'ko'    => TRUE,
803                 'ltz'   => TRUE,
804                 'nl'    => TRUE,
805                 'nn'    => TRUE,
806                 'no'    => TRUE,
807                 'po'    => TRUE,
808                 'pt'    => TRUE,
809                 'pt-br' => TRUE,
810                 'ru'    => TRUE,
811                 'sv'    => TRUE,
812                 'zh-cn' => TRUE,
813                 'zh-tw' => TRUE,
814
815                 // Reference: Apache 2.0.59 default 'index.html' variants
816                 'ee'    => TRUE,
817                 'lb'    => TRUE,
818                 'var'   => TRUE,
819         );
820
821         static $charset_suffix = array(
822                 // Reference: Apache 2.0.59 'AddCharset' default
823                 'iso8859-1'     => TRUE, // ISO-8859-1
824                 'latin1'        => TRUE, // ISO-8859-1
825                 'iso8859-2'     => TRUE, // ISO-8859-2
826                 'latin2'        => TRUE, // ISO-8859-2
827                 'cen'           => TRUE, // ISO-8859-2
828                 'iso8859-3'     => TRUE, // ISO-8859-3
829                 'latin3'        => TRUE, // ISO-8859-3
830                 'iso8859-4'     => TRUE, // ISO-8859-4
831                 'latin4'        => TRUE, // ISO-8859-4
832                 'iso8859-5'     => TRUE, // ISO-8859-5
833                 'latin5'        => TRUE, // ISO-8859-5
834                 'cyr'           => TRUE, // ISO-8859-5
835                 'iso-ru'        => TRUE, // ISO-8859-5
836                 'iso8859-6'     => TRUE, // ISO-8859-6
837                 'latin6'        => TRUE, // ISO-8859-6
838                 'arb'           => TRUE, // ISO-8859-6
839                 'iso8859-7'     => TRUE, // ISO-8859-7
840                 'latin7'        => TRUE, // ISO-8859-7
841                 'grk'           => TRUE, // ISO-8859-7
842                 'iso8859-8'     => TRUE, // ISO-8859-8
843                 'latin8'        => TRUE, // ISO-8859-8
844                 'heb'           => TRUE, // ISO-8859-8
845                 'iso8859-9'     => TRUE, // ISO-8859-9
846                 'latin9'        => TRUE, // ISO-8859-9
847                 'trk'           => TRUE, // ISO-8859-9
848                 'iso2022-jp'=> TRUE, // ISO-2022-JP
849                 'jis'           => TRUE, // ISO-2022-JP
850                 'iso2022-kr'=> TRUE, // ISO-2022-KR
851                 'kis'           => TRUE, // ISO-2022-KR
852                 'iso2022-cn'=> TRUE, // ISO-2022-CN
853                 'cis'           => TRUE, // ISO-2022-CN
854                 'big5'          => TRUE,
855                 'cp-1251'       => TRUE, // ru, WINDOWS-1251
856                 'win-1251'      => TRUE, // ru, WINDOWS-1251
857                 'cp866'         => TRUE, // ru
858                 'koi8-r'        => TRUE, // ru, KOI8-r
859                 'koi8-ru'       => TRUE, // ru, KOI8-r
860                 'koi8-uk'       => TRUE, // ru, KOI8-ru
861                 'ua'            => TRUE, // ru, KOI8-ru
862                 'ucs2'          => TRUE, // ru, ISO-10646-UCS-2
863                 'ucs4'          => TRUE, // ru, ISO-10646-UCS-4
864                 'utf8'          => TRUE,
865
866                 // Reference: Apache 2.0.59 default 'index.html' variants
867                 'euc-kr'        => TRUE,
868                 'gb2312'        => TRUE,
869         );
870
871         // May uncompress by web browsers on the fly
872         // Must be at the last of the filename
873         // Reference: Apache 2.0.59 'AddEncoding'
874         static $encoding_suffix = array(
875                 'z'             => TRUE,
876                 'gz'    => TRUE,
877         );
878
879         if (! is_string($file)) return '';
880         $_file = strtolower($file);
881         if (isset($simple_defaults[$_file])) return '';
882
883
884         // Roughly removing language/character-set/encoding suffixes
885         // References:
886         //  * Apache 2 document about 'Content-negotiaton', 'mod_mime' and 'mod_negotiation'
887         //    http://httpd.apache.org/docs/2.0/content-negotiation.html
888         //    http://httpd.apache.org/docs/2.0/mod/mod_mime.html
889         //    http://httpd.apache.org/docs/2.0/mod/mod_negotiation.html
890         //  * http://www.iana.org/assignments/character-sets
891         //  * RFC3066: Tags for the Identification of Languages
892         //    http://www.ietf.org/rfc/rfc3066.txt
893         //  * ISO 639: codes of 'language names'
894         $suffixes = explode('.', $_file);
895         $body = array_shift($suffixes);
896         if ($suffixes) {
897                 // Remove the last .gz/.z
898                 $last_key = end(array_keys($suffixes));
899                 if (isset($encoding_suffix[$suffixes[$last_key]])) {
900                         unset($suffixes[$last_key]);
901                 }
902         }
903         // Cut language and charset suffixes
904         foreach($suffixes as $key => $value){
905                 if (isset($language_suffix[$value]) || isset($charset_suffix[$value])) {
906                         unset($suffixes[$key]);
907                 }
908         }
909         if (empty($suffixes)) return $body;
910
911         // Index.xxx
912         $count = count($suffixes);
913         reset($suffixes);
914         $current = current($suffixes);
915         if ($body == 'index' && $count == 1 && isset($content_suffix[$current])) return '';
916
917         return $file;
918 }
919
920 // Sort query-strings if possible (Destructive and rough)
921 // [OK] &&&&f=d&b&d&c&a=0dd  =>  a=0dd&b&c&d&f=d
922 // [OK] nothing==&eg=dummy&eg=padding&eg=foobar  =>  eg=foobar
923 function query_normalize($string = '', $equal = TRUE, $equal_cutempty = TRUE, $stortolower = TRUE)
924 {
925         if (! is_string($string)) return '';
926         if ($stortolower) $string = strtolower($string);
927
928         $array = explode('&', $string);
929
930         // Remove '&' paddings
931         foreach(array_keys($array) as $key) {
932                 if ($array[$key] == '') {
933                          unset($array[$key]);
934                 }
935         }
936
937         // Consider '='-sepalated input and paddings
938         if ($equal) {
939                 $equals = $not_equals = array();
940                 foreach ($array as $part) {
941                         if (strpos($part, '=') === FALSE) {
942                                  $not_equals[] = $part;
943                         } else {
944                                 list($key, $value) = explode('=', $part, 2);
945                                 $value = ltrim($value, '=');
946                                 if (! $equal_cutempty || $value != '') {
947                                         $equals[$key] = $value;
948                                 }
949                         }
950                 }
951
952                 $array = & $not_equals;
953                 foreach ($equals as $key => $value) {
954                         $array[] = $key . '=' . $value;
955                 }
956                 unset($equals);
957         }
958
959         natsort($array);
960         return implode('&', $array);
961 }
962
963 // ---------------------
964 // Part One : Checker
965
966 // Rough implementation of globbing
967 //
968 // USAGE: $regex = '/^' . generate_glob_regex('*.txt', '/') . '$/i';
969 //
970 function generate_glob_regex($string = '', $divider = '/')
971 {
972         static $from = array(
973                          1 => '*',
974                         11 => '?',
975         //              22 => '[',      // Maybe cause regex compilation error (e.g. '[]')
976         //              23 => ']',      //
977                 );
978         static $mid = array(
979                          1 => '_AST_',
980                         11 => '_QUE_',
981         //              22 => '_RBR_',
982         //              23 => '_LBR_',
983                 );
984         static $to = array(
985                          1 => '.*',
986                         11 => '.',
987         //              22 => '[',
988         //              23 => ']',
989                 );
990
991         if (! is_string($string)) return '';
992
993         $string = str_replace($from, $mid, $string); // Hide
994         $string = preg_quote($string, $divider);
995         $string = str_replace($mid, $to, $string);   // Unhide
996
997         return $string;
998 }
999
1000 // Rough hostname checker
1001 // [OK] 192.168.
1002 // TODO: Strict digit, 0x, CIDR, IPv6
1003 function is_ip($string = '')
1004 {
1005         if (preg_match('/^' .
1006                 '(?:[0-9]{1,3}\.){3}[0-9]{1,3}' . '|' .
1007                 '(?:[0-9]{1,3}\.){1,3}' . '$/',
1008                 $string)) {
1009                 return 4;       // Seems IPv4(dot-decimal)
1010         } else {
1011                 return 0;       // Seems not IP
1012         }
1013 }
1014
1015 // Generate host (FQDN, IPv4, ...) regex
1016 // 'localhost'     : Matches with 'localhost' only
1017 // 'example.org'   : Matches with 'example.org' only (See host_normalize() about 'www')
1018 // '.example.org'  : Matches with ALL FQDN ended with '.example.org'
1019 // '*.example.org' : Almost the same of '.example.org' except 'www.example.org'
1020 // '10.20.30.40'   : Matches with IPv4 address '10.20.30.40' only
1021 // [TODO] '192.'   : Matches with all IPv4 hosts started with '192.'
1022 // TODO: IPv4, CIDR?, IPv6
1023 function generate_host_regex($string = '', $divider = '/')
1024 {
1025         if (! is_string($string)) return '';
1026
1027         if (mb_strpos($string, '.') === FALSE)
1028                 return generate_glob_regex($string, $divider);
1029
1030         $result = '';
1031         if (is_ip($string)) {
1032                 // IPv4
1033                 return generate_glob_regex($string, $divider);
1034         } else {
1035                 // FQDN or something
1036                 $part = explode('.', $string, 2);
1037                 if ($part[0] == '') {
1038                         $part[0] = '(?:.*\.)?'; // And all related FQDN
1039                 } else if ($part[0] == '*') {
1040                         $part[0] = '.*\.';      // All subdomains/hosts only
1041                 } else {
1042                         return generate_glob_regex($string, $divider);
1043                 }
1044                 $part[1] = generate_glob_regex($part[1], $divider);
1045                 return implode('', $part);
1046         }
1047 }
1048
1049 function get_blocklist($list = '')
1050 {
1051         static $regexes;
1052
1053         if ($list === NULL) {
1054                 $regexes = NULL;        // Unset
1055                 return array();
1056         }
1057
1058         if (! isset($regexes)) {
1059                 $regexes = array();
1060                 if (file_exists(SPAM_INI_FILE)) {
1061                         $blocklist = array();
1062                         include(SPAM_INI_FILE);
1063                         //      $blocklist['badhost'] = array(
1064                         //              '*.blogspot.com',       // Blog services's subdomains (only)
1065                         //              'IANA-examples' => '#^(?:.*\.)?example\.(?:com|net|org)$#',
1066                         //      );
1067                         if (isset($blocklist['list'])) {
1068                                 $regexes['list'] = & $blocklist['list'];
1069                         } else {
1070                                 // Default
1071                                 $blocklist['list'] = array(
1072                                         'goodhost' => FALSE,
1073                                         'badhost'  => TRUE,
1074                                 );
1075                         }
1076                         foreach(array_keys($blocklist['list']) as $_list) {
1077                                 if (! isset($blocklist[$_list])) continue;
1078                                 foreach ($blocklist[$_list] as $key => $value) {
1079                                         if (is_array($value)) {
1080                                                 $regexes[$_list][$key] = array();
1081                                                 foreach($value as $_key => $_value) {
1082                                                         get_blocklist_add($regexes[$_list][$key], $_key, $_value);
1083                                                 }
1084                                         } else {
1085                                                 get_blocklist_add($regexes[$_list], $key, $value);
1086                                         }
1087                                 }
1088                                 unset($blocklist[$_list]);
1089                         }
1090                 }
1091         }
1092
1093         if ($list === '') {
1094                 return $regexes;        // ALL
1095         } else if (isset($regexes[$list])) {
1096                 return $regexes[$list];
1097         } else {
1098                 return array();
1099         }
1100 }
1101
1102 // Subroutine of get_blocklist()
1103 function get_blocklist_add(& $array, $key = 0, $value = '*.example.org')
1104 {
1105         if (is_string($key)) {
1106                 $array[$key] = & $value; // Treat $value as a regex
1107         } else {
1108                 $array[$value] = '/^' . generate_host_regex($value, '/') . '$/i';
1109         }
1110 }
1111
1112 // Blocklist metrics: Separate $host, to $blocked and not blocked
1113 function blocklist_distiller(& $hosts, $keys = array('goodhost', 'badhost'), $asap = FALSE)
1114 {
1115         if (! is_array($hosts)) $hosts = array($hosts);
1116         if (! is_array($keys))  $keys  = array($keys);
1117
1118         $list = get_blocklist('list');
1119         $blocked = array();
1120
1121         foreach($keys as $key){
1122                 foreach (get_blocklist($key) as $label => $regex) {
1123                         if (is_array($regex)) {
1124                                 foreach($regex as $_label => $_regex) {
1125                                         $group = preg_grep($_regex, $hosts);
1126                                         if ($group) {
1127                                                 $hosts = array_diff($hosts, $group);
1128                                                 $blocked[$key][$label][$_label] = $group;
1129                                                 if ($asap && $list[$key]) break;
1130                                         }
1131                                 }
1132                         } else {
1133                                 $group = preg_grep($regex, $hosts);
1134                                 if ($group) {
1135                                         $hosts = array_diff($hosts, $group);
1136                                         $blocked[$key][$label] = $group;
1137                                         if ($asap && $list[$key]) break;
1138                                 }
1139                         }
1140                 }
1141         }
1142
1143         return $blocked;
1144 }
1145
1146 // Default (enabled) methods and thresholds (for content insertion)
1147 function check_uri_spam_method($times = 1, $t_area = 0, $rule = TRUE)
1148 {
1149         $times  = intval($times);
1150         $t_area = intval($t_area);
1151
1152         $positive = array(
1153                 // Thresholds
1154                 'quantity'     =>  8 * $times,  // Allow N URIs
1155                 'non_uniqhost' =>  3 * $times,  // Allow N duped (and normalized) Hosts
1156                 //'non_uniquri'=>  3 * $times,  // Allow N duped (and normalized) URIs
1157
1158                 // Areas
1159                 'area_anchor'  => $t_area,      // Using <a href> HTML tag
1160                 'area_bbcode'  => $t_area,      // Using [url] or [link] BBCode
1161                 //'uri_anchor' => $t_area,      // URI inside <a href> HTML tag
1162                 //'uri_bbcode' => $t_area,      // URI inside [url] or [link] BBCode
1163         );
1164         if ($rule) {
1165                 $bool = array(
1166                         // Rules
1167                         //'asap'   => TRUE,     // Quit or return As Soon As Possible
1168                         'uniqhost' => TRUE,     // Show uniq host (at block notification mail)
1169                         'badhost'  => TRUE,     // Check badhost
1170                 );
1171         } else {
1172                 $bool = array();
1173         }
1174
1175         // Remove non-$positive values
1176         foreach (array_keys($positive) as $key) {
1177                 if ($positive[$key] < 0) unset($positive[$key]);
1178         }
1179
1180         return $positive + $bool;
1181 }
1182
1183 // Simple/fast spam check
1184 function check_uri_spam($target = '', $method = array())
1185 {
1186         // Return value
1187         $progress = array(
1188                 'method'  => array(
1189                         // Theme to do  => Dummy, optional value, or optional array()
1190                         //'quantity'    => 8,
1191                         //'uniqhost'    => TRUE,
1192                         //'non_uniqhost'=> 3,
1193                         //'non_uniquri' => 3,
1194                         //'badhost'     => TRUE,
1195                         //'area_anchor' => 0,
1196                         //'area_bbcode' => 0,
1197                         //'uri_anchor'  => 0,
1198                         //'uri_bbcode'  => 0,
1199                 ),
1200                 'sum' => array(
1201                         // Theme        => Volume found (int)
1202                 ),
1203                 'is_spam' => array(
1204                         // Flag. If someting defined here,
1205                         // one or more spam will be included
1206                         // in this report
1207                 ),
1208                 'blocked' => array(
1209                         // Hosts blocked
1210                         //'category' => array(
1211                         //      'host',
1212                         //)
1213                 ),
1214                 'hosts' => array(
1215                         // Hosts not blocked
1216                 ),
1217         );
1218
1219         // Aliases
1220         $sum     = & $progress['sum'];
1221         $is_spam = & $progress['is_spam'];
1222         $progress['method'] = & $method;        // Argument
1223         $blocked = & $progress['blocked'];
1224         $hosts   = & $progress['hosts'];
1225         $asap    = isset($method['asap']);
1226
1227         // Init
1228         if (! is_array($method) || empty($method)) {
1229                 $method = check_uri_spam_method();
1230         }
1231         foreach(array_keys($method) as $key) {
1232                 if (! isset($sum[$key])) $sum[$key] = 0;
1233         }
1234         if (! isset($sum['quantity'])) $sum['quantity'] = 0;
1235
1236         if (is_array($target)) {
1237                 foreach($target as $str) {
1238                         if (! is_string($str)) continue;
1239
1240                         $_progress = check_uri_spam($str, $method);     // Recurse
1241
1242                         // Merge $sum
1243                         $_sum = & $_progress['sum'];
1244                         foreach (array_keys($_sum) as $key) {
1245                                 if (! isset($sum[$key])) {
1246                                         $sum[$key] = & $_sum[$key];
1247                                 } else {
1248                                         $sum[$key] += $_sum[$key];
1249                                 }
1250                         }
1251
1252                         // Merge $is_spam
1253                         $_is_spam = & $_progress['is_spam'];
1254                         foreach (array_keys($_is_spam) as $key) {
1255                                 $is_spam[$key] = TRUE;
1256                                 if ($asap) break;
1257                         }
1258                         if ($asap && $is_spam) break;
1259
1260                         // Merge only
1261                         $blocked = array_merge_recursive($blocked, $_progress['blocked']);
1262                         $hosts   = array_merge_recursive($hosts,   $_progress['hosts']);
1263                 }
1264
1265                 // Unique values
1266                 $blocked = array_unique_recursive($blocked);
1267                 $hosts   = array_unique_recursive($hosts);
1268
1269                 // Recount $sum['badhost']
1270                 $sum['badhost'] = array_count_leaves($blocked);
1271
1272                 return $progress;
1273         }
1274
1275         // Area: There's HTML anchor tag
1276         if ((! $asap || ! $is_spam) && isset($method['area_anchor'])) {
1277                 $key = 'area_anchor';
1278                 $_asap = isset($method['asap']) ? array('asap' => TRUE) : array();
1279                 $result = area_pickup($target, array($key => TRUE) + $_asap);
1280                 if ($result) {
1281                         $sum[$key] = $result[$key];
1282                         if (isset($method[$key]) && $sum[$key] > $method[$key]) {
1283                                 $is_spam[$key] = TRUE;
1284                         }
1285                 }
1286         }
1287
1288         // Area: There's 'BBCode' linking tag
1289         if ((! $asap || ! $is_spam) && isset($method['area_bbcode'])) {
1290                 $key = 'area_bbcode';
1291                 $_asap = isset($method['asap']) ? array('asap' => TRUE) : array();
1292                 $result = area_pickup($target, array($key => TRUE) + $_asap);
1293                 if ($result) {
1294                         $sum[$key] = $result[$key];
1295                         if (isset($method[$key]) && $sum[$key] > $method[$key]) {
1296                                 $is_spam[$key] = TRUE;
1297                         }
1298                 }
1299         }
1300
1301         // Return if ...
1302         if ($asap && $is_spam) return $progress;
1303
1304         // URI: Pickup
1305         $pickups = uri_pickup_normalize(spam_uri_pickup($target, $method));
1306
1307         // Return if ...
1308         if (empty($pickups)) return $progress;
1309
1310         // URI: Check quantity
1311         $sum['quantity'] += count($pickups);
1312                 // URI quantity
1313         if ((! $asap || ! $is_spam) && isset($method['quantity']) &&
1314                 $sum['quantity'] > $method['quantity']) {
1315                 $is_spam['quantity'] = TRUE;
1316         }
1317
1318         // URI: used inside HTML anchor tag pair
1319         if ((! $asap || ! $is_spam) && isset($method['uri_anchor'])) {
1320                 $key = 'uri_anchor';
1321                 foreach($pickups as $pickup) {
1322                         if (isset($pickup['area'][$key])) {
1323                                 $sum[$key] += $pickup['area'][$key];
1324                                 if(isset($method[$key]) &&
1325                                         $sum[$key] > $method[$key]) {
1326                                         $is_spam[$key] = TRUE;
1327                                         if ($asap && $is_spam) break;
1328                                 }
1329                                 if ($asap && $is_spam) break;
1330                         }
1331                 }
1332         }
1333
1334         // URI: used inside 'BBCode' pair
1335         if ((! $asap || ! $is_spam) && isset($method['uri_bbcode'])) {
1336                 $key = 'uri_bbcode';
1337                 foreach($pickups as $pickup) {
1338                         if (isset($pickup['area'][$key])) {
1339                                 $sum[$key] += $pickup['area'][$key];
1340                                 if(isset($method[$key]) &&
1341                                         $sum[$key] > $method[$key]) {
1342                                         $is_spam[$key] = TRUE;
1343                                         if ($asap && $is_spam) break;
1344                                 }
1345                                 if ($asap && $is_spam) break;
1346                         }
1347                 }
1348         }
1349
1350         // URI: Uniqueness (and removing non-uniques)
1351         if ((! $asap || ! $is_spam) && isset($method['non_uniquri'])) {
1352
1353                 $uris = array();
1354                 foreach (array_keys($pickups) as $key) {
1355                         $uris[$key] = uri_pickup_implode($pickups[$key]);
1356                 }
1357                 $count = count($uris);
1358                 $uris  = array_unique($uris);
1359                 $sum['non_uniquri'] += $count - count($uris);
1360                 if ($sum['non_uniquri'] > $method['non_uniquri']) {
1361                         $is_spam['non_uniquri'] = TRUE;
1362                 }
1363                 if (! $asap || ! $is_spam) {
1364                         foreach (array_diff(array_keys($pickups),
1365                                 array_keys($uris)) as $remove) {
1366                                 unset($pickups[$remove]);
1367                         }
1368                 }
1369                 unset($uris);
1370         }
1371
1372         // Return if ...
1373         if ($asap && $is_spam) return $progress;
1374
1375         // Host: Uniqueness (uniq / non-uniq)
1376         foreach ($pickups as $pickup) $hosts[] = & $pickup['host'];
1377         $hosts = array_unique($hosts);
1378         $sum['uniqhost'] += count($hosts);
1379         if ((! $asap || ! $is_spam) && isset($method['non_uniqhost'])) {
1380                 $sum['non_uniqhost'] = $sum['quantity'] - $sum['uniqhost'];
1381                 if ($sum['non_uniqhost'] > $method['non_uniqhost']) {
1382                         $is_spam['non_uniqhost'] = TRUE;
1383                 }
1384         }
1385
1386         // Return if ...
1387         if ($asap && $is_spam) return $progress;
1388
1389         // URI: Bad host (Separate good/bad hosts from $hosts)
1390         if ((! $asap || ! $is_spam) && isset($method['badhost'])) {
1391
1392                 // is_badhost()
1393                 $list = get_blocklist('list');
1394                 $blocked = blocklist_distiller($hosts, array_keys($list), $asap);
1395                 foreach($list as $key=>$type){
1396                         if (! $type) unset($blocked[$key]); // Ignore goodhost etc
1397                 }
1398                 unset($list);
1399
1400                 if (! empty($blocked)) $is_spam['badhost'] = TRUE;
1401         }
1402
1403         return $progress;
1404 }
1405
1406 // Count leaves (A leaf = value that is not an array, or an empty array)
1407 function array_count_leaves($array = array(), $count_empty = FALSE)
1408 {
1409         if (! is_array($array) || (empty($array) && $count_empty)) return 1;
1410
1411         // Recurse
1412         $count = 0;
1413         foreach ($array as $part) {
1414                 $count += array_count_leaves($part, $count_empty);
1415         }
1416         return $count;
1417 }
1418
1419 // An array-leaves to a flat array
1420 function array_flat_leaves($array, $unique = TRUE)
1421 {
1422         if (! is_array($array)) return $array;
1423
1424         $tmp = array();
1425         foreach(array_keys($array) as $key) {
1426                 if (is_array($array[$key])) {
1427                         // Recurse
1428                         foreach(array_flat_leaves($array[$key]) as $_value) {
1429                                 $tmp[] = $_value;
1430                         }
1431                 } else {
1432                         $tmp[] = & $array[$key];
1433                 }
1434         }
1435
1436         return $unique ? array_values(array_unique($tmp)) : $tmp;
1437 }
1438
1439 // An array() to an array leaf
1440 function array_leaf($array = array('A', 'B', 'C.D'), $stem = FALSE, $edge = TRUE)
1441 {
1442         if (! is_array($array)) return $array;
1443
1444         $leaf = array();
1445         $tmp  = & $leaf;
1446         foreach($array as $arg) {
1447                 if (! is_string($arg) && ! is_int($arg)) continue;
1448                 $tmp[$arg] = array();
1449                 $parent    = & $tmp;
1450                 $tmp       = & $tmp[$arg];
1451         }
1452         if ($stem) {
1453                 $parent[key($parent)] = & $edge;
1454         } else {
1455                 $parent = key($parent);
1456         }
1457
1458         return $leaf;   // array('A' => array('B' => 'C.D'))
1459 }
1460
1461
1462 // ---------------------
1463 // Reporting
1464
1465 // Summarize $progress (blocked only)
1466 function summarize_spam_progress($progress = array(), $blockedonly = FALSE)
1467 {
1468         if ($blockedonly) {
1469                 $tmp = array_keys($progress['is_spam']);
1470         } else {
1471                 $tmp = array();
1472                 $method = & $progress['method'];
1473                 if (isset($progress['sum'])) {
1474                         foreach ($progress['sum'] as $key => $value) {
1475                                 if (isset($method[$key]) && $value) {
1476                                         $tmp[] = $key . '(' . $value . ')';
1477                                 }
1478                         }
1479                 }
1480         }
1481
1482         return implode(', ', $tmp);
1483 }
1484
1485 function summarize_detail_badhost($progress = array())
1486 {
1487         if (! isset($progress['blocked']) || empty($progress['blocked'])) return '';
1488
1489         // Flat per group
1490         $blocked = array();
1491         foreach($progress['blocked'] as $list => $lvalue) {
1492                 foreach($lvalue as $group => $gvalue) {
1493                         $flat = implode(', ', array_flat_leaves($gvalue));
1494                         if ($flat === $group) {
1495                                 $blocked[$list][]       = $flat;
1496                         } else {
1497                                 $blocked[$list][$group] = $flat;
1498                         }
1499                 }
1500         }
1501
1502         // Shrink per list
1503         // From: 'A-1' => array('ie.to')
1504         // To:   'A-1' => 'ie.to'
1505         foreach($blocked as $list => $lvalue) {
1506                 if (is_array($lvalue) &&
1507                    count($lvalue) == 1 &&
1508                    is_numeric(key($lvalue))) {
1509                     $blocked[$list] = current($lvalue);
1510                 }
1511         }
1512
1513         return var_export_shrink($blocked, TRUE, TRUE);
1514 }
1515
1516 function summarize_detail_newtral($progress = array())
1517 {
1518         if (! isset($progress['hosts'])    ||
1519             ! is_array($progress['hosts']) ||
1520             empty($progress['hosts'])) return '';
1521
1522         $result = '';
1523
1524         // Generate a $trie
1525         $trie = array();
1526         foreach($progress['hosts'] as $value) {
1527
1528                 // Try to shorten (pre) -- array('example.com', 'bar', 'foo')
1529                 $resp = whois_responsibility($value);   // 'example.com'
1530                 $rest = rtrim(substr($value, 0, - strlen($resp)), '.'); // 'foo.bar'
1531                 if ($rest) {
1532                         $parts = explode('.', delimiter_reverse('.' . $rest));
1533                         array_unshift($parts, $resp);
1534                 } else {
1535                         $parts = array($resp, $rest);
1536                 }
1537
1538                 $trie = array_merge_recursive(
1539                         $trie,
1540                         array_leaf($parts, TRUE, $value)
1541                 );
1542         }
1543
1544         // Try to shorten (post, non-recursive) -- 'foo.bar.example.com'
1545         array_joinbranch_leaf($trie, '.', 0, TRUE);
1546
1547         // Sort and flatten -- 'A.foo.bar.example.com, B.foo.bar.example.com'
1548         foreach(array_keys($trie) as $key) {
1549                 if (is_array($trie[$key])) {
1550                         ksort_by_domain($trie[$key]);
1551                         $trie[$key] = implode(', ', array_flat_leaves($trie[$key]));
1552                 }
1553         }
1554
1555         // TODO: ltrim('.') from $trie
1556
1557         ksort_by_domain($trie);
1558
1559         // TODO: from array('foobar' => 'foobar') to 'foobar'
1560
1561         return var_export_shrink($trie, TRUE, TRUE);
1562 }
1563
1564 // ksort() by domain
1565 function ksort_by_domain(& $array)
1566 {
1567         $sort = array();
1568         foreach(array_keys($array) as $key) {
1569                 $sort[delimiter_reverse($key)] = $key;
1570         }
1571         ksort($sort, SORT_STRING);
1572         $result = array();
1573         foreach($sort as $key) {
1574                 $result[$key] = & $array[$key];
1575         }
1576         $array = $result;
1577 }
1578
1579 // array('F' => array('B' => array('C' => array('d' => array('' => 'foobar')))))
1580 // to
1581 // array('F.B.C.d.' => 'foobar')
1582 function array_joinbranch_leaf(& $array, $delim = '.', $limit = 0, $reverse = FALSE)
1583 {
1584         $result = array();
1585         if (! is_array($array)) return $result; // Nothing to do
1586
1587         $limit  = max(0, intval($limit));
1588         $cstack = array();
1589
1590         foreach(array_keys($array) as $key) {
1591                 $kstack = array();
1592                 $k      = -1;
1593
1594                 $single = array($key => & $array[$key]);        // Keep it single
1595                 $cursor = & $single;
1596                 while(is_array($cursor) && count($cursor) == 1) {       // Once
1597                         ++$k;
1598                         $kstack[] = key($cursor);
1599                         $cursor   = & $cursor[$kstack[$k]];
1600                         if ($limit != 0 && $k == $limit) break;
1601                 }
1602
1603                 // Relink
1604                 if ($k != 0) {
1605                         if ($reverse) $kstack = array_reverse($kstack);
1606                         $joinkey = implode($delim, $kstack);
1607
1608                         unset($array[$key]);
1609                         $array[$joinkey]  = & $cursor;
1610                         $result[$joinkey] = $k + 1;     // Key seems not an single array => joined length
1611                 }
1612         }
1613
1614         return $result;
1615 }
1616
1617
1618 // Check responsibility-root of the FQDN
1619 // 'foo.bar.example.com'        => 'example.com'        (.com        has the last whois for it)
1620 // 'foo.bar.example.au'         => 'example.au'         (.au         has the last whois for it)
1621 // 'foo.bar.example.edu.au'     => 'example.edu.au'     (.edu.au     has the last whois for it)
1622 // 'foo.bar.example.act.edu.au' => 'example.act.edu.au' (.act.edu.au has the last whois for it)
1623 function whois_responsibility($fqdn = 'foo.bar.example.com', $parent = FALSE, $implicit = TRUE)
1624 {
1625         // Domains who have 2nd and/or 3rd level domains
1626         static $domain = array(
1627
1628                 // ccTLD: Australia
1629                 // http://www.auda.org.au/
1630                 // NIC  : http://www.aunic.net/
1631                 // Whois: http://www.ausregistry.com.au/
1632                 'au' => array(
1633                         // .au Second Level Domains
1634                         // http://www.auda.org.au/domains/
1635                         'asn'   => TRUE,
1636                         'com'   => TRUE,
1637                         'conf'  => TRUE,
1638                         'csiro' => TRUE,
1639                         'edu'   => array(       // http://www.domainname.edu.au/
1640                                 // Geographic
1641                                 'act' => TRUE,
1642                                 'nt'  => TRUE,
1643                                 'nsw' => TRUE,
1644                                 'qld' => TRUE,
1645                                 'sa'  => TRUE,
1646                                 'tas' => TRUE,
1647                                 'vic' => TRUE,
1648                                 'wa'  => TRUE,
1649                         ),
1650                         'gov'   => array(
1651                                 // Geographic
1652                                 'act' => TRUE,  // Australian Capital Territory
1653                                 'nt'  => TRUE,  // Northern Territory
1654                                 'nsw' => TRUE,  // New South Wales
1655                                 'qld' => TRUE,  // Queensland
1656                                 'sa'  => TRUE,  // South Australia
1657                                 'tas' => TRUE,  // Tasmania
1658                                 'vic' => TRUE,  // Victoria
1659                                 'wa'  => TRUE,  // Western Australia
1660                         ),
1661                         'id'    => TRUE,
1662                         'net'   => TRUE,
1663                         'org'   => TRUE,
1664                         'info'  => TRUE,
1665                 ),
1666
1667                 // ccTLD: China
1668                 // NIC  : http://www.cnnic.net.cn/en/index/
1669                 // Whois: http://ewhois.cnnic.cn/
1670                 'cn' => array(
1671                         // Provisional Administrative Rules for Registration of Domain Names in China
1672                         // http://www.cnnic.net.cn/html/Dir/2003/11/27/1520.htm
1673
1674                         // Organizational
1675                         'ac'  => TRUE,
1676                         'com' => TRUE,
1677                         'edu' => TRUE,
1678                         'gov' => TRUE,
1679                         'net' => TRUE,
1680                         'org' => TRUE,
1681
1682                         // Geographic
1683                         'ah' => TRUE,
1684                         'bj' => TRUE,
1685                         'cq' => TRUE,
1686                         'fj' => TRUE,
1687                         'gd' => TRUE,
1688                         'gs' => TRUE,
1689                         'gx' => TRUE,
1690                         'gz' => TRUE,
1691                         'ha' => TRUE,
1692                         'hb' => TRUE,
1693                         'he' => TRUE,
1694                         'hi' => TRUE,
1695                         'hk' => TRUE,
1696                         'hl' => TRUE,
1697                         'hn' => TRUE,
1698                         'jl' => TRUE,
1699                         'js' => TRUE,
1700                         'jx' => TRUE,
1701                         'ln' => TRUE,
1702                         'mo' => TRUE,
1703                         'nm' => TRUE,
1704                         'nx' => TRUE,
1705                         'qh' => TRUE,
1706                         'sc' => TRUE,
1707                         'sd' => TRUE,
1708                         'sh' => TRUE,
1709                         'sn' => TRUE,
1710                         'sx' => TRUE,
1711                         'tj' => TRUE,
1712                         'tw' => TRUE,
1713                         'xj' => TRUE,
1714                         'xz' => TRUE,
1715                         'yn' => TRUE,
1716                         'zj' => TRUE,
1717                 ),
1718
1719                 // ccTLD: South Korea
1720                 // NIC  : http://www.nic.or.kr/english/
1721                 // Whois: http://whois.nida.or.kr/english/
1722                 'kr' => array(
1723                         // .kr domain policy [appendix 1] : Qualifications for Second Level Domains
1724                         // http://domain.nida.or.kr/eng/policy.jsp
1725
1726                         // Organizational
1727                         'co'  => TRUE,
1728                         'ne ' => TRUE,
1729                         'or ' => TRUE,
1730                         're ' => TRUE,
1731                         'pe'  => TRUE,
1732                         'go ' => TRUE,
1733                         'mil' => TRUE,
1734                         'ac'  => TRUE,
1735                         'hs'  => TRUE,
1736                         'ms'  => TRUE,
1737                         'es'  => TRUE,
1738                         'sc'  => TRUE,
1739                         'kg'  => TRUE,
1740
1741                         // Geographic
1742                         'seoul'     => TRUE,
1743                         'busan'     => TRUE,
1744                         'daegu'     => TRUE,
1745                         'incheon'   => TRUE,
1746                         'gwangju'   => TRUE,
1747                         'daejeon'   => TRUE,
1748                         'ulsan'     => TRUE,
1749                         'gyeonggi'  => TRUE,
1750                         'gangwon'   => TRUE,
1751                         'chungbuk'  => TRUE,
1752                         'chungnam'  => TRUE,
1753                         'jeonbuk'   => TRUE,
1754                         'jeonnam'   => TRUE,
1755                         'gyeongbuk' => TRUE,
1756                         'gyeongnam' => TRUE,
1757                         'jeju'      => TRUE,
1758                 ),
1759
1760                 // ccTLD: Japan
1761                 // NIC  : http://jprs.co.jp/en/
1762                 // Whois: http://whois.jprs.jp/en/
1763                 'jp' => array(
1764                         // Guide to JP Domain Name
1765                         // http://jprs.co.jp/en/jpdomain.html
1766
1767                         // Organizational
1768                         'ac' => TRUE,
1769                         'ad' => TRUE,
1770                         'co' => TRUE,
1771                         'go' => TRUE,
1772                         'gr' => TRUE,
1773                         'lg' => TRUE,
1774                         'ne' => TRUE,
1775                         'or' => TRUE,
1776
1777                         // Geographic
1778                         //
1779                         // Examples for 3rd level domains
1780                         //'kumamoto'  => array(
1781                         //      // http://www.pref.kumamoto.jp/link/list.asp#4
1782                         //      'amakusa'   => TRUE,
1783                         //      'hitoyoshi' => TRUE,
1784                         //      'jonan'     => TRUE,
1785                         //      'kumamoto'  => TRUE,
1786                         //      ...
1787                         //),
1788                         'aichi'     => TRUE,
1789                         'akita'     => TRUE,
1790                         'aomori'    => TRUE,
1791                         'chiba'     => TRUE,
1792                         'ehime'     => TRUE,
1793                         'fukui'     => TRUE,
1794                         'fukuoka'   => TRUE,
1795                         'fukushima' => TRUE,
1796                         'gifu'      => TRUE,
1797                         'gunma'     => TRUE,
1798                         'hiroshima' => TRUE,
1799                         'hokkaido'  => TRUE,
1800                         'hyogo'     => TRUE,
1801                         'ibaraki'   => TRUE,
1802                         'ishikawa'  => TRUE,
1803                         'iwate'     => TRUE,
1804                         'kagawa'    => TRUE,
1805                         'kagoshima' => TRUE,
1806                         'kanagawa'  => TRUE,
1807                         'kawasaki'  => TRUE,
1808                         'kitakyushu'=> TRUE,
1809                         'kobe'      => TRUE,
1810                         'kochi'     => TRUE,
1811                         'kumamoto'  => TRUE,
1812                         'kyoto'     => TRUE,
1813                         'mie'       => TRUE,
1814                         'miyagi'    => TRUE,
1815                         'miyazaki'  => TRUE,
1816                         'nagano'    => TRUE,
1817                         'nagasaki'  => TRUE,
1818                         'nagoya'    => TRUE,
1819                         'nara'      => TRUE,
1820                         'niigata'   => TRUE,
1821                         'oita'      => TRUE,
1822                         'okayama'   => TRUE,
1823                         'okinawa'   => TRUE,
1824                         'osaka'     => TRUE,
1825                         'saga'      => TRUE,
1826                         'saitama'   => TRUE,
1827                         'sapporo'   => TRUE,
1828                         'sendai'    => TRUE,
1829                         'shiga'     => TRUE,
1830                         'shimane'   => TRUE,
1831                         'shizuoka'  => TRUE,
1832                         'tochigi'   => TRUE,
1833                         'tokushima' => TRUE,
1834                         'tokyo'     => TRUE,
1835                         'tottori'   => TRUE,
1836                         'toyama'    => TRUE,
1837                         'wakayama'  => TRUE,
1838                         'yamagata'  => TRUE,
1839                         'yamaguchi' => TRUE,
1840                         'yamanashi' => TRUE,
1841                         'yokohama'  => TRUE,
1842                 ),
1843
1844                 // ccTLD: Ukraine
1845                 // NIC  : http://www.nic.net.ua/
1846                 // Whois: http://whois.com.ua/
1847                 'ua' => array(
1848                         // policy for alternative 2nd level domain names (a2ld)
1849                         // http://www.nic.net.ua/doc/a2ld
1850                         // http://whois.com.ua/
1851                         'cherkassy'  => TRUE,
1852                         'chernigov'  => TRUE,
1853                         'chernovtsy' => TRUE,
1854                         'ck'         => TRUE,
1855                         'cn'         => TRUE,
1856                         'com'        => TRUE,
1857                         'crimea'     => TRUE,
1858                         'cv'         => TRUE,
1859                         'dn'         => TRUE,
1860                         'dnepropetrovsk' => TRUE,
1861                         'donetsk'    => TRUE,
1862                         'dp'         => TRUE,
1863                         'edu'        => TRUE,
1864                         'gov'        => TRUE,
1865                         'if'         => TRUE,
1866                         'ivano-frankivsk' => TRUE,
1867                         'kh'         => TRUE,
1868                         'kharkov'    => TRUE,
1869                         'kherson'    => TRUE,
1870                         'kiev'       => TRUE,
1871                         'kirovograd' => TRUE,
1872                         'km'         => TRUE,
1873                         'kr'         => TRUE,
1874                         'ks'         => TRUE,
1875                         'lg'         => TRUE,
1876                         'lugansk'    => TRUE,
1877                         'lutsk'      => TRUE,
1878                         'lviv'       => TRUE,
1879                         'mk'         => TRUE,
1880                         'net'        => TRUE,
1881                         'nikolaev'   => TRUE,
1882                         'od'         => TRUE,
1883                         'odessa'     => TRUE,
1884                         'org'        => TRUE,
1885                         'pl'         => TRUE,
1886                         'poltava'    => TRUE,
1887                         'rovno'      => TRUE,
1888                         'rv'         => TRUE,
1889                         'sebastopol' => TRUE,
1890                         'sumy'       => TRUE,
1891                         'te'         => TRUE,
1892                         'ternopil'   => TRUE,
1893                         'uz'         => TRUE,
1894                         'uzhgorod'   => TRUE,
1895                         'vinnica'    => TRUE,
1896                         'vn'         => TRUE,
1897                         'zaporizhzhe' => TRUE,
1898                         'zhitomir'   => TRUE,
1899                         'zp'         => TRUE,
1900                         'zt'         => TRUE,
1901                 ),
1902
1903                 // ccTLD: United Kingdom
1904                 // NIC  : http://www.nic.uk/
1905                 'uk' => array(
1906                         // Second Level Domains
1907                         // http://www.nic.uk/registrants/aboutdomainnames/sld/
1908                         'co'     => TRUE,
1909                         'ltd'    => TRUE,
1910                         'me'     => TRUE,
1911                         'net'    => TRUE,
1912                         'nic'    => TRUE,
1913                         'org'    => TRUE,
1914                         'plc'    => TRUE,
1915                         'sch'    => TRUE,
1916                         
1917                         // Delegated Second Level Domains
1918                         // http://www.nic.uk/registrants/aboutdomainnames/sld/delegated/
1919                         'ac'     => TRUE,
1920                         'gov'    => TRUE,
1921                         'mil'    => TRUE,
1922                         'mod'    => TRUE,
1923                         'nhs'    => TRUE,
1924                         'police' => TRUE,
1925                 ),
1926
1927                 // ccTLD: United States of America
1928                 // NIC  : http://nic.us/
1929                 // Whois: http://whois.us/
1930                 'us' => array(
1931                         // See RFC1480
1932
1933                         // Organizational
1934                         'dni',
1935                         'fed',
1936                         'isa',
1937                         'kids',
1938                         'nsn',
1939
1940                         // Geographical
1941                         // United States Postal Service: State abbreviations (for postal codes)
1942                         // http://www.usps.com/ncsc/lookups/abbreviations.html
1943                         'ak' => TRUE, // Alaska
1944                         'al' => TRUE, // Alabama
1945                         'ar' => TRUE, // Arkansas
1946                         'as' => TRUE, // American samoa
1947                         'az' => TRUE, // Arizona
1948                         'ca' => TRUE, // California
1949                         'co' => TRUE, // Colorado
1950                         'ct' => TRUE, // Connecticut
1951                         'dc' => TRUE, // District of Columbia
1952                         'de' => TRUE, // Delaware
1953                         'fl' => TRUE, // Florida
1954                         'fm' => TRUE, // Federated states of Micronesia
1955                         'ga' => TRUE, // Georgia
1956                         'gu' => TRUE, // Guam
1957                         'hi' => TRUE, // Hawaii
1958                         'ia' => TRUE, // Iowa
1959                         'id' => TRUE, // Idaho
1960                         'il' => TRUE, // Illinois
1961                         'in' => TRUE, // Indiana
1962                         'ks' => TRUE, // Kansas
1963                         'ky' => TRUE, // Kentucky
1964                         'la' => TRUE, // Louisiana
1965                         'ma' => TRUE, // Massachusetts
1966                         'md' => TRUE, // Maryland
1967                         'me' => TRUE, // Maine
1968                         'mh' => TRUE, // Marshall Islands
1969                         'mi' => TRUE, // Michigan
1970                         'mn' => TRUE, // Minnesota
1971                         'mo' => TRUE, // Missouri
1972                         'mp' => TRUE, // Northern mariana islands
1973                         'ms' => TRUE, // Mississippi
1974                         'mt' => TRUE, // Montana
1975                         'nc' => TRUE, // North Carolina
1976                         'nd' => TRUE, // North Dakota
1977                         'ne' => TRUE, // Nebraska
1978                         'nh' => TRUE, // New Hampshire
1979                         'nj' => TRUE, // New Jersey
1980                         'nm' => TRUE, // New Mexico
1981                         'nv' => TRUE, // Nevada
1982                         'ny' => TRUE, // New York
1983                         'oh' => TRUE, // Ohio
1984                         'ok' => TRUE, // Oklahoma
1985                         'or' => TRUE, // Oregon
1986                         'pa' => TRUE, // Pennsylvania
1987                         'pr' => TRUE, // Puerto Rico
1988                         'pw' => TRUE, // Palau
1989                         'ri' => TRUE, // Rhode Island
1990                         'sc' => TRUE, // South Carolina
1991                         'sd' => TRUE, // South Dakota
1992                         'tn' => TRUE, // Tennessee
1993                         'tx' => TRUE, // Texas
1994                         'ut' => TRUE, // Utah
1995                         'va' => TRUE, // Virginia
1996                         'vi' => TRUE, // Virgin Islands
1997                         'vt' => TRUE, // Vermont
1998                         'wa' => TRUE, // Washington
1999                         'wi' => TRUE, // Wisconsin
2000                         'wv' => TRUE, // West Virginia
2001                         'wy' => TRUE, // Wyoming
2002                 ),
2003         );
2004
2005         if (! is_string($fqdn)) return '';
2006
2007         $result  = array();
2008         $dcursor = & $domain;
2009         $array   = array_reverse(explode('.', $fqdn));
2010         $i = 0;
2011         while(TRUE) {
2012                 $acursor = $array[$i];
2013                 if (is_array($dcursor) && isset($dcursor[$acursor])) {
2014                         $result[] = & $array[$i];
2015                         $dcursor  = & $dcursor[$acursor];
2016                 } else {
2017                         if (! $parent && isset($acursor)) {
2018                                 $result[] = & $array[$i];       // Whois servers must know this subdomain
2019                         }
2020                         break;
2021                 }
2022                 ++$i;
2023         }
2024
2025         // Implicit responsibility: Top-Level-Domains must not be yours
2026         // 'bar.foo.something' => 'foo.something'
2027         if ($implicit && count($result) == 1 && count($array) > 1) {
2028                 $result[] = & $array[1];
2029         }
2030
2031         return $result ? implode('.', array_reverse($result)) : '';
2032 }
2033
2034
2035 // ---------------------
2036 // Exit
2037
2038 // Freeing memories
2039 function spam_dispose()
2040 {
2041         get_blocklist(NULL);
2042 }
2043
2044 // Common bahavior for blocking
2045 // NOTE: Call this function from various blocking feature, to disgueise the reason 'why blocked'
2046 function spam_exit($mode = '', $data = array())
2047 {
2048
2049         $exit = TRUE;
2050         switch ($mode) {
2051                 case '':
2052                         echo("\n");
2053                         break;
2054                 case 'dump':
2055                         echo('<pre>' . "\n");
2056                         echo htmlspecialchars(var_export($data, TRUE));
2057                         echo('</pre>' . "\n");
2058                         break;
2059         };
2060
2061         if ($exit) exit;        // Force exit
2062 }
2063
2064
2065 // ---------------------
2066 // Simple filtering
2067
2068 // TODO: Record them
2069 // Simple/fast spam filter ($target: 'a string' or an array())
2070 function pkwk_spamfilter($action, $page, $target = array('title' => ''), $method = array(), $exitmode = '')
2071 {
2072         $progress = check_uri_spam($target, $method);
2073
2074         if (empty($progress['is_spam'])) {
2075                 spam_dispose();
2076         } else {
2077                 $target = strings($target, 0);  // Removing "\0" etc
2078                 pkwk_spamnotify($action, $page, $target, $progress, $method);
2079                 spam_exit($exitmode, $progress);
2080         }
2081 }
2082
2083 // ---------------------
2084 // PukiWiki original
2085
2086 // Mail to administrator(s)
2087 function pkwk_spamnotify($action, $page, $target = array('title' => ''), $progress = array(), $method = array())
2088 {
2089         global $notify, $notify_subject;
2090
2091         if (! $notify) return;
2092
2093         $asap = isset($method['asap']);
2094
2095         $summary['ACTION']  = 'Blocked by: ' . summarize_spam_progress($progress, TRUE);
2096         if (! $asap) {
2097                 $summary['METRICS'] = summarize_spam_progress($progress);
2098         }
2099
2100         $tmp = summarize_detail_badhost($progress);
2101         if ($tmp != '') $summary['DETAIL_BADHOST'] = $tmp;
2102
2103         $tmp = summarize_detail_newtral($progress);
2104         if (! $asap && $tmp != '') $summary['DETAIL_NEUTRAL_HOST'] = $tmp;
2105
2106         $summary['COMMENT'] = $action;
2107         $summary['PAGE']    = '[blocked] ' . (is_pagename($page) ? $page : '');
2108         $summary['URI']     = get_script_uri() . '?' . rawurlencode($page);
2109         $summary['USER_AGENT']  = TRUE;
2110         $summary['REMOTE_ADDR'] = TRUE;
2111         pkwk_mail_notify($notify_subject,  var_export($target, TRUE), $summary, TRUE);
2112 }
2113
2114 ?>