OSDN Git Service

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