OSDN Git Service

.ru, .tz, .za
[pukiwiki/pukiwiki_sandbox.git] / spam / spam.php
1 <?php
2 // $Id: spam.php,v 1.191 2007/06/24 03:13:09 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         // Generate a responsible $trie
1525         $trie = array();
1526         foreach($progress['hosts'] as $value) {
1527                 // 'A.foo.bar.example.com'
1528                 $resp = whois_responsibility($value);   // 'example.com'
1529                 if (empty($resp)) {
1530                         // One or more test, or do nothing here
1531                         $resp = strval($value);
1532                         $rest = '';
1533                 } else {
1534                         $rest = rtrim(substr($value, 0, - strlen($resp)), '.'); // 'A.foo.bar'
1535                 }
1536                 $trie = array_merge_recursive($trie, array($resp => array($rest => NULL)));
1537         }
1538
1539         // Format: var_export_shrink() -like output
1540         $result = array();
1541         ksort_by_domain($trie);
1542         foreach(array_keys($trie) as $key) {
1543                 ksort_by_domain($trie[$key]);
1544                 if (count($trie[$key]) == 1 && key($trie[$key]) == '') {
1545                         // Just one 'responsibility.example.com'
1546                         $result[] = '  \'' . $key . '\',';
1547                 } else {
1548                         // One subdomain-or-host, or several ones
1549                         $subs = array();
1550                         foreach(array_keys($trie[$key]) as $sub) {
1551                                 if ($sub == '') {
1552                                         $subs[] = $key;
1553                                 } else {
1554                                         $subs[] = $sub . '.' . $key;
1555                                 }
1556                         }
1557                         $result[] = '  \'' . $key . '\' => \'' . implode(', ', $subs) . '\',';
1558                 }
1559                 unset($trie[$key]);
1560         }
1561         return
1562                 'array (' . "\n" .
1563                         implode("\n", $result) . "\n" .
1564                 ')';
1565 }
1566
1567 // ksort() by domain
1568 function ksort_by_domain(& $array)
1569 {
1570         $sort = array();
1571         foreach(array_keys($array) as $key) {
1572                 $sort[delimiter_reverse($key)] = $key;
1573         }
1574         ksort($sort, SORT_STRING);
1575         $result = array();
1576         foreach($sort as $key) {
1577                 $result[$key] = & $array[$key];
1578         }
1579         $array = $result;
1580 }
1581
1582 // Check responsibility-root of the FQDN
1583 // 'foo.bar.example.com'        => 'example.com'        (.com        has the last whois for it)
1584 // 'foo.bar.example.au'         => 'example.au'         (.au         has the last whois for it)
1585 // 'foo.bar.example.edu.au'     => 'example.edu.au'     (.edu.au     has the last whois for it)
1586 // 'foo.bar.example.act.edu.au' => 'example.act.edu.au' (.act.edu.au has the last whois for it)
1587 function whois_responsibility($fqdn = 'foo.bar.example.com', $parent = FALSE, $implicit = TRUE)
1588 {
1589         // Domains who have 2nd and/or 3rd level domains
1590         static $domain = array(
1591
1592                 // ccTLD: Australia
1593                 // http://www.auda.org.au/
1594                 // NIC  : http://www.aunic.net/
1595                 // Whois: http://www.ausregistry.com.au/
1596                 'au' => array(
1597                         // .au Second Level Domains
1598                         // http://www.auda.org.au/domains/
1599                         'asn'   => TRUE,
1600                         'com'   => TRUE,
1601                         'conf'  => TRUE,
1602                         'csiro' => TRUE,
1603                         'edu'   => array(       // http://www.domainname.edu.au/
1604                                 // Geographic
1605                                 'act' => TRUE,
1606                                 'nt'  => TRUE,
1607                                 'nsw' => TRUE,
1608                                 'qld' => TRUE,
1609                                 'sa'  => TRUE,
1610                                 'tas' => TRUE,
1611                                 'vic' => TRUE,
1612                                 'wa'  => TRUE,
1613                         ),
1614                         'gov'   => array(
1615                                 // Geographic
1616                                 'act' => TRUE,  // Australian Capital Territory
1617                                 'nt'  => TRUE,  // Northern Territory
1618                                 'nsw' => TRUE,  // New South Wales
1619                                 'qld' => TRUE,  // Queensland
1620                                 'sa'  => TRUE,  // South Australia
1621                                 'tas' => TRUE,  // Tasmania
1622                                 'vic' => TRUE,  // Victoria
1623                                 'wa'  => TRUE,  // Western Australia
1624                         ),
1625                         'id'    => TRUE,
1626                         'net'   => TRUE,
1627                         'org'   => TRUE,
1628                         'info'  => TRUE,
1629                 ),
1630
1631                 // ccTLD: Bahrain
1632                 // NIC  : http://www.inet.com.bh/ (.bh policies not found)
1633                 // Whois: (Not available) http://www.inet.com.bh/
1634                 'bh' => array(
1635                         // Observed
1636                         'com' => TRUE,
1637                         'edu' => TRUE,
1638                         'gov' => TRUE,
1639                         'org' => TRUE,
1640                 ),
1641
1642                 // ccTLD: China
1643                 // NIC  : http://www.cnnic.net.cn/en/index/
1644                 // Whois: http://ewhois.cnnic.cn/
1645                 'cn' => array(
1646                         // Provisional Administrative Rules for Registration of Domain Names in China
1647                         // http://www.cnnic.net.cn/html/Dir/2003/11/27/1520.htm
1648
1649                         // Organizational
1650                         'ac'  => TRUE,
1651                         'com' => TRUE,
1652                         'edu' => TRUE,
1653                         'gov' => TRUE,
1654                         'net' => TRUE,
1655                         'org' => TRUE,
1656
1657                         // Geographic
1658                         'ah' => TRUE,
1659                         'bj' => TRUE,
1660                         'cq' => TRUE,
1661                         'fj' => TRUE,
1662                         'gd' => TRUE,
1663                         'gs' => TRUE,
1664                         'gx' => TRUE,
1665                         'gz' => TRUE,
1666                         'ha' => TRUE,
1667                         'hb' => TRUE,
1668                         'he' => TRUE,
1669                         'hi' => TRUE,
1670                         'hk' => TRUE,
1671                         'hl' => TRUE,
1672                         'hn' => TRUE,
1673                         'jl' => TRUE,
1674                         'js' => TRUE,
1675                         'jx' => TRUE,
1676                         'ln' => TRUE,
1677                         'mo' => TRUE,
1678                         'nm' => TRUE,
1679                         'nx' => TRUE,
1680                         'qh' => TRUE,
1681                         'sc' => TRUE,
1682                         'sd' => TRUE,
1683                         'sh' => TRUE,
1684                         'sn' => TRUE,
1685                         'sx' => TRUE,
1686                         'tj' => TRUE,
1687                         'tw' => TRUE,
1688                         'xj' => TRUE,
1689                         'xz' => TRUE,
1690                         'yn' => TRUE,
1691                         'zj' => TRUE,
1692                 ),
1693
1694                 // ccTLD: India
1695                 // NIC  : http://www.inregistry.in/
1696                 // Whois: http://www.inregistry.in/whois_search/
1697                 'in' => array(
1698                         // Policies http://www.inregistry.in/policies/
1699                         'ac'   => TRUE,
1700                         'co'   => TRUE,
1701                         'firm' => TRUE,
1702                         'gen'  => TRUE,
1703                         'gov'  => TRUE,
1704                         'ind'  => TRUE,
1705                         'mil'  => TRUE,
1706                         'net'  => TRUE,
1707                         'org'  => TRUE,
1708                         'res'  => TRUE,
1709                         // Reserved Names by the government (for the 2nd level)
1710                         // http://www.inregistry.in/policies/reserved_names
1711                 ),
1712
1713                 // ccTLD: South Korea
1714                 // NIC  : http://www.nic.or.kr/english/
1715                 // Whois: http://whois.nida.or.kr/english/
1716                 'kr' => array(
1717                         // .kr domain policy [appendix 1] : Qualifications for Second Level Domains
1718                         // http://domain.nida.or.kr/eng/policy.jsp
1719
1720                         // Organizational
1721                         'co'  => TRUE,
1722                         'ne ' => TRUE,
1723                         'or ' => TRUE,
1724                         're ' => TRUE,
1725                         'pe'  => TRUE,
1726                         'go ' => TRUE,
1727                         'mil' => TRUE,
1728                         'ac'  => TRUE,
1729                         'hs'  => TRUE,
1730                         'ms'  => TRUE,
1731                         'es'  => TRUE,
1732                         'sc'  => TRUE,
1733                         'kg'  => TRUE,
1734
1735                         // Geographic
1736                         'seoul'     => TRUE,
1737                         'busan'     => TRUE,
1738                         'daegu'     => TRUE,
1739                         'incheon'   => TRUE,
1740                         'gwangju'   => TRUE,
1741                         'daejeon'   => TRUE,
1742                         'ulsan'     => TRUE,
1743                         'gyeonggi'  => TRUE,
1744                         'gangwon'   => TRUE,
1745                         'chungbuk'  => TRUE,
1746                         'chungnam'  => TRUE,
1747                         'jeonbuk'   => TRUE,
1748                         'jeonnam'   => TRUE,
1749                         'gyeongbuk' => TRUE,
1750                         'gyeongnam' => TRUE,
1751                         'jeju'      => TRUE,
1752                 ),
1753
1754                 // ccTLD: Japan
1755                 // NIC  : http://jprs.co.jp/en/
1756                 // Whois: http://whois.jprs.jp/en/
1757                 'jp' => array(
1758                         // Guide to JP Domain Name
1759                         // http://jprs.co.jp/en/jpdomain.html
1760
1761                         // Organizational
1762                         'ac' => TRUE,
1763                         'ad' => TRUE,
1764                         'co' => TRUE,
1765                         'ed' => TRUE,
1766                         'go' => TRUE,
1767                         'gr' => TRUE,
1768                         'lg' => TRUE,
1769                         'ne' => TRUE,
1770                         'or' => TRUE,
1771
1772                         // Geographic
1773                         //
1774                         // Examples for 3rd level domains
1775                         //'kumamoto'  => array(
1776                         //      // http://www.pref.kumamoto.jp/link/list.asp#4
1777                         //      'amakusa'   => TRUE,
1778                         //      'hitoyoshi' => TRUE,
1779                         //      'jonan'     => TRUE,
1780                         //      'kumamoto'  => TRUE,
1781                         //      ...
1782                         //),
1783                         'aichi'     => TRUE,
1784                         'akita'     => TRUE,
1785                         'aomori'    => TRUE,
1786                         'chiba'     => TRUE,
1787                         'ehime'     => TRUE,
1788                         'fukui'     => TRUE,
1789                         'fukuoka'   => TRUE,
1790                         'fukushima' => TRUE,
1791                         'gifu'      => TRUE,
1792                         'gunma'     => TRUE,
1793                         'hiroshima' => TRUE,
1794                         'hokkaido'  => TRUE,
1795                         'hyogo'     => TRUE,
1796                         'ibaraki'   => TRUE,
1797                         'ishikawa'  => TRUE,
1798                         'iwate'     => TRUE,
1799                         'kagawa'    => TRUE,
1800                         'kagoshima' => TRUE,
1801                         'kanagawa'  => TRUE,
1802                         'kawasaki'  => TRUE,
1803                         'kitakyushu'=> TRUE,
1804                         'kobe'      => TRUE,
1805                         'kochi'     => TRUE,
1806                         'kumamoto'  => TRUE,
1807                         'kyoto'     => TRUE,
1808                         'mie'       => TRUE,
1809                         'miyagi'    => TRUE,
1810                         'miyazaki'  => TRUE,
1811                         'nagano'    => TRUE,
1812                         'nagasaki'  => TRUE,
1813                         'nagoya'    => TRUE,
1814                         'nara'      => TRUE,
1815                         'niigata'   => TRUE,
1816                         'oita'      => TRUE,
1817                         'okayama'   => TRUE,
1818                         'okinawa'   => TRUE,
1819                         'osaka'     => TRUE,
1820                         'saga'      => TRUE,
1821                         'saitama'   => TRUE,
1822                         'sapporo'   => TRUE,
1823                         'sendai'    => TRUE,
1824                         'shiga'     => TRUE,
1825                         'shimane'   => TRUE,
1826                         'shizuoka'  => TRUE,
1827                         'tochigi'   => TRUE,
1828                         'tokushima' => TRUE,
1829                         'tokyo'     => TRUE,
1830                         'tottori'   => TRUE,
1831                         'toyama'    => TRUE,
1832                         'wakayama'  => TRUE,
1833                         'yamagata'  => TRUE,
1834                         'yamaguchi' => TRUE,
1835                         'yamanashi' => TRUE,
1836                         'yokohama'  => TRUE,
1837                 ),
1838
1839                 // ccTLD: Mexico
1840                 // NIC  : http://www.nic.mx/
1841                 // Whois: http://www.nic.mx/es/Busqueda.Who_Is
1842                 'mx' => array(
1843                         // Politicas Generales de Nombres de Dominio
1844                         // http://www.nic.mx/es/Politicas?CATEGORY=INDICE
1845                         'com'  => TRUE,
1846                         'edu'  => TRUE,
1847                         'gob'  => TRUE,
1848                         'net'  => TRUE,
1849                         'org'  => TRUE,
1850                 ),
1851
1852                 // ccTLD: Russia
1853                 // NIC  : http://www.cctld.ru/en/
1854                 // Whois: http://www.ripn.net:8080/nic/whois/en/
1855                 'ru' => array(
1856                         // List of Reserved second-level Domain Names
1857                         // http://www.cctld.ru/en/doc/detail.php?id21=20&i21=2
1858
1859                         // Organizational
1860                         'ac'   => TRUE,
1861                         'com'  => TRUE,
1862                         'edu'  => TRUE,
1863                         'gov'  => TRUE,
1864                         'int'  => TRUE,
1865                         'mil'  => TRUE,
1866                         'net'  => TRUE,
1867                         'org'  => TRUE,
1868                         'pp'   => TRUE,
1869                         //'test' => TRUE,
1870
1871                         // Geographic
1872                         'adygeya'     => TRUE,
1873                         'altai'       => TRUE,
1874                         'amur'        => TRUE,
1875                         'amursk'      => TRUE,
1876                         'arkhangelsk' => TRUE,
1877                         'astrakhan'   => TRUE,
1878                         'baikal'      => TRUE,
1879                         'bashkiria'   => TRUE,
1880                         'belgorod'    => TRUE,
1881                         'bir'         => TRUE,
1882                         'bryansk'     => TRUE,
1883                         'buryatia'    => TRUE,
1884                         'cbg'         => TRUE,
1885                         'chel'        => TRUE,
1886                         'chelyabinsk' => TRUE,
1887                         'chita'       => TRUE,
1888                         'chukotka'    => TRUE,
1889                         'chuvashia'   => TRUE,
1890                         'cmw'         => TRUE,
1891                         'dagestan'    => TRUE,
1892                         'dudinka'     => TRUE,
1893                         'e-burg'      => TRUE,
1894                         'fareast'     => TRUE,
1895                         'grozny'      => TRUE,
1896                         'irkutsk'     => TRUE,
1897                         'ivanovo'     => TRUE,
1898                         'izhevsk'     => TRUE,
1899                         'jamal'       => TRUE,
1900                         'jar'         => TRUE,
1901                         'joshkar-ola' => TRUE,
1902                         'k-uralsk'    => TRUE,
1903                         'kalmykia'    => TRUE,
1904                         'kaluga'      => TRUE,
1905                         'kamchatka'   => TRUE,
1906                         'karelia'     => TRUE,
1907                         'kazan'       => TRUE,
1908                         'kchr'        => TRUE,
1909                         'kemerovo'    => TRUE,
1910                         'khabarovsk'  => TRUE,
1911                         'khakassia'   => TRUE,
1912                         'khv'         => TRUE,
1913                         'kirov'       => TRUE,
1914                         'kms'         => TRUE,
1915                         'koenig'      => TRUE,
1916                         'komi'        => TRUE,
1917                         'kostroma'    => TRUE,
1918                         'krasnoyarsk' => TRUE,
1919                         'kuban'       => TRUE,
1920                         'kurgan'      => TRUE,
1921                         'kursk'       => TRUE,
1922                         'kustanai'    => TRUE,
1923                         'kuzbass'     => TRUE,
1924                         'lipetsk'     => TRUE,
1925                         'magadan'     => TRUE,
1926                         'magnitka'    => TRUE,
1927                         'mari-el'     => TRUE,
1928                         'mari'        => TRUE,
1929                         'marine'      => TRUE,
1930                         'mordovia'    => TRUE,
1931                         'mosreg'      => TRUE,
1932                         'msk'         => TRUE,
1933                         'murmansk'    => TRUE,
1934                         'mytis'       => TRUE,
1935                         'nakhodka'    => TRUE,
1936                         'nalchik'     => TRUE,
1937                         'nkz'         => TRUE,
1938                         'nnov'        => TRUE,
1939                         'norilsk'     => TRUE,
1940                         'nov'         => TRUE,
1941                         'novosibirsk' => TRUE,
1942                         'nsk'         => TRUE,
1943                         'omsk'        => TRUE,
1944                         'orenburg'    => TRUE,
1945                         'oryol'       => TRUE,
1946                         'oskol'       => TRUE,
1947                         'palana'      => TRUE,
1948                         'penza'       => TRUE,
1949                         'perm'        => TRUE,
1950                         'pskov'       => TRUE,
1951                         'ptz'         => TRUE,
1952                         'pyatigorsk'  => TRUE,
1953                         'rnd'         => TRUE,
1954                         'rubtsovsk'   => TRUE,
1955                         'ryazan'      => TRUE,
1956                         'sakhalin'    => TRUE,
1957                         'samara'      => TRUE,
1958                         'saratov'     => TRUE,
1959                         'simbirsk'    => TRUE,
1960                         'smolensk'    => TRUE,
1961                         'snz'         => TRUE,
1962                         'spb'         => TRUE,
1963                         'stavropol'   => TRUE,
1964                         'stv'         => TRUE,
1965                         'surgut'      => TRUE,
1966                         'syzran'      => TRUE,
1967                         'tambov'      => TRUE,
1968                         'tatarstan'   => TRUE,
1969                         'tom'         => TRUE,
1970                         'tomsk'       => TRUE,
1971                         'tsaritsyn'   => TRUE,
1972                         'tsk'         => TRUE,
1973                         'tula'        => TRUE,
1974                         'tuva'        => TRUE,
1975                         'tver'        => TRUE,
1976                         'tyumen'      => TRUE,
1977                         'udm'         => TRUE,
1978                         'udmurtia'    => TRUE,
1979                         'ulan-ude'    => TRUE,
1980                         'vdonsk'      => TRUE,
1981                         'vladikavkaz' => TRUE,
1982                         'vladimir'    => TRUE,
1983                         'vladivostok' => TRUE,
1984                         'volgograd'   => TRUE,
1985                         'vologda'     => TRUE,
1986                         'voronezh'    => TRUE,
1987                         'vrn'         => TRUE,
1988                         'vyatka'      => TRUE,
1989                         'yakutia'     => TRUE,
1990                         'yamal'       => TRUE,
1991                         'yaroslavl'   => TRUE,
1992                         'yekaterinburg'     => TRUE,
1993                         'yuzhno-sakhalinsk' => TRUE,
1994                         'zgrad'       => TRUE,
1995                 ),
1996
1997                 // ccTLD: Seychelles
1998                 // NIC  : http://www.nic.sc/
1999                 // Whois: (Not available)
2000                 'sc' => array(
2001                         // http://www.nic.sc/policies.html
2002                         'com' => TRUE,
2003                         'edu' => TRUE,
2004                         'gov' => TRUE,
2005                         'net' => TRUE,
2006                         'org' => TRUE,
2007                 ),
2008
2009                 // ccTLD: Taiwan
2010                 // NIC  : http://www.twnic.net.tw/
2011                 // Whois: http://www.twnic.net.tw/
2012                 'tw' => array(
2013                         // Guidelines for Administration of Domain Name Registration
2014                         // http://www.twnic.net.tw/english/dn/dn_02.htm
2015                         // II. Types of TWNIC Domain Names and Application Requirements
2016                         // http://www.twnic.net.tw/english/dn/dn_02_b.htm
2017                         'club' => TRUE,
2018                         'com'  => TRUE,
2019                         'ebiz' => TRUE,
2020                         'edu'  => TRUE,
2021                         'game' => TRUE,
2022                         'gov'  => TRUE,
2023                         'idv'  => TRUE,
2024                         'mil'  => TRUE,
2025                         'net'  => TRUE,
2026                         'org'  => TRUE,
2027                         // Reserved words for the 2nd level
2028                         // http://mydn.twnic.net.tw/en/dn02/INDEX.htm
2029                 ),
2030
2031                 // ccTLD: Tanzania
2032                 // NIC  : http://www.psg.com/dns/tz/
2033                 // Whois: (Not available)
2034                 'tz' => array(
2035                         //  TZ DOMAIN NAMING STRUCTURE
2036                         // http://www.psg.com/dns/tz/tz.txt
2037                         'ac' => TRUE,
2038                         'co' => TRUE,
2039                         'go' => TRUE,
2040                         'ne' => TRUE,
2041                         'or' => TRUE,
2042                 ),
2043
2044                 // ccTLD: Ukraine
2045                 // NIC  : http://www.nic.net.ua/
2046                 // Whois: http://whois.com.ua/
2047                 'ua' => array(
2048                         // policy for alternative 2nd level domain names (a2ld)
2049                         // http://www.nic.net.ua/doc/a2ld
2050                         // http://whois.com.ua/
2051                         'cherkassy'  => TRUE,
2052                         'chernigov'  => TRUE,
2053                         'chernovtsy' => TRUE,
2054                         'ck'         => TRUE,
2055                         'cn'         => TRUE,
2056                         'com'        => TRUE,
2057                         'crimea'     => TRUE,
2058                         'cv'         => TRUE,
2059                         'dn'         => TRUE,
2060                         'dnepropetrovsk' => TRUE,
2061                         'donetsk'    => TRUE,
2062                         'dp'         => TRUE,
2063                         'edu'        => TRUE,
2064                         'gov'        => TRUE,
2065                         'if'         => TRUE,
2066                         'ivano-frankivsk' => TRUE,
2067                         'kh'         => TRUE,
2068                         'kharkov'    => TRUE,
2069                         'kherson'    => TRUE,
2070                         'kiev'       => TRUE,
2071                         'kirovograd' => TRUE,
2072                         'km'         => TRUE,
2073                         'kr'         => TRUE,
2074                         'ks'         => TRUE,
2075                         'lg'         => TRUE,
2076                         'lugansk'    => TRUE,
2077                         'lutsk'      => TRUE,
2078                         'lviv'       => TRUE,
2079                         'mk'         => TRUE,
2080                         'net'        => TRUE,
2081                         'nikolaev'   => TRUE,
2082                         'od'         => TRUE,
2083                         'odessa'     => TRUE,
2084                         'org'        => TRUE,
2085                         'pl'         => TRUE,
2086                         'poltava'    => TRUE,
2087                         'rovno'      => TRUE,
2088                         'rv'         => TRUE,
2089                         'sebastopol' => TRUE,
2090                         'sumy'       => TRUE,
2091                         'te'         => TRUE,
2092                         'ternopil'   => TRUE,
2093                         'uz'         => TRUE,
2094                         'uzhgorod'   => TRUE,
2095                         'vinnica'    => TRUE,
2096                         'vn'         => TRUE,
2097                         'zaporizhzhe' => TRUE,
2098                         'zhitomir'   => TRUE,
2099                         'zp'         => TRUE,
2100                         'zt'         => TRUE,
2101                 ),
2102
2103                 // ccTLD: United Kingdom
2104                 // NIC  : http://www.nic.uk/
2105                 'uk' => array(
2106                         // Second Level Domains
2107                         // http://www.nic.uk/registrants/aboutdomainnames/sld/
2108                         'co'     => TRUE,
2109                         'ltd'    => TRUE,
2110                         'me'     => TRUE,
2111                         'net'    => TRUE,
2112                         'nic'    => TRUE,
2113                         'org'    => TRUE,
2114                         'plc'    => TRUE,
2115                         'sch'    => TRUE,
2116                         
2117                         // Delegated Second Level Domains
2118                         // http://www.nic.uk/registrants/aboutdomainnames/sld/delegated/
2119                         'ac'     => TRUE,
2120                         'gov'    => TRUE,
2121                         'mil'    => TRUE,
2122                         'mod'    => TRUE,
2123                         'nhs'    => TRUE,
2124                         'police' => TRUE,
2125                 ),
2126
2127                 // ccTLD: United States of America
2128                 // NIC  : http://nic.us/
2129                 // Whois: http://whois.us/
2130                 'us' => array(
2131                         // See RFC1480
2132
2133                         // Organizational
2134                         'dni',
2135                         'fed',
2136                         'isa',
2137                         'kids',
2138                         'nsn',
2139
2140                         // Geographical
2141                         // United States Postal Service: State abbreviations (for postal codes)
2142                         // http://www.usps.com/ncsc/lookups/abbreviations.html
2143                         'ak' => TRUE, // Alaska
2144                         'al' => TRUE, // Alabama
2145                         'ar' => TRUE, // Arkansas
2146                         'as' => TRUE, // American samoa
2147                         'az' => TRUE, // Arizona
2148                         'ca' => TRUE, // California
2149                         'co' => TRUE, // Colorado
2150                         'ct' => TRUE, // Connecticut
2151                         'dc' => TRUE, // District of Columbia
2152                         'de' => TRUE, // Delaware
2153                         'fl' => TRUE, // Florida
2154                         'fm' => TRUE, // Federated states of Micronesia
2155                         'ga' => TRUE, // Georgia
2156                         'gu' => TRUE, // Guam
2157                         'hi' => TRUE, // Hawaii
2158                         'ia' => TRUE, // Iowa
2159                         'id' => TRUE, // Idaho
2160                         'il' => TRUE, // Illinois
2161                         'in' => TRUE, // Indiana
2162                         'ks' => TRUE, // Kansas
2163                         'ky' => TRUE, // Kentucky
2164                         'la' => TRUE, // Louisiana
2165                         'ma' => TRUE, // Massachusetts
2166                         'md' => TRUE, // Maryland
2167                         'me' => TRUE, // Maine
2168                         'mh' => TRUE, // Marshall Islands
2169                         'mi' => TRUE, // Michigan
2170                         'mn' => TRUE, // Minnesota
2171                         'mo' => TRUE, // Missouri
2172                         'mp' => TRUE, // Northern mariana islands
2173                         'ms' => TRUE, // Mississippi
2174                         'mt' => TRUE, // Montana
2175                         'nc' => TRUE, // North Carolina
2176                         'nd' => TRUE, // North Dakota
2177                         'ne' => TRUE, // Nebraska
2178                         'nh' => TRUE, // New Hampshire
2179                         'nj' => TRUE, // New Jersey
2180                         'nm' => TRUE, // New Mexico
2181                         'nv' => TRUE, // Nevada
2182                         'ny' => TRUE, // New York
2183                         'oh' => TRUE, // Ohio
2184                         'ok' => TRUE, // Oklahoma
2185                         'or' => TRUE, // Oregon
2186                         'pa' => TRUE, // Pennsylvania
2187                         'pr' => TRUE, // Puerto Rico
2188                         'pw' => TRUE, // Palau
2189                         'ri' => TRUE, // Rhode Island
2190                         'sc' => TRUE, // South Carolina
2191                         'sd' => TRUE, // South Dakota
2192                         'tn' => TRUE, // Tennessee
2193                         'tx' => TRUE, // Texas
2194                         'ut' => TRUE, // Utah
2195                         'va' => TRUE, // Virginia
2196                         'vi' => TRUE, // Virgin Islands
2197                         'vt' => TRUE, // Vermont
2198                         'wa' => TRUE, // Washington
2199                         'wi' => TRUE, // Wisconsin
2200                         'wv' => TRUE, // West Virginia
2201                         'wy' => TRUE, // Wyoming
2202                 ),
2203
2204                 // ccTLD: South Africa
2205                 // NIC  : http://www.zadna.org.za/
2206                 // Whois: 
2207                 //   ac.za  http://www.tenet.ac.za/cgi/cgi_domainquery.exe
2208                 //   co.za  http://co.za/whois.shtml
2209                 //   gov.za http://dnsadmin.gov.za/
2210                 //   org.za http://www.org.za/
2211                 'za' => array(
2212                         // Second-level subdomains of .ZA
2213                         // http://www.zadna.org.za/slds.html
2214                         'ac'   => TRUE,
2215                         'city' => TRUE,
2216                         'co'   => TRUE,
2217                         'edu'  => TRUE,
2218                         'gov'  => TRUE,
2219                         'law'  => TRUE,
2220                         'mil'  => TRUE,
2221                         'nom'  => TRUE,
2222                         'org'  => TRUE,
2223                         'school' => array(
2224                                 // Provincial Domains
2225                                 // http://www.esn.org.za/dns/
2226                                 'ecape' => TRUE,
2227                                 'fs.'   => TRUE,
2228                                 'gp'    => TRUE,
2229                                 'kzn'   => TRUE,
2230                                 'lp'    => TRUE,
2231                                 'mpm'   => TRUE,
2232                                 'ncape' => TRUE,
2233                                 'nw'    => TRUE,
2234                                 'wcape' => TRUE,
2235                         ),
2236                 ),
2237         );
2238
2239         if (! is_string($fqdn)) return '';
2240         if (is_ip($fqdn))       return $fqdn;
2241
2242         $result  = array();
2243         $dcursor = & $domain;
2244         $array   = array_reverse(explode('.', $fqdn));
2245         $i = 0;
2246         while(TRUE) {
2247                 if (! isset($array[$i])) break;
2248                 $acursor = $array[$i];
2249                 if (is_array($dcursor) && isset($dcursor[$acursor])) {
2250                         $result[] = & $array[$i];
2251                         $dcursor  = & $dcursor[$acursor];
2252                 } else {
2253                         if (! $parent && isset($acursor)) {
2254                                 $result[] = & $array[$i];       // Whois servers must know this subdomain
2255                         }
2256                         break;
2257                 }
2258                 ++$i;
2259         }
2260
2261         // Implicit responsibility: Top-Level-Domains must not be yours
2262         // 'bar.foo.something' => 'foo.something'
2263         if ($implicit && count($result) == 1 && count($array) > 1) {
2264                 $result[] = & $array[1];
2265         }
2266
2267         return $result ? implode('.', array_reverse($result)) : '';
2268 }
2269
2270
2271 // ---------------------
2272 // Exit
2273
2274 // Freeing memories
2275 function spam_dispose()
2276 {
2277         get_blocklist(NULL);
2278 }
2279
2280 // Common bahavior for blocking
2281 // NOTE: Call this function from various blocking feature, to disgueise the reason 'why blocked'
2282 function spam_exit($mode = '', $data = array())
2283 {
2284         $exit = TRUE;
2285
2286         switch ($mode) {
2287                 case '':
2288                         echo("\n");
2289                         break;
2290                 case 'dump':
2291                         echo('<pre>' . "\n");
2292                         echo htmlspecialchars(var_export($data, TRUE));
2293                         echo('</pre>' . "\n");
2294                         break;
2295         };
2296
2297         if ($exit) exit;        // Force exit
2298 }
2299
2300
2301 // ---------------------
2302 // Simple filtering
2303
2304 // TODO: Record them
2305 // Simple/fast spam filter ($target: 'a string' or an array())
2306 function pkwk_spamfilter($action, $page, $target = array('title' => ''), $method = array(), $exitmode = '')
2307 {
2308         $progress = check_uri_spam($target, $method);
2309
2310         if (empty($progress['is_spam'])) {
2311                 spam_dispose();
2312         } else {
2313
2314 // TODO: detect encoding from $target for mbstring functions
2315 //              $tmp = array();
2316 //              foreach(array_keys($target) as $key) {
2317 //                      $tmp[strings($key, 0, FALSE, TRUE)] = strings($target[$key], 0, FALSE, TRUE);   // Removing "\0" etc
2318 //              }
2319 //              $target = & $tmp;
2320
2321                 pkwk_spamnotify($action, $page, $target, $progress, $method);
2322                 spam_exit($exitmode, $progress);
2323         }
2324 }
2325
2326 // ---------------------
2327 // PukiWiki original
2328
2329 // Mail to administrator(s)
2330 function pkwk_spamnotify($action, $page, $target = array('title' => ''), $progress = array(), $method = array())
2331 {
2332         global $notify, $notify_subject;
2333
2334         if (! $notify) return;
2335
2336         $asap = isset($method['asap']);
2337
2338         $summary['ACTION']  = 'Blocked by: ' . summarize_spam_progress($progress, TRUE);
2339         if (! $asap) {
2340                 $summary['METRICS'] = summarize_spam_progress($progress);
2341         }
2342
2343         $tmp = summarize_detail_badhost($progress);
2344         if ($tmp != '') $summary['DETAIL_BADHOST'] = $tmp;
2345
2346         $tmp = summarize_detail_newtral($progress);
2347         if (! $asap && $tmp != '') $summary['DETAIL_NEUTRAL_HOST'] = $tmp;
2348
2349         $summary['COMMENT'] = $action;
2350         $summary['PAGE']    = '[blocked] ' . (is_pagename($page) ? $page : '');
2351         $summary['URI']     = get_script_uri() . '?' . rawurlencode($page);
2352         $summary['USER_AGENT']  = TRUE;
2353         $summary['REMOTE_ADDR'] = TRUE;
2354         pkwk_mail_notify($notify_subject,  var_export($target, TRUE), $summary, TRUE);
2355 }
2356
2357 ?>