OSDN Git Service

81654542cb514bb175442d02bf0cdb0dbae76c65
[pukiwiki/pukiwiki_sandbox.git] / spam / spam.php
1 <?php
2 // $Id: spam.php,v 1.164 2007/05/18 14:12:40 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 =preg_replace(
47                 // Remove a newline and spaces
48                 '# => \n *array \(#', ' => array (',
49                 var_export($expression, TRUE)
50         );
51
52         if ($ignore_numeric_keys) {
53                 $result =preg_replace(
54                         // Remove numeric keys
55                         '#^( *)[0-9]+ => #m', '$1',
56                         $result
57                 );
58         }
59
60         if ($return) {
61                 return $result;
62         } else {
63                 echo   $result;
64                 return NULL;
65         }
66 }
67
68 // Remove redundant values from array()
69 function array_unique_recursive($array = array())
70 {
71         if (! is_array($array)) return $array;
72
73         $tmp = array();
74         foreach($array as $key => $value){
75                 if (is_array($value)) {
76                         $array[$key] = array_unique_recursive($value);
77                 } else {
78                         if (isset($tmp[$value])) {
79                                 unset($array[$key]);
80                         } else {
81                                 $tmp[$value] = TRUE;
82                         }
83                 }
84         }
85
86         return $array;
87 }
88
89 // Renumber all numeric keys from 0
90 function array_renumber_numeric_keys(& $array)
91 {
92         if (! is_array($array)) return $array;
93
94         $count = -1;
95         $tmp = array();
96         foreach($array as $key => $value){
97                 if (is_array($value)) array_renumber_numeric_keys($array[$key]);        // Recurse
98                 if (is_numeric($key)) $tmp[$key] = ++$count;
99         }
100         array_rename_keys($array, $tmp);
101
102         return $array;
103 }
104
105 // Roughly strings(1) using PCRE
106 // This function is useful to:
107 //   * Reduce the size of data, from removing unprintable binary data
108 //   * Detect _bare_strings_ from binary data
109 // References:
110 //   http://www.freebsd.org/cgi/man.cgi?query=strings (Man-page of GNU strings)
111 //   http://www.pcre.org/pcre.txt
112 function strings($binary = '', $min_len = 4, $ignore_space = FALSE)
113 {
114         if ($ignore_space) {
115                 $binary = preg_replace(
116                         array(
117                                 '/(?:[^[:graph:] \t\n]|[\r])+/s',
118                                 '/[ \t]{2,}/',
119                                 '/^[ \t]/m',
120                                 '/[ \t]$/m',
121                         ),
122                         array(
123                                 "\n",
124                                 ' ',
125                                 '',
126                                 ''
127                         ),
128                          $binary);
129         } else {
130                 $binary = preg_replace('/(?:[^[:graph:][:space:]]|[\r])+/s', "\n", $binary);
131         }
132
133         if ($min_len > 1) {
134                 $min_len = min(1024, intval($min_len));
135                 $binary = 
136                         implode("\n",
137                                 preg_grep('/^.{' . $min_len . ',}/S',
138                                         explode("\n", $binary)
139                                 )
140                         );
141         }
142
143         return $binary;
144 }
145
146 // Reverse $string with specified delimiter
147 function delimiter_reverse($string = 'foo.bar.example.com', $from_delim = '.', $to_delim = '.')
148 {
149         if (! is_string($string) || ! is_string($from_delim) || ! is_string($to_delim))
150                 return $string;
151
152         // com.example.bar.foo
153         return implode($to_delim, array_reverse(explode($from_delim, $string)));
154 }
155
156
157 // ---------------------
158 // URI pickup
159
160 // Return an array of URIs in the $string
161 // [OK] http://nasty.example.org#nasty_string
162 // [OK] http://nasty.example.org:80/foo/xxx#nasty_string/bar
163 // [OK] ftp://nasty.example.org:80/dfsdfs
164 // [OK] ftp://cnn.example.com&story=breaking_news@10.0.0.1/top_story.htm (from RFC3986)
165 function uri_pickup($string = '')
166 {
167         if (! is_string($string)) return array();
168
169         // Not available for: IDN(ignored)
170         $array = array();
171         preg_match_all(
172                 // scheme://userinfo@host:port/path/or/pathinfo/maybefile.and?query=string#fragment
173                 // Refer RFC3986 (Regex below is not strict)
174                 '#(\b[a-z][a-z0-9.+-]{1,8}):[/\\\]+' .  // 1: Scheme
175                 '(?:' .
176                         '([^\s<>"\'\[\]/\#?@]*)' .              // 2: Userinfo (Username)
177                 '@)?' .
178                 '(' .
179                         // 3: Host
180                         '\[[0-9a-f:.]+\]' . '|' .                               // IPv6([colon-hex and dot]): RFC2732
181                         '(?:[0-9]{1,3}\.){3}[0-9]{1,3}' . '|' . // IPv4(dot-decimal): 001.22.3.44
182                         '[a-z0-9][a-z0-9.-]+[a-z0-9]' .                 // hostname(FQDN) : foo.example.org
183                 ')' .
184                 '(?::([0-9]*))?' .                                      // 4: Port
185                 '((?:/+[^\s<>"\'\[\]/\#]+)*/+)?' .      // 5: Directory path or path-info
186                 '([^\s<>"\'\[\]\#?]+)?' .                       // 6: File?
187                 '(?:\?([^\s<>"\'\[\]\#]+))?' .          // 7: Query string
188                 '(?:\#([a-z0-9._~%!$&\'()*+,;=:@-]*))?' .       // 8: Fragment
189                 '#i',
190                  $string, $array, PREG_SET_ORDER | PREG_OFFSET_CAPTURE
191         );
192
193         // Format the $array
194         static $parts = array(
195                 1 => 'scheme', 2 => 'userinfo', 3 => 'host', 4 => 'port',
196                 5 => 'path', 6 => 'file', 7 => 'query', 8 => 'fragment'
197         );
198         $default = array('');
199         foreach(array_keys($array) as $uri) {
200                 $_uri = & $array[$uri];
201                 array_rename_keys($_uri, $parts, TRUE, $default);
202                 $offset = $_uri['scheme'][1]; // Scheme's offset = URI's offset
203                 foreach(array_keys($_uri) as $part) {
204                         $_uri[$part] = & $_uri[$part][0];       // Remove offsets
205                 }
206         }
207
208         foreach(array_keys($array) as $uri) {
209                 $_uri = & $array[$uri];
210                 if ($_uri['scheme'] === '') {
211                         unset($array[$uri]);    // Considererd harmless
212                         continue;
213                 }
214                 unset($_uri[0]); // Matched string itself
215                 $_uri['area']['offset'] = $offset;      // Area offset for area_measure()
216         }
217
218         return $array;
219 }
220
221 // Normalize an array of URI arrays
222 // NOTE: Give me the uri_pickup() results
223 function uri_pickup_normalize(& $pickups, $destructive = TRUE)
224 {
225         if (! is_array($pickups)) return $pickups;
226
227         if ($destructive) {
228                 foreach (array_keys($pickups) as $key) {
229                         $_key = & $pickups[$key];
230                         $_key['scheme']   = isset($_key['scheme']) ? scheme_normalize($_key['scheme']) : '';
231                         $_key['host']     = isset($_key['host'])     ? host_normalize($_key['host']) : '';
232                         $_key['port']     = isset($_key['port'])       ? port_normalize($_key['port'], $_key['scheme'], FALSE) : '';
233                         $_key['path']     = isset($_key['path'])     ? strtolower(path_normalize($_key['path'])) : '';
234                         $_key['file']     = isset($_key['file'])     ? file_normalize($_key['file']) : '';
235                         $_key['query']    = isset($_key['query'])    ? query_normalize($_key['query']) : '';
236                         $_key['fragment'] = isset($_key['fragment']) ? strtolower($_key['fragment']) : '';
237                 }
238         } else {
239                 foreach (array_keys($pickups) as $key) {
240                         $_key = & $pickups[$key];
241                         $_key['scheme']   = isset($_key['scheme']) ? scheme_normalize($_key['scheme']) : '';
242                         $_key['host']     = isset($_key['host'])   ? strtolower($_key['host']) : '';
243                         $_key['port']     = isset($_key['port'])   ? port_normalize($_key['port'], $_key['scheme'], FALSE) : '';
244                         $_key['path']     = isset($_key['path'])   ? path_normalize($_key['path']) : '';
245                 }
246         }
247
248         return $pickups;
249 }
250
251 // An URI array => An URI (See uri_pickup())
252 // USAGE:
253 //      $pickups = uri_pickup('a string include some URIs');
254 //      $uris = array();
255 //      foreach (array_keys($pickups) as $key) {
256 //              $uris[$key] = uri_pickup_implode($pickups[$key]);
257 //      }
258 function uri_pickup_implode($uri = array())
259 {
260         if (empty($uri) || ! is_array($uri)) return NULL;
261
262         $tmp = array();
263         if (isset($uri['scheme']) && $uri['scheme'] !== '') {
264                 $tmp[] = & $uri['scheme'];
265                 $tmp[] = '://';
266         }
267         if (isset($uri['userinfo']) && $uri['userinfo'] !== '') {
268                 $tmp[] = & $uri['userinfo'];
269                 $tmp[] = '@';
270         }
271         if (isset($uri['host']) && $uri['host'] !== '') {
272                 $tmp[] = & $uri['host'];
273         }
274         if (isset($uri['port']) && $uri['port'] !== '') {
275                 $tmp[] = ':';
276                 $tmp[] = & $uri['port'];
277         }
278         if (isset($uri['path']) && $uri['path'] !== '') {
279                 $tmp[] = & $uri['path'];
280         }
281         if (isset($uri['file']) && $uri['file'] !== '') {
282                 $tmp[] = & $uri['file'];
283         }
284         if (isset($uri['query']) && $uri['query'] !== '') {
285                 $tmp[] = '?';
286                 $tmp[] = & $uri['query'];
287         }
288         if (isset($uri['fragment']) && $uri['fragment'] !== '') {
289                 $tmp[] = '#';
290                 $tmp[] = & $uri['fragment'];
291         }
292
293         return implode('', $tmp);
294 }
295
296 // $array['something'] => $array['wanted']
297 function array_rename_keys(& $array, $keys = array('from' => 'to'), $force = FALSE, $default = '')
298 {
299         if (! is_array($array) || ! is_array($keys)) return FALSE;
300
301         // Nondestructive test
302         if (! $force)
303                 foreach(array_keys($keys) as $from)
304                         if (! isset($array[$from]))
305                                 return FALSE;
306
307         foreach($keys as $from => $to) {
308                 if ($from === $to) continue;
309                 if (! $force || isset($array[$from])) {
310                         $array[$to] = & $array[$from];
311                         unset($array[$from]);
312                 } else  {
313                         $array[$to] = $default;
314                 }
315         }
316
317         return TRUE;
318 }
319
320 // ---------------------
321 // Area pickup
322
323 // Pickup all of markup areas
324 function area_pickup($string = '', $method = array())
325 {
326         $area = array();
327         if (empty($method)) return $area;
328
329         // Anchor tag pair by preg_match and preg_match_all()
330         // [OK] <a href></a>
331         // [OK] <a href=  >Good site!</a>
332         // [OK] <a href= "#" >test</a>
333         // [OK] <a href="http://nasty.example.com">visit http://nasty.example.com/</a>
334         // [OK] <a href=\'http://nasty.example.com/\' >discount foobar</a> 
335         // [NG] <a href="http://ng.example.com">visit http://ng.example.com _not_ended_
336         $regex = '#<a\b[^>]*\bhref\b[^>]*>.*?</a\b[^>]*(>)#is';
337         if (isset($method['area_anchor'])) {
338                 $areas = array();
339                 $count = isset($method['asap']) ?
340                         preg_match($regex, $string) :
341                         preg_match_all($regex, $string, $areas);
342                 if (! empty($count)) $area['area_anchor'] = $count;
343         }
344         if (isset($method['uri_anchor'])) {
345                 $areas = array();
346                 preg_match_all($regex, $string, $areas, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
347                 foreach(array_keys($areas) as $_area) {
348                         $areas[$_area] =  array(
349                                 $areas[$_area][0][1], // Area start (<a href>)
350                                 $areas[$_area][1][1], // Area end   (</a>)
351                         );
352                 }
353                 if (! empty($areas)) $area['uri_anchor'] = $areas;
354         }
355
356         // phpBB's "BBCode" pair by preg_match and preg_match_all()
357         // [OK] [url][/url]
358         // [OK] [url]http://nasty.example.com/[/url]
359         // [OK] [link]http://nasty.example.com/[/link]
360         // [OK] [url=http://nasty.example.com]visit http://nasty.example.com/[/url]
361         // [OK] [link http://nasty.example.com/]buy something[/link]
362         $regex = '#\[(url|link)\b[^\]]*\].*?\[/\1\b[^\]]*(\])#is';
363         if (isset($method['area_bbcode'])) {
364                 $areas = array();
365                 $count = isset($method['asap']) ?
366                         preg_match($regex, $string) :
367                         preg_match_all($regex, $string, $areas, PREG_SET_ORDER);
368                 if (! empty($count)) $area['area_bbcode'] = $count;
369         }
370         if (isset($method['uri_bbcode'])) {
371                 $areas = array();
372                 preg_match_all($regex, $string, $areas, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
373                 foreach(array_keys($areas) as $_area) {
374                         $areas[$_area] = array(
375                                 $areas[$_area][0][1], // Area start ([url])
376                                 $areas[$_area][2][1], // Area end   ([/url])
377                         );
378                 }
379                 if (! empty($areas)) $area['uri_bbcode'] = $areas;
380         }
381
382         // Various Wiki syntax
383         // [text_or_uri>text_or_uri]
384         // [text_or_uri:text_or_uri]
385         // [text_or_uri|text_or_uri]
386         // [text_or_uri->text_or_uri]
387         // [text_or_uri text_or_uri] // MediaWiki
388         // MediaWiki: [http://nasty.example.com/ visit http://nasty.example.com/]
389
390         return $area;
391 }
392
393 // If in doubt, it's a little doubtful
394 // if (Area => inside <= Area) $brief += -1
395 function area_measure($areas, & $array, $belief = -1, $a_key = 'area', $o_key = 'offset')
396 {
397         if (! is_array($areas) || ! is_array($array)) return;
398
399         $areas_keys = array_keys($areas);
400         foreach(array_keys($array) as $u_index) {
401                 $offset = isset($array[$u_index][$o_key]) ?
402                         intval($array[$u_index][$o_key]) : 0;
403                 foreach($areas_keys as $a_index) {
404                         if (isset($array[$u_index][$a_key])) {
405                                 $offset_s = intval($areas[$a_index][0]);
406                                 $offset_e = intval($areas[$a_index][1]);
407                                 // [Area => inside <= Area]
408                                 if ($offset_s < $offset && $offset < $offset_e) {
409                                         $array[$u_index][$a_key] += $belief;
410                                 }
411                         }
412                 }
413         }
414 }
415
416 // ---------------------
417 // Spam-uri pickup
418
419 // Domain exposure callback (See spam_uri_pickup_preprocess())
420 // http://victim.example.org/?foo+site:nasty.example.com+bar
421 // => http://nasty.example.com/?refer=victim.example.org
422 // NOTE: 'refer=' is not so good for (at this time).
423 // Consider about using IP address of the victim, try to avoid that.
424 function _preg_replace_callback_domain_exposure($matches = array())
425 {
426         $result = '';
427
428         // Preserve the victim URI as a complicity or ...
429         if (isset($matches[5])) {
430                 $result =
431                         $matches[1] . '://' .   // scheme
432                         $matches[2] . '/' .             // victim.example.org
433                         $matches[3];                    // The rest of all (before victim)
434         }
435
436         // Flipped URI
437         if (isset($matches[4])) {
438                 $result = 
439                         $matches[1] . '://' .   // scheme
440                         $matches[4] .                   // nasty.example.com
441                         '/?refer=' . strtolower($matches[2]) .  // victim.example.org
442                         ' ' . $result;
443         }
444
445         return $result;
446 }
447
448 // Preprocess: rawurldecode() and adding space(s) and something
449 // to detect/count some URIs _if possible_
450 // NOTE: It's maybe danger to var_dump(result). [e.g. 'javascript:']
451 // [OK] http://victim.example.org/?site:nasty.example.org
452 // [OK] http://victim.example.org/nasty.example.org
453 // [OK] http://victim.example.org/go?http%3A%2F%2Fnasty.example.org
454 // [OK] http://victim.example.org/http://nasty.example.org
455 function spam_uri_pickup_preprocess($string = '')
456 {
457         if (! is_string($string)) return '';
458
459         $string = rawurldecode($string);
460
461         // Domain exposure (simple)
462         // http://victim.example.org/nasty.example.org/path#frag
463         // => http://nasty.example.org/?refer=victim.example.org and original
464         $string = preg_replace(
465                 '#h?ttp://' .
466                 '(' .
467                         'ime\.nu' . '|' .       // 2ch.net
468                         'ime\.st' . '|' .       // 2ch.net
469                         'link\.toolbot\.com' . '|' .
470                         'urlx\.org' .
471                 ')' .
472                 '/([a-z0-9.%_-]+\.[a-z0-9.%_-]+)#i',    // nasty.example.org
473                 'http://$2/?refer=$1 $0',                               // Preserve $0 or remove?
474                 $string
475         );
476
477         // Domain exposure (gate-big5)
478         // http://victim.example.org/gate/big5/nasty.example.org/path
479         // => http://nasty.example.org/?refer=victim.example.org and original
480         $string = preg_replace(
481                 '#h?ttp://' .
482                 '(' .
483                         'big5.51job.com'         . '|' .
484                         'big5.china.com'         . '|' .
485                         'big5.xinhuanet.com' . '|' .
486                 ')' .
487                 '/gate/big5' .
488                 '/([a-z0-9.%_-]+\.[a-z0-9.%_-]+)' .
489                  '#i',  // nasty.example.org
490                 'http://$2/?refer=$1 $0',                               // Preserve $0 or remove?
491                 $string
492         );
493
494         // Domain exposure (See _preg_replace_callback_domain_exposure())
495         $string = preg_replace_callback(
496                 array(
497                         '#(http)://' .
498                         '(' .
499                                 // Something Google: http://www.google.com/supported_domains
500                                 '(?:[a-z0-9.]+\.)?google\.[a-z]{2,3}(?:\.[a-z]{2})?' .
501                                 '|' .
502                                 // AltaVista
503                                 '(?:[a-z0-9.]+\.)?altavista.com' .
504                                 
505                         ')' .
506                         '/' .
507                         '([a-z0-9?=&.%_/\'\\\+-]+)' .                           // path/?query=foo+bar+
508                         '\bsite:([a-z0-9.%_-]+\.[a-z0-9.%_-]+)' .       // site:nasty.example.com
509                         //'()' .        // Preserve or remove?
510                         '#i',
511                 ),
512                 '_preg_replace_callback_domain_exposure',
513                 $string
514         );
515
516         // URI exposure (uriuri => uri uri)
517         $string = preg_replace(
518                 array(
519                         '#(?<! )(?:https?|ftp):/#i',
520                 //      '#[a-z][a-z0-9.+-]{1,8}://#i',
521                 //      '#[a-z][a-z0-9.+-]{1,8}://#i'
522                 ),
523                 ' $0',
524                 $string
525         );
526
527         return $string;
528 }
529
530 // Main function of spam-uri pickup,
531 // A wrapper function of uri_pickup()
532 function spam_uri_pickup($string = '', $method = array())
533 {
534         if (! is_array($method) || empty($method)) {
535                 $method = check_uri_spam_method();
536         }
537
538         $string = spam_uri_pickup_preprocess($string);
539
540         $array  = uri_pickup($string);
541
542         // Area elevation of URIs, for '(especially external)link' intension
543         if (! empty($array)) {
544                 $_method = array();
545                 if (isset($method['uri_anchor'])) $_method['uri_anchor'] = & $method['uri_anchor'];
546                 if (isset($method['uri_bbcode'])) $_method['uri_bbcode'] = & $method['uri_bbcode'];
547                 $areas = area_pickup($string, $_method, TRUE);
548                 if (! empty($areas)) {
549                         $area_shadow = array();
550                         foreach (array_keys($array) as $key) {
551                                 $area_shadow[$key] = & $array[$key]['area'];
552                                 foreach (array_keys($_method) as $_key) {
553                                         $area_shadow[$key][$_key] = 0;
554                                 }
555                         }
556                         foreach (array_keys($_method) as $_key) {
557                                 if (isset($areas[$_key])) {
558                                         area_measure($areas[$_key], $area_shadow, 1, $_key);
559                                 }
560                         }
561                 }
562         }
563
564         // Remove 'offset's for area_measure()
565         foreach(array_keys($array) as $key)
566                 unset($array[$key]['area']['offset']);
567
568         return $array;
569 }
570
571
572 // ---------------------
573 // Normalization
574
575 // Scheme normalization: Renaming the schemes
576 // snntp://example.org =>  nntps://example.org
577 // NOTE: Keep the static lists simple. See also port_normalize().
578 function scheme_normalize($scheme = '', $abbrevs_harmfull = TRUE)
579 {
580         // Abbreviations they have no intention of link
581         static $abbrevs = array(
582                 'ttp'   => 'http',
583                 'ttps'  => 'https',
584         );
585
586         // Aliases => normalized ones
587         static $aliases = array(
588                 'pop'   => 'pop3',
589                 'news'  => 'nntp',
590                 'imap4' => 'imap',
591                 'snntp' => 'nntps',
592                 'snews' => 'nntps',
593                 'spop3' => 'pop3s',
594                 'pops'  => 'pop3s',
595         );
596
597         if (! is_string($scheme)) return '';
598
599         $scheme = strtolower($scheme);
600         if (isset($abbrevs[$scheme])) {
601                 $scheme = $abbrevs_harmfull ? $abbrevs[$scheme] : '';
602         }
603         if (isset($aliases[$scheme])) {
604                 $scheme = $aliases[$scheme];
605         }
606
607         return $scheme;
608 }
609
610 // Hostname normlization (Destructive)
611 // www.foo     => www.foo   ('foo' seems TLD)
612 // www.foo.bar => foo.bar
613 // www.10.20   => www.10.20 (Invalid hostname)
614 // NOTE:
615 //   'www' is  mostly used as traditional hostname of WWW server.
616 //   'www.foo.bar' may be identical with 'foo.bar'.
617 function host_normalize($host = '')
618 {
619         if (! is_string($host)) return '';
620
621         $host = strtolower($host);
622         $matches = array();
623         if (preg_match('/^www\.(.+\.[a-z]+)$/', $host, $matches)) {
624                 return $matches[1];
625         } else {
626                 return $host;
627         }
628 }
629
630 // Port normalization: Suppress the (redundant) default port
631 // HTTP://example.org:80/ => http://example.org/
632 // HTTP://example.org:8080/ => http://example.org:8080/
633 // HTTPS://example.org:443/ => https://example.org/
634 function port_normalize($port, $scheme, $scheme_normalize = FALSE)
635 {
636         // Schemes that users _maybe_ want to add protocol-handlers
637         // to their web browsers. (and attackers _maybe_ want to use ...)
638         // Reference: http://www.iana.org/assignments/port-numbers
639         static $array = array(
640                 // scheme => default port
641                 'ftp'     =>    21,
642                 'ssh'     =>    22,
643                 'telnet'  =>    23,
644                 'smtp'    =>    25,
645                 'tftp'    =>    69,
646                 'gopher'  =>    70,
647                 'finger'  =>    79,
648                 'http'    =>    80,
649                 'pop3'    =>   110,
650                 'sftp'    =>   115,
651                 'nntp'    =>   119,
652                 'imap'    =>   143,
653                 'irc'     =>   194,
654                 'wais'    =>   210,
655                 'https'   =>   443,
656                 'nntps'   =>   563,
657                 'rsync'   =>   873,
658                 'ftps'    =>   990,
659                 'telnets' =>   992,
660                 'imaps'   =>   993,
661                 'ircs'    =>   994,
662                 'pop3s'   =>   995,
663                 'mysql'   =>  3306,
664         );
665
666         // intval() converts '0-1' to '0', so preg_match() rejects these invalid ones
667         if (! is_numeric($port) || $port < 0 || preg_match('/[^0-9]/i', $port))
668                 return '';
669
670         $port = intval($port);
671         if ($scheme_normalize) $scheme = scheme_normalize($scheme);
672         if (isset($array[$scheme]) && $port == $array[$scheme])
673                 $port = ''; // Ignore the defaults
674
675         return $port;
676 }
677
678 // Path normalization
679 // http://example.org => http://example.org/
680 // http://example.org#hoge => http://example.org/#hoge
681 // http://example.org/path/a/b/./c////./d => http://example.org/path/a/b/c/d
682 // http://example.org/path/../../a/../back => http://example.org/back
683 function path_normalize($path = '', $divider = '/', $add_root = TRUE)
684 {
685         if (! is_string($divider)) return is_string($path) ? $path : '';
686
687         if ($add_root) {
688                 $first_div = & $divider;
689         } else {
690                 $first_div = '';
691         }
692         if (! is_string($path) || $path == '') return $first_div;
693
694         if (strpos($path, $divider, strlen($path) - strlen($divider)) === FALSE) {
695                 $last_div = '';
696         } else {
697                 $last_div = & $divider;
698         }
699
700         $array = explode($divider, $path);
701
702         // Remove paddings ('//' and '/./')
703         foreach(array_keys($array) as $key) {
704                 if ($array[$key] == '' || $array[$key] == '.') {
705                          unset($array[$key]);
706                 }
707         }
708
709         // Remove back-tracks ('/../')
710         $tmp = array();
711         foreach($array as $value) {
712                 if ($value == '..') {
713                         array_pop($tmp);
714                 } else {
715                         array_push($tmp, $value);
716                 }
717         }
718         $array = & $tmp;
719
720         if (empty($array)) {
721                 return $first_div;
722         } else {
723                 return $first_div . implode($divider, $array) . $last_div;
724         }
725 }
726
727 // DirectoryIndex normalize (Destructive and rough)
728 // TODO: sample.en.ja.html.gz => sample.html
729 function file_normalize($file = 'index.html.en')
730 {
731         static $simple_defaults = array(
732                 'default.htm'   => TRUE,
733                 'default.html'  => TRUE,
734                 'default.asp'   => TRUE,
735                 'default.aspx'  => TRUE,
736                 'index'                 => TRUE,        // Some system can omit the suffix
737         );
738
739         static $content_suffix = array(
740                 // index.xxx, sample.xxx
741                 'htm'   => TRUE,
742                 'html'  => TRUE,
743                 'shtml' => TRUE,
744                 'jsp'   => TRUE,
745                 'php'   => TRUE,
746                 'php3'  => TRUE,
747                 'php4'  => TRUE,
748                 'pl'    => TRUE,
749                 'py'    => TRUE,
750                 'rb'    => TRUE,
751                 'cgi'   => TRUE,
752                 'xml'   => TRUE,
753         );
754
755         static $language_suffix = array(
756                 // Reference: Apache 2.0.59 'AddLanguage' default
757                 'ca'    => TRUE,
758                 'cs'    => TRUE,        // cs
759                 'cz'    => TRUE,        // cs
760                 'de'    => TRUE,
761                 'dk'    => TRUE,        // da
762                 'el'    => TRUE,
763                 'en'    => TRUE,
764                 'eo'    => TRUE,
765                 'es'    => TRUE,
766                 'et'    => TRUE,
767                 'fr'    => TRUE,
768                 'he'    => TRUE,
769                 'hr'    => TRUE,
770                 'it'    => TRUE,
771                 'ja'    => TRUE,
772                 'ko'    => TRUE,
773                 'ltz'   => TRUE,
774                 'nl'    => TRUE,
775                 'nn'    => TRUE,
776                 'no'    => TRUE,
777                 'po'    => TRUE,
778                 'pt'    => TRUE,
779                 'pt-br' => TRUE,
780                 'ru'    => TRUE,
781                 'sv'    => TRUE,
782                 'zh-cn' => TRUE,
783                 'zh-tw' => TRUE,
784
785                 // Reference: Apache 2.0.59 default 'index.html' variants
786                 'ee'    => TRUE,
787                 'lb'    => TRUE,
788                 'var'   => TRUE,
789         );
790
791         static $charset_suffix = array(
792                 // Reference: Apache 2.0.59 'AddCharset' default
793                 'iso8859-1'     => TRUE, // ISO-8859-1
794                 'latin1'        => TRUE, // ISO-8859-1
795                 'iso8859-2'     => TRUE, // ISO-8859-2
796                 'latin2'        => TRUE, // ISO-8859-2
797                 'cen'           => TRUE, // ISO-8859-2
798                 'iso8859-3'     => TRUE, // ISO-8859-3
799                 'latin3'        => TRUE, // ISO-8859-3
800                 'iso8859-4'     => TRUE, // ISO-8859-4
801                 'latin4'        => TRUE, // ISO-8859-4
802                 'iso8859-5'     => TRUE, // ISO-8859-5
803                 'latin5'        => TRUE, // ISO-8859-5
804                 'cyr'           => TRUE, // ISO-8859-5
805                 'iso-ru'        => TRUE, // ISO-8859-5
806                 'iso8859-6'     => TRUE, // ISO-8859-6
807                 'latin6'        => TRUE, // ISO-8859-6
808                 'arb'           => TRUE, // ISO-8859-6
809                 'iso8859-7'     => TRUE, // ISO-8859-7
810                 'latin7'        => TRUE, // ISO-8859-7
811                 'grk'           => TRUE, // ISO-8859-7
812                 'iso8859-8'     => TRUE, // ISO-8859-8
813                 'latin8'        => TRUE, // ISO-8859-8
814                 'heb'           => TRUE, // ISO-8859-8
815                 'iso8859-9'     => TRUE, // ISO-8859-9
816                 'latin9'        => TRUE, // ISO-8859-9
817                 'trk'           => TRUE, // ISO-8859-9
818                 'iso2022-jp'=> TRUE, // ISO-2022-JP
819                 'jis'           => TRUE, // ISO-2022-JP
820                 'iso2022-kr'=> TRUE, // ISO-2022-KR
821                 'kis'           => TRUE, // ISO-2022-KR
822                 'iso2022-cn'=> TRUE, // ISO-2022-CN
823                 'cis'           => TRUE, // ISO-2022-CN
824                 'big5'          => TRUE,
825                 'cp-1251'       => TRUE, // ru, WINDOWS-1251
826                 'win-1251'      => TRUE, // ru, WINDOWS-1251
827                 'cp866'         => TRUE, // ru
828                 'koi8-r'        => TRUE, // ru, KOI8-r
829                 'koi8-ru'       => TRUE, // ru, KOI8-r
830                 'koi8-uk'       => TRUE, // ru, KOI8-ru
831                 'ua'            => TRUE, // ru, KOI8-ru
832                 'ucs2'          => TRUE, // ru, ISO-10646-UCS-2
833                 'ucs4'          => TRUE, // ru, ISO-10646-UCS-4
834                 'utf8'          => TRUE,
835
836                 // Reference: Apache 2.0.59 default 'index.html' variants
837                 'euc-kr'        => TRUE,
838                 'gb2312'        => TRUE,
839         );
840
841         // May uncompress by web browsers on the fly
842         // Must be at the last of the filename
843         // Reference: Apache 2.0.59 'AddEncoding'
844         static $encoding_suffix = array(
845                 'z'             => TRUE,
846                 'gz'    => TRUE,
847         );
848
849         if (! is_string($file)) return '';
850         $_file = strtolower($file);
851         if (isset($simple_defaults[$_file])) return '';
852
853
854         // Roughly removing language/character-set/encoding suffixes
855         // References:
856         //  * Apache 2 document about 'Content-negotiaton', 'mod_mime' and 'mod_negotiation'
857         //    http://httpd.apache.org/docs/2.0/content-negotiation.html
858         //    http://httpd.apache.org/docs/2.0/mod/mod_mime.html
859         //    http://httpd.apache.org/docs/2.0/mod/mod_negotiation.html
860         //  * http://www.iana.org/assignments/character-sets
861         //  * RFC3066: Tags for the Identification of Languages
862         //    http://www.ietf.org/rfc/rfc3066.txt
863         //  * ISO 639: codes of 'language names'
864         $suffixes = explode('.', $_file);
865         $body = array_shift($suffixes);
866         if ($suffixes) {
867                 // Remove the last .gz/.z
868                 $last_key = end(array_keys($suffixes));
869                 if (isset($encoding_suffix[$suffixes[$last_key]])) {
870                         unset($suffixes[$last_key]);
871                 }
872         }
873         // Cut language and charset suffixes
874         foreach($suffixes as $key => $value){
875                 if (isset($language_suffix[$value]) || isset($charset_suffix[$value])) {
876                         unset($suffixes[$key]);
877                 }
878         }
879         if (empty($suffixes)) return $body;
880
881         // Index.xxx
882         $count = count($suffixes);
883         reset($suffixes);
884         $current = current($suffixes);
885         if ($body == 'index' && $count == 1 && isset($content_suffix[$current])) return '';
886
887         return $file;
888 }
889
890 // Sort query-strings if possible (Destructive and rough)
891 // [OK] &&&&f=d&b&d&c&a=0dd  =>  a=0dd&b&c&d&f=d
892 // [OK] nothing==&eg=dummy&eg=padding&eg=foobar  =>  eg=foobar
893 function query_normalize($string = '', $equal = TRUE, $equal_cutempty = TRUE, $stortolower = TRUE)
894 {
895         if (! is_string($string)) return '';
896         if ($stortolower) $string = strtolower($string);
897
898         $array = explode('&', $string);
899
900         // Remove '&' paddings
901         foreach(array_keys($array) as $key) {
902                 if ($array[$key] == '') {
903                          unset($array[$key]);
904                 }
905         }
906
907         // Consider '='-sepalated input and paddings
908         if ($equal) {
909                 $equals = $not_equals = array();
910                 foreach ($array as $part) {
911                         if (strpos($part, '=') === FALSE) {
912                                  $not_equals[] = $part;
913                         } else {
914                                 list($key, $value) = explode('=', $part, 2);
915                                 $value = ltrim($value, '=');
916                                 if (! $equal_cutempty || $value != '') {
917                                         $equals[$key] = $value;
918                                 }
919                         }
920                 }
921
922                 $array = & $not_equals;
923                 foreach ($equals as $key => $value) {
924                         $array[] = $key . '=' . $value;
925                 }
926                 unset($equals);
927         }
928
929         natsort($array);
930         return implode('&', $array);
931 }
932
933 // ---------------------
934 // Part One : Checker
935
936 // Rough implementation of globbing
937 //
938 // USAGE: $regex = '/^' . generate_glob_regex('*.txt', '/') . '$/i';
939 //
940 function generate_glob_regex($string = '', $divider = '/')
941 {
942         static $from = array(
943                          1 => '*',
944                         11 => '?',
945         //              22 => '[',      // Maybe cause regex compilation error (e.g. '[]')
946         //              23 => ']',      //
947                 );
948         static $mid = array(
949                          1 => '_AST_',
950                         11 => '_QUE_',
951         //              22 => '_RBR_',
952         //              23 => '_LBR_',
953                 );
954         static $to = array(
955                          1 => '.*',
956                         11 => '.',
957         //              22 => '[',
958         //              23 => ']',
959                 );
960
961         if (! is_string($string)) return '';
962
963         $string = str_replace($from, $mid, $string); // Hide
964         $string = preg_quote($string, $divider);
965         $string = str_replace($mid, $to, $string);   // Unhide
966
967         return $string;
968 }
969
970 // Rough hostname checker
971 // [OK] 192.168.
972 // TODO: Strict digit, 0x, CIDR, IPv6
973 function is_ip($string = '')
974 {
975         if (preg_match('/^' .
976                 '(?:[0-9]{1,3}\.){3}[0-9]{1,3}' . '|' .
977                 '(?:[0-9]{1,3}\.){1,3}' . '$/',
978                 $string)) {
979                 return 4;       // Seems IPv4(dot-decimal)
980         } else {
981                 return 0;       // Seems not IP
982         }
983 }
984
985 // Generate host (FQDN, IPv4, ...) regex
986 // 'localhost'     : Matches with 'localhost' only
987 // 'example.org'   : Matches with 'example.org' only (See host_normalize() about 'www')
988 // '.example.org'  : Matches with ALL FQDN ended with '.example.org'
989 // '*.example.org' : Almost the same of '.example.org' except 'www.example.org'
990 // '10.20.30.40'   : Matches with IPv4 address '10.20.30.40' only
991 // [TODO] '192.'   : Matches with all IPv4 hosts started with '192.'
992 // TODO: IPv4, CIDR?, IPv6
993 function generate_host_regex($string = '', $divider = '/')
994 {
995         if (! is_string($string)) return '';
996
997         if (mb_strpos($string, '.') === FALSE)
998                 return generate_glob_regex($string, $divider);
999
1000         $result = '';
1001         if (is_ip($string)) {
1002                 // IPv4
1003                 return generate_glob_regex($string, $divider);
1004         } else {
1005                 // FQDN or something
1006                 $part = explode('.', $string, 2);
1007                 if ($part[0] == '') {
1008                         $part[0] = '(?:.*\.)?'; // And all related FQDN
1009                 } else if ($part[0] == '*') {
1010                         $part[0] = '.*\.';      // All subdomains/hosts only
1011                 } else {
1012                         return generate_glob_regex($string, $divider);
1013                 }
1014                 $part[1] = generate_glob_regex($part[1], $divider);
1015                 return implode('', $part);
1016         }
1017 }
1018
1019 function get_blocklist($list = '', $dispose = FALSE)
1020 {
1021         static $f_dispose = FALSE, $regexes;
1022
1023         if ($dispose) {
1024                 $f_dispose = TRUE;
1025                 $regexes   = NULL;      // Unset
1026                 return array();
1027         }
1028
1029         if (! isset($regexes)) {
1030                 if ($f_dispose) die(__FUNCTION__ . '(): Memory already disposed');
1031
1032                 $regexes = array();
1033                 if (file_exists(SPAM_INI_FILE)) {
1034                         $blocklist = array();
1035                         include(SPAM_INI_FILE);
1036                         //      $blocklist['badhost'] = array(
1037                         //              '*.blogspot.com',       // Blog services's subdomains (only)
1038                         //              'IANA-examples' => '#^(?:.*\.)?example\.(?:com|net|org)$#',
1039                         //      );
1040                         if (isset($blocklist['list'])) {
1041                                 $regexes['list'] = & $blocklist['list'];
1042                         } else {
1043                                 // Default
1044                                 $blocklist['list'] = array(
1045                                         'goodhost' => FALSE,
1046                                         'badhost'  => TRUE,
1047                                 );
1048                         }
1049                         foreach(array_keys($blocklist['list']) as $_list) {
1050                                 if (! isset($blocklist[$_list])) continue;
1051                                 foreach ($blocklist[$_list] as $key => $value) {
1052                                         if (is_array($value)) {
1053                                                 $regexes[$_list][$key] = array();
1054                                                 foreach($value as $_key => $_value) {
1055                                                         get_blocklist_add($regexes[$_list][$key], $_key, $_value);
1056                                                 }
1057                                         } else {
1058                                                 get_blocklist_add($regexes[$_list], $key, $value);
1059                                         }
1060                                 }
1061                                 unset($blocklist[$_list]);
1062                         }
1063                 }
1064         }
1065
1066         if ($list === '') {
1067                 return $regexes;        // ALL
1068         } else if (isset($regexes[$list])) {
1069                 return $regexes[$list];
1070         } else {
1071                 return array();
1072         }
1073 }
1074
1075 // Subroutine of get_blocklist()
1076 function get_blocklist_add(& $array, $key = 0, $value = '*.example.org')
1077 {
1078         if (is_string($key)) {
1079                 $array[$key] = & $value; // Treat $value as a regex
1080         } else {
1081                 $array[$value] = '/^' . generate_host_regex($value, '/') . '$/i';
1082         }
1083 }
1084
1085 // Blocklist metrics: Separate $host, to $blocked and not blocked
1086 function blocklist_distiller(& $hosts, $keys = array('goodhost', 'badhost'), $asap = FALSE)
1087 {
1088         if (! is_array($hosts)) $hosts = array($hosts);
1089         if (! is_array($keys))  $keys  = array($keys);
1090
1091         $list = get_blocklist('list');
1092         $blocked = array();
1093
1094         foreach($keys as $key){
1095                 foreach (get_blocklist($key) as $label => $regex) {
1096                         if (is_array($regex)) {
1097                                 foreach($regex as $_label => $_regex) {
1098                                         $group = preg_grep($_regex, $hosts);
1099                                         if ($group) {
1100                                                 $hosts = array_diff($hosts, $group);
1101                                                 $blocked[$key][$label][$_label] = $group;
1102                                                 if ($asap && $list[$key]) break;
1103                                         }
1104                                 }
1105                         } else {
1106                                 $group = preg_grep($regex, $hosts);
1107                                 if ($group) {
1108                                         $hosts = array_diff($hosts, $group);
1109                                         $blocked[$key][$label] = $group;
1110                                         if ($asap && $list[$key]) break;
1111                                 }
1112                         }
1113                 }
1114         }
1115
1116         return $blocked;
1117 }
1118
1119 // Default (enabled) methods and thresholds (for content insertion)
1120 function check_uri_spam_method($times = 1, $t_area = 0, $rule = TRUE)
1121 {
1122         $times  = intval($times);
1123         $t_area = intval($t_area);
1124
1125         $positive = array(
1126                 // Thresholds
1127                 'quantity'     =>  8 * $times,  // Allow N URIs
1128                 'non_uniqhost' =>  3 * $times,  // Allow N duped (and normalized) Hosts
1129                 //'non_uniquri'=>  3 * $times,  // Allow N duped (and normalized) URIs
1130
1131                 // Areas
1132                 'area_anchor'  => $t_area,      // Using <a href> HTML tag
1133                 'area_bbcode'  => $t_area,      // Using [url] or [link] BBCode
1134                 //'uri_anchor' => $t_area,      // URI inside <a href> HTML tag
1135                 //'uri_bbcode' => $t_area,      // URI inside [url] or [link] BBCode
1136         );
1137         if ($rule) {
1138                 $bool = array(
1139                         // Rules
1140                         //'asap'   => TRUE,     // Quit or return As Soon As Possible
1141                         'uniqhost' => TRUE,     // Show uniq host (at block notification mail)
1142                         'badhost'  => TRUE,     // Check badhost
1143                 );
1144         } else {
1145                 $bool = array();
1146         }
1147
1148         // Remove non-$positive values
1149         foreach (array_keys($positive) as $key) {
1150                 if ($positive[$key] < 0) unset($positive[$key]);
1151         }
1152
1153         return $positive + $bool;
1154 }
1155
1156 // Simple/fast spam check
1157 function check_uri_spam($target = '', $method = array())
1158 {
1159         // Return value
1160         $progress = array(
1161                 'method'  => array(
1162                         // Theme to do  => Dummy, optional value, or optional array()
1163                         //'quantity'    => 8,
1164                         //'uniqhost'    => TRUE,
1165                         //'non_uniqhost'=> 3,
1166                         //'non_uniquri' => 3,
1167                         //'badhost'     => TRUE,
1168                         //'area_anchor' => 0,
1169                         //'area_bbcode' => 0,
1170                         //'uri_anchor'  => 0,
1171                         //'uri_bbcode'  => 0,
1172                 ),
1173                 'sum' => array(
1174                         // Theme        => Volume found (int)
1175                 ),
1176                 'is_spam' => array(
1177                         // Flag. If someting defined here,
1178                         // one or more spam will be included
1179                         // in this report
1180                 ),
1181                 'blocked' => array(
1182                         // Hosts blocked
1183                         //'category' => array(
1184                         //      'host',
1185                         //)
1186                 ),
1187                 'hosts' => array(
1188                         // Hosts not blocked
1189                 ),
1190         );
1191
1192         // Aliases
1193         $sum     = & $progress['sum'];
1194         $is_spam = & $progress['is_spam'];
1195         $progress['method'] = & $method;        // Argument
1196         $blocked = & $progress['blocked'];
1197         $hosts   = & $progress['hosts'];
1198         $asap    = isset($method['asap']);
1199
1200         // Init
1201         if (! is_array($method) || empty($method)) {
1202                 $method = check_uri_spam_method();
1203         }
1204         foreach(array_keys($method) as $key) {
1205                 if (! isset($sum[$key])) $sum[$key] = 0;
1206         }
1207
1208         if (is_array($target)) {
1209                 foreach($target as $str) {
1210                         if (! is_string($str)) continue;
1211
1212                         $_progress = check_uri_spam($str, $method);     // Recurse
1213
1214                         // Merge $sum
1215                         $_sum = & $_progress['sum'];
1216                         foreach (array_keys($_sum) as $key) {
1217                                 if (! isset($sum[$key])) {
1218                                         $sum[$key] = & $_sum[$key];
1219                                 } else {
1220                                         $sum[$key] += $_sum[$key];
1221                                 }
1222                         }
1223
1224                         // Merge $is_spam
1225                         $_is_spam = & $_progress['is_spam'];
1226                         foreach (array_keys($_is_spam) as $key) {
1227                                 $is_spam[$key] = TRUE;
1228                                 if ($asap) break;
1229                         }
1230                         if ($asap && $is_spam) break;
1231
1232                         // Merge only
1233                         $blocked = array_merge_recursive($blocked, $_progress['blocked']);
1234                         $hosts   = array_merge_recursive($hosts,   $_progress['hosts']);
1235                 }
1236
1237                 // Unique values
1238                 $blocked = array_unique_recursive($blocked);
1239                 $hosts   = array_unique_recursive($hosts);
1240
1241                 // Recount $sum['badhost']
1242                 $sum['badhost'] = array_count_leaves($blocked);
1243
1244                 return $progress;
1245         }
1246
1247         // Area: There's HTML anchor tag
1248         if ((! $asap || ! $is_spam) && isset($method['area_anchor'])) {
1249                 $key = 'area_anchor';
1250                 $_asap = isset($method['asap']) ? array('asap' => TRUE) : array();
1251                 $result = area_pickup($target, array($key => TRUE) + $_asap);
1252                 if ($result) {
1253                         $sum[$key] = $result[$key];
1254                         if (isset($method[$key]) && $sum[$key] > $method[$key]) {
1255                                 $is_spam[$key] = TRUE;
1256                         }
1257                 }
1258         }
1259
1260         // Area: There's 'BBCode' linking tag
1261         if ((! $asap || ! $is_spam) && isset($method['area_bbcode'])) {
1262                 $key = 'area_bbcode';
1263                 $_asap = isset($method['asap']) ? array('asap' => TRUE) : array();
1264                 $result = area_pickup($target, array($key => TRUE) + $_asap);
1265                 if ($result) {
1266                         $sum[$key] = $result[$key];
1267                         if (isset($method[$key]) && $sum[$key] > $method[$key]) {
1268                                 $is_spam[$key] = TRUE;
1269                         }
1270                 }
1271         }
1272
1273         // Return if ...
1274         if ($asap && $is_spam) return $progress;
1275
1276         // URI: Pickup
1277         $pickups = uri_pickup_normalize(spam_uri_pickup($target, $method));
1278
1279         // Return if ...
1280         if (empty($pickups)) return $progress;
1281
1282         // URI: Check quantity
1283         $sum['quantity'] += count($pickups);
1284                 // URI quantity
1285         if ((! $asap || ! $is_spam) && isset($method['quantity']) &&
1286                 $sum['quantity'] > $method['quantity']) {
1287                 $is_spam['quantity'] = TRUE;
1288         }
1289
1290         // URI: used inside HTML anchor tag pair
1291         if ((! $asap || ! $is_spam) && isset($method['uri_anchor'])) {
1292                 $key = 'uri_anchor';
1293                 foreach($pickups as $pickup) {
1294                         if (isset($pickup['area'][$key])) {
1295                                 $sum[$key] += $pickup['area'][$key];
1296                                 if(isset($method[$key]) &&
1297                                         $sum[$key] > $method[$key]) {
1298                                         $is_spam[$key] = TRUE;
1299                                         if ($asap && $is_spam) break;
1300                                 }
1301                                 if ($asap && $is_spam) break;
1302                         }
1303                 }
1304         }
1305
1306         // URI: used inside 'BBCode' pair
1307         if ((! $asap || ! $is_spam) && isset($method['uri_bbcode'])) {
1308                 $key = 'uri_bbcode';
1309                 foreach($pickups as $pickup) {
1310                         if (isset($pickup['area'][$key])) {
1311                                 $sum[$key] += $pickup['area'][$key];
1312                                 if(isset($method[$key]) &&
1313                                         $sum[$key] > $method[$key]) {
1314                                         $is_spam[$key] = TRUE;
1315                                         if ($asap && $is_spam) break;
1316                                 }
1317                                 if ($asap && $is_spam) break;
1318                         }
1319                 }
1320         }
1321
1322         // URI: Uniqueness (and removing non-uniques)
1323         if ((! $asap || ! $is_spam) && isset($method['non_uniquri'])) {
1324
1325                 $uris = array();
1326                 foreach (array_keys($pickups) as $key) {
1327                         $uris[$key] = uri_pickup_implode($pickups[$key]);
1328                 }
1329                 $count = count($uris);
1330                 $uris  = array_unique($uris);
1331                 $sum['non_uniquri'] += $count - count($uris);
1332                 if ($sum['non_uniquri'] > $method['non_uniquri']) {
1333                         $is_spam['non_uniquri'] = TRUE;
1334                 }
1335                 if (! $asap || ! $is_spam) {
1336                         foreach (array_diff(array_keys($pickups),
1337                                 array_keys($uris)) as $remove) {
1338                                 unset($pickups[$remove]);
1339                         }
1340                 }
1341                 unset($uris);
1342         }
1343
1344         // Return if ...
1345         if ($asap && $is_spam) return $progress;
1346
1347         // Host: Uniqueness (uniq / non-uniq)
1348         foreach ($pickups as $pickup) $hosts[] = & $pickup['host'];
1349         $hosts = array_unique($hosts);
1350         $sum['uniqhost'] += count($hosts);
1351         if ((! $asap || ! $is_spam) && isset($method['non_uniqhost'])) {
1352                 $sum['non_uniqhost'] = $sum['quantity'] - $sum['uniqhost'];
1353                 if ($sum['non_uniqhost'] > $method['non_uniqhost']) {
1354                         $is_spam['non_uniqhost'] = TRUE;
1355                 }
1356         }
1357
1358         // Return if ...
1359         if ($asap && $is_spam) return $progress;
1360
1361         // URI: Bad host (Separate good/bad hosts from $hosts)
1362         if ((! $asap || ! $is_spam) && isset($method['badhost'])) {
1363
1364                 // is_badhost()
1365                 $list = get_blocklist('list');
1366                 $blocked = blocklist_distiller($hosts, array_keys($list), $asap);
1367                 foreach($list as $key=>$type){
1368                         if (! $type) unset($blocked[$key]); // Ignore goodhost etc
1369                 }
1370                 unset($list);
1371
1372                 if (! empty($blocked)) $is_spam['badhost'] = TRUE;
1373         }
1374
1375         return $progress;
1376 }
1377
1378 // Count leaves (A leaf = value that is not an array, or an empty array)
1379 function array_count_leaves($array = array(), $count_empty = FALSE)
1380 {
1381         if (! is_array($array) || (empty($array) && $count_empty)) return 1;
1382
1383         // Recurse
1384         $count = 0;
1385         foreach ($array as $part) {
1386                 $count += array_count_leaves($part, $count_empty);
1387         }
1388         return $count;
1389 }
1390
1391 // An array-leaves to a flat array
1392 function array_flat_leaves($array, $unique = TRUE)
1393 {
1394         if (! is_array($array)) return $array;
1395
1396         $tmp = array();
1397         foreach(array_keys($array) as $key) {
1398                 if (is_array($array[$key])) {
1399                         // Recurse
1400                         foreach(array_flat_leaves($array[$key]) as $_value) {
1401                                 $tmp[] = $_value;
1402                         }
1403                 } else {
1404                         $tmp[] = & $array[$key];
1405                 }
1406         }
1407
1408         return $unique ? array_values(array_unique($tmp)) : $tmp;
1409 }
1410
1411 // An array() to an array leaf
1412 function array_leaf($array = array('A', 'B', 'C.D'), $stem = FALSE, $edge = array())
1413 {
1414         $leaf = array();
1415         $tmp  = & $leaf;
1416         foreach($array as $arg) {
1417                 if (! is_string($arg) && ! is_int($arg)) continue;
1418                 $tmp[$arg] = array();
1419                 $parent    = & $tmp;
1420                 $tmp       = & $tmp[$arg];
1421         }
1422         if ($stem) {
1423                 $parent[key($parent)] = & $edge;
1424         } else {
1425                 $parent = key($parent);
1426         }
1427
1428         return $leaf;   // array('A' => array('B' => 'C.D'))
1429 }
1430
1431
1432 // ---------------------
1433 // Reporting
1434
1435 // Summarize $progress (blocked only)
1436 function summarize_spam_progress($progress = array(), $blockedonly = FALSE)
1437 {
1438         if ($blockedonly) {
1439                 $tmp = array_keys($progress['is_spam']);
1440         } else {
1441                 $tmp = array();
1442                 $method = & $progress['method'];
1443                 if (isset($progress['sum'])) {
1444                         foreach ($progress['sum'] as $key => $value) {
1445                                 if (isset($method[$key]) && $value) {
1446                                         $tmp[] = $key . '(' . $value . ')';
1447                                 }
1448                         }
1449                 }
1450         }
1451
1452         return implode(', ', $tmp);
1453 }
1454
1455 function summarize_detail_badhost($progress = array())
1456 {
1457         if (! isset($progress['blocked']) || empty($progress['blocked'])) return '';
1458
1459         // Flat per group
1460         $blocked = array();
1461         foreach($progress['blocked'] as $list => $lvalue) {
1462                 foreach($lvalue as $group => $gvalue) {
1463                         $flat = implode(', ', array_flat_leaves($gvalue));
1464                         if ($flat === $group) {
1465                                 $blocked[$list][]       = $flat;
1466                         } else {
1467                                 $blocked[$list][$group] = $flat;
1468                         }
1469                 }
1470         }
1471
1472         // Shrink per list
1473         // From: 'A-1' => array('ie.to')
1474         // To:   'A-1' => 'ie.to'
1475         foreach($blocked as $list => $lvalue) {
1476                 if (is_array($lvalue) &&
1477                    count($lvalue) == 1 &&
1478                    is_numeric(key($lvalue))) {
1479                     $blocked[$list] = current($lvalue);
1480                 }
1481         }
1482
1483         return var_export_shrink($blocked, TRUE, TRUE);
1484 }
1485
1486 function summarize_detail_newtral($progress = array())
1487 {
1488         if (! isset($progress['hosts'])    ||
1489             ! is_array($progress['hosts']) ||
1490             empty($progress['hosts'])) return '';
1491
1492         $result = '';
1493         if (FALSE) {
1494                 // Sort by domain
1495                 $tmp = array();
1496                 foreach($progress['hosts'] as $value) {
1497                         $tmp[delimiter_reverse($value)] = $value;
1498                 }
1499                 ksort($tmp, SORT_STRING);
1500                 $result = count($tmp) . ' (' .implode(', ', $tmp) . ')';
1501         } else {
1502                 $tmp = array();
1503                 foreach($progress['hosts'] as $value) {
1504                         $tmp = array_merge_recursive(
1505                                 $tmp,
1506                                 array_leaf(explode('.', delimiter_reverse($value) . '.'), TRUE, $value)
1507                         );
1508                 }
1509                 ksort($tmp, SORT_STRING);
1510
1511                 separate_and_joinkey_leaves($tmp, '.', TRUE, TRUE);
1512                 separate_and_joinkey_leaves($tmp, '.', TRUE, FALSE);
1513                 separate_and_joinkey_leaves($tmp, '.', TRUE, FALSE);
1514                 //separate_and_joinkey_leaves($tmp, '.', TRUE, FALSE);
1515
1516                 foreach($tmp as $key => $value) {
1517                         if (is_array($value)) {
1518                                 ksort($tmp[$key]);
1519                 //              $tmp[$key] = implode(', ', array_flat_leaves($value));
1520                         }
1521                 }
1522
1523                 $result = var_export_shrink($tmp, TRUE, TRUE);
1524         }
1525
1526         return $result;
1527 }
1528
1529 function separate_and_joinkey_leaves(
1530         & $array,       // array('A' => array('B' => 'C.D')),
1531         $delim = '.', $reversejoin = FALSE, $allowmulti = FALSE)
1532 {
1533         if (! is_array($array)) return $array;
1534
1535         $result = array();
1536         foreach(array_keys($array) as $key) {
1537                 if (! is_array($array[$key]) || (! $allowmulti && count($array[$key]) > 1)) {
1538                         $result[$key] = & $array[$key]; // Do nothing
1539                 } else {
1540                         foreach(array_keys($array[$key]) as $_key) {
1541                                 $joinkey = $reversejoin ?
1542                                         $_key . $delim . $key :
1543                                         $key  . $delim . $_key;
1544                                 $result[$joinkey] = & $array[$key][$_key];
1545                         }
1546                 }
1547         }
1548
1549         $array = & $result;
1550
1551         return $result; // array('A.B' => 'C.D')
1552 }
1553
1554
1555 // ---------------------
1556 // Exit
1557
1558 // Common bahavior for blocking
1559 // NOTE: Call this function from various blocking feature, to disgueise the reason 'why blocked'
1560 function spam_exit($mode = '', $data = array())
1561 {
1562         // Dispose
1563         get_blocklist(NULL, TRUE);
1564
1565         $exit = TRUE;
1566         switch ($mode) {
1567                 case '':
1568                         echo("\n");
1569                         break;
1570                 case 'dump':
1571                         echo('<pre>' . "\n");
1572                         echo htmlspecialchars(var_export($data, TRUE));
1573                         echo('</pre>' . "\n");
1574                         break;
1575         };
1576
1577         if ($exit) exit;        // Force exit
1578 }
1579
1580
1581 // ---------------------
1582 // Simple filtering
1583
1584 // TODO: Record them
1585 // Simple/fast spam filter ($target: 'a string' or an array())
1586 function pkwk_spamfilter($action, $page, $target = array('title' => ''), $method = array(), $exitmode = '')
1587 {
1588         $progress = check_uri_spam($target, $method);
1589
1590         if (! empty($progress['is_spam'])) {
1591                 // Mail to administrator(s)
1592                 pkwk_spamnotify($action, $page, $target, $progress, $method);
1593
1594                 // Exit
1595                 spam_exit($exitmode, $progress);
1596         }
1597 }
1598
1599 // ---------------------
1600 // PukiWiki original
1601
1602 // Mail to administrator(s)
1603 function pkwk_spamnotify($action, $page, $target = array('title' => ''), $progress = array(), $method = array())
1604 {
1605         global $notify, $notify_subject;
1606
1607         if (! $notify) return;
1608
1609         $asap = isset($method['asap']);
1610
1611         $summary['ACTION']  = 'Blocked by: ' . summarize_spam_progress($progress, TRUE);
1612         if (! $asap) {
1613                 $summary['METRICS'] = summarize_spam_progress($progress);
1614         }
1615
1616         $tmp = summarize_detail_badhost($progress);
1617         if ($tmp != '') $summary['DETAIL_BADHOST'] = $tmp;
1618
1619         $tmp = summarize_detail_newtral($progress);
1620         if (! $asap && $tmp != '') $summary['DETAIL_NEUTRAL_HOST'] = $tmp;
1621
1622         $summary['COMMENT'] = $action;
1623         $summary['PAGE']    = '[blocked] ' . (is_pagename($page) ? $page : '');
1624         $summary['URI']     = get_script_uri() . '?' . rawurlencode($page);
1625         $summary['USER_AGENT']  = TRUE;
1626         $summary['REMOTE_ADDR'] = TRUE;
1627         pkwk_mail_notify($notify_subject,  var_export($target, TRUE), $summary, TRUE);
1628 }
1629
1630 ?>