OSDN Git Service

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