OSDN Git Service

Remove unused array_shrink_leaves().
[pukiwiki/pukiwiki_sandbox.git] / spam / spam.php
1 <?php
2 // $Id: spam.php,v 1.157 2007/05/05 13:58:39 henoheno Exp $
3 // Copyright (C) 2006-2007 PukiWiki Developers Team
4 // License: GPL v2 or (at your option) any later version
5 //
6 // Functions for Concept-work of spam-uri metrics
7 //
8 // (PHP 4 >= 4.3.0): preg_match_all(PREG_OFFSET_CAPTURE): $method['uri_XXX'] related feature
9
10 if (! defined('SPAM_INI_FILE')) define('SPAM_INI_FILE', 'spam.ini.php');
11
12 // ---------------------
13 // Compat etc
14
15 // (PHP 4 >= 4.2.0): var_export(): mail-reporting and dump related
16 if (! function_exists('var_export')) {
17         function var_export() {
18                 return 'var_export() is not found on this server' . "\n";
19         }
20 }
21
22 // (PHP 4 >= 4.2.0): preg_grep() enables invert option
23 function preg_grep_invert($pattern = '//', $input = array())
24 {
25         static $invert;
26         if (! isset($invert)) $invert = defined('PREG_GREP_INVERT');
27
28         if ($invert) {
29                 return preg_grep($pattern, $input, PREG_GREP_INVERT);
30         } else {
31                 $result = preg_grep($pattern, $input);
32                 if ($result) {
33                         return array_diff($input, preg_grep($pattern, $input));
34                 } else {
35                         return $input;
36                 }
37         }
38 }
39
40 // ----
41
42 // Very roughly, shrink the lines of var_export()
43 // NOTE: If the same data exists, it must be corrupted.
44 function var_export_shrink($expression, $return = FALSE, $ignore_numeric_keys = FALSE)
45 {
46         $result =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.-]+' .                                                 // 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                 '#http://' .
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 (See _preg_replace_callback_domain_exposure())
478         $string = preg_replace_callback(
479                 array(
480                         '#(http)://' .
481                         '(' .
482                                 // Something Google: http://www.google.com/supported_domains
483                                 '(?:[a-z0-9.]+\.)?google\.[a-z]{2,3}(?:\.[a-z]{2})?' .
484                                 '|' .
485                                 // AltaVista
486                                 '(?:[a-z0-9.]+\.)?altavista.com' .
487                                 
488                         ')' .
489                         '/' .
490                         '([a-z0-9?=&.%_/\'\\\+-]+)' .                           // path/?query=foo+bar+
491                         '\bsite:([a-z0-9.%_-]+\.[a-z0-9.%_-]+)' .       // site:nasty.example.com
492                         //'()' .        // Preserve or remove?
493                         '#i',
494                 ),
495                 '_preg_replace_callback_domain_exposure',
496                 $string
497         );
498
499         // URI exposure (uriuri => uri uri)
500         $string = preg_replace(
501                 array(
502                         '#(?<! )(?:https?|ftp):/#i',
503                 //      '#[a-z][a-z0-9.+-]{1,8}://#i',
504                 //      '#[a-z][a-z0-9.+-]{1,8}://#i'
505                 ),
506                 ' $0',
507                 $string
508         );
509
510         return $string;
511 }
512
513 // Main function of spam-uri pickup,
514 // A wrapper function of uri_pickup()
515 function spam_uri_pickup($string = '', $method = array())
516 {
517         if (! is_array($method) || empty($method)) {
518                 $method = check_uri_spam_method();
519         }
520
521         $string = spam_uri_pickup_preprocess($string);
522
523         $array  = uri_pickup($string);
524
525         // Area elevation of URIs, for '(especially external)link' intension
526         if (! empty($array)) {
527                 $_method = array();
528                 if (isset($method['uri_anchor'])) $_method['uri_anchor'] = & $method['uri_anchor'];
529                 if (isset($method['uri_bbcode'])) $_method['uri_bbcode'] = & $method['uri_bbcode'];
530                 $areas = area_pickup($string, $_method, TRUE);
531                 if (! empty($areas)) {
532                         $area_shadow = array();
533                         foreach (array_keys($array) as $key) {
534                                 $area_shadow[$key] = & $array[$key]['area'];
535                                 foreach (array_keys($_method) as $_key) {
536                                         $area_shadow[$key][$_key] = 0;
537                                 }
538                         }
539                         foreach (array_keys($_method) as $_key) {
540                                 if (isset($areas[$_key])) {
541                                         area_measure($areas[$_key], $area_shadow, 1, $_key);
542                                 }
543                         }
544                 }
545         }
546
547         // Remove 'offset's for area_measure()
548         foreach(array_keys($array) as $key)
549                 unset($array[$key]['area']['offset']);
550
551         return $array;
552 }
553
554
555 // ---------------------
556 // Normalization
557
558 // Scheme normalization: Renaming the schemes
559 // snntp://example.org =>  nntps://example.org
560 // NOTE: Keep the static lists simple. See also port_normalize().
561 function scheme_normalize($scheme = '', $abbrevs_harmfull = TRUE)
562 {
563         // Abbreviations they have no intention of link
564         static $abbrevs = array(
565                 'ttp'   => 'http',
566                 'ttps'  => 'https',
567         );
568
569         // Aliases => normalized ones
570         static $aliases = array(
571                 'pop'   => 'pop3',
572                 'news'  => 'nntp',
573                 'imap4' => 'imap',
574                 'snntp' => 'nntps',
575                 'snews' => 'nntps',
576                 'spop3' => 'pop3s',
577                 'pops'  => 'pop3s',
578         );
579
580         if (! is_string($scheme)) return '';
581
582         $scheme = strtolower($scheme);
583         if (isset($abbrevs[$scheme])) {
584                 $scheme = $abbrevs_harmfull ? $abbrevs[$scheme] : '';
585         }
586         if (isset($aliases[$scheme])) {
587                 $scheme = $aliases[$scheme];
588         }
589
590         return $scheme;
591 }
592
593 // Hostname normlization (Destructive)
594 // www.foo     => www.foo   ('foo' seems TLD)
595 // www.foo.bar => foo.bar
596 // www.10.20   => www.10.20 (Invalid hostname)
597 // NOTE:
598 //   'www' is  mostly used as traditional hostname of WWW server.
599 //   'www.foo.bar' may be identical with 'foo.bar'.
600 function host_normalize($host = '')
601 {
602         if (! is_string($host)) return '';
603
604         $host = strtolower($host);
605         $matches = array();
606         if (preg_match('/^www\.(.+\.[a-z]+)$/', $host, $matches)) {
607                 return $matches[1];
608         } else {
609                 return $host;
610         }
611 }
612
613 // Port normalization: Suppress the (redundant) default port
614 // HTTP://example.org:80/ => http://example.org/
615 // HTTP://example.org:8080/ => http://example.org:8080/
616 // HTTPS://example.org:443/ => https://example.org/
617 function port_normalize($port, $scheme, $scheme_normalize = FALSE)
618 {
619         // Schemes that users _maybe_ want to add protocol-handlers
620         // to their web browsers. (and attackers _maybe_ want to use ...)
621         // Reference: http://www.iana.org/assignments/port-numbers
622         static $array = array(
623                 // scheme => default port
624                 'ftp'     =>    21,
625                 'ssh'     =>    22,
626                 'telnet'  =>    23,
627                 'smtp'    =>    25,
628                 'tftp'    =>    69,
629                 'gopher'  =>    70,
630                 'finger'  =>    79,
631                 'http'    =>    80,
632                 'pop3'    =>   110,
633                 'sftp'    =>   115,
634                 'nntp'    =>   119,
635                 'imap'    =>   143,
636                 'irc'     =>   194,
637                 'wais'    =>   210,
638                 'https'   =>   443,
639                 'nntps'   =>   563,
640                 'rsync'   =>   873,
641                 'ftps'    =>   990,
642                 'telnets' =>   992,
643                 'imaps'   =>   993,
644                 'ircs'    =>   994,
645                 'pop3s'   =>   995,
646                 'mysql'   =>  3306,
647         );
648
649         // intval() converts '0-1' to '0', so preg_match() rejects these invalid ones
650         if (! is_numeric($port) || $port < 0 || preg_match('/[^0-9]/i', $port))
651                 return '';
652
653         $port = intval($port);
654         if ($scheme_normalize) $scheme = scheme_normalize($scheme);
655         if (isset($array[$scheme]) && $port == $array[$scheme])
656                 $port = ''; // Ignore the defaults
657
658         return $port;
659 }
660
661 // Path normalization
662 // http://example.org => http://example.org/
663 // http://example.org#hoge => http://example.org/#hoge
664 // http://example.org/path/a/b/./c////./d => http://example.org/path/a/b/c/d
665 // http://example.org/path/../../a/../back => http://example.org/back
666 function path_normalize($path = '', $divider = '/', $add_root = TRUE)
667 {
668         if (! is_string($divider)) return is_string($path) ? $path : '';
669
670         if ($add_root) {
671                 $first_div = & $divider;
672         } else {
673                 $first_div = '';
674         }
675         if (! is_string($path) || $path == '') return $first_div;
676
677         if (strpos($path, $divider, strlen($path) - strlen($divider)) === FALSE) {
678                 $last_div = '';
679         } else {
680                 $last_div = & $divider;
681         }
682
683         $array = explode($divider, $path);
684
685         // Remove paddings ('//' and '/./')
686         foreach(array_keys($array) as $key) {
687                 if ($array[$key] == '' || $array[$key] == '.') {
688                          unset($array[$key]);
689                 }
690         }
691
692         // Remove back-tracks ('/../')
693         $tmp = array();
694         foreach($array as $value) {
695                 if ($value == '..') {
696                         array_pop($tmp);
697                 } else {
698                         array_push($tmp, $value);
699                 }
700         }
701         $array = & $tmp;
702
703         if (empty($array)) {
704                 return $first_div;
705         } else {
706                 return $first_div . implode($divider, $array) . $last_div;
707         }
708 }
709
710 // DirectoryIndex normalize (Destructive and rough)
711 // TODO: sample.en.ja.html.gz => sample.html
712 function file_normalize($file = 'index.html.en')
713 {
714         static $simple_defaults = array(
715                 'default.htm'   => TRUE,
716                 'default.html'  => TRUE,
717                 'default.asp'   => TRUE,
718                 'default.aspx'  => TRUE,
719                 'index'                 => TRUE,        // Some system can omit the suffix
720         );
721
722         static $content_suffix = array(
723                 // index.xxx, sample.xxx
724                 'htm'   => TRUE,
725                 'html'  => TRUE,
726                 'shtml' => TRUE,
727                 'jsp'   => TRUE,
728                 'php'   => TRUE,
729                 'php3'  => TRUE,
730                 'php4'  => TRUE,
731                 'pl'    => TRUE,
732                 'py'    => TRUE,
733                 'rb'    => TRUE,
734                 'cgi'   => TRUE,
735                 'xml'   => TRUE,
736         );
737
738         static $language_suffix = array(
739                 // Reference: Apache 2.0.59 'AddLanguage' default
740                 'ca'    => TRUE,
741                 'cs'    => TRUE,        // cs
742                 'cz'    => TRUE,        // cs
743                 'de'    => TRUE,
744                 'dk'    => TRUE,        // da
745                 'el'    => TRUE,
746                 'en'    => TRUE,
747                 'eo'    => TRUE,
748                 'es'    => TRUE,
749                 'et'    => TRUE,
750                 'fr'    => TRUE,
751                 'he'    => TRUE,
752                 'hr'    => TRUE,
753                 'it'    => TRUE,
754                 'ja'    => TRUE,
755                 'ko'    => TRUE,
756                 'ltz'   => TRUE,
757                 'nl'    => TRUE,
758                 'nn'    => TRUE,
759                 'no'    => TRUE,
760                 'po'    => TRUE,
761                 'pt'    => TRUE,
762                 'pt-br' => TRUE,
763                 'ru'    => TRUE,
764                 'sv'    => TRUE,
765                 'zh-cn' => TRUE,
766                 'zh-tw' => TRUE,
767
768                 // Reference: Apache 2.0.59 default 'index.html' variants
769                 'ee'    => TRUE,
770                 'lb'    => TRUE,
771                 'var'   => TRUE,
772         );
773
774         static $charset_suffix = array(
775                 // Reference: Apache 2.0.59 'AddCharset' default
776                 'iso8859-1'     => TRUE, // ISO-8859-1
777                 'latin1'        => TRUE, // ISO-8859-1
778                 'iso8859-2'     => TRUE, // ISO-8859-2
779                 'latin2'        => TRUE, // ISO-8859-2
780                 'cen'           => TRUE, // ISO-8859-2
781                 'iso8859-3'     => TRUE, // ISO-8859-3
782                 'latin3'        => TRUE, // ISO-8859-3
783                 'iso8859-4'     => TRUE, // ISO-8859-4
784                 'latin4'        => TRUE, // ISO-8859-4
785                 'iso8859-5'     => TRUE, // ISO-8859-5
786                 'latin5'        => TRUE, // ISO-8859-5
787                 'cyr'           => TRUE, // ISO-8859-5
788                 'iso-ru'        => TRUE, // ISO-8859-5
789                 'iso8859-6'     => TRUE, // ISO-8859-6
790                 'latin6'        => TRUE, // ISO-8859-6
791                 'arb'           => TRUE, // ISO-8859-6
792                 'iso8859-7'     => TRUE, // ISO-8859-7
793                 'latin7'        => TRUE, // ISO-8859-7
794                 'grk'           => TRUE, // ISO-8859-7
795                 'iso8859-8'     => TRUE, // ISO-8859-8
796                 'latin8'        => TRUE, // ISO-8859-8
797                 'heb'           => TRUE, // ISO-8859-8
798                 'iso8859-9'     => TRUE, // ISO-8859-9
799                 'latin9'        => TRUE, // ISO-8859-9
800                 'trk'           => TRUE, // ISO-8859-9
801                 'iso2022-jp'=> TRUE, // ISO-2022-JP
802                 'jis'           => TRUE, // ISO-2022-JP
803                 'iso2022-kr'=> TRUE, // ISO-2022-KR
804                 'kis'           => TRUE, // ISO-2022-KR
805                 'iso2022-cn'=> TRUE, // ISO-2022-CN
806                 'cis'           => TRUE, // ISO-2022-CN
807                 'big5'          => TRUE,
808                 'cp-1251'       => TRUE, // ru, WINDOWS-1251
809                 'win-1251'      => TRUE, // ru, WINDOWS-1251
810                 'cp866'         => TRUE, // ru
811                 'koi8-r'        => TRUE, // ru, KOI8-r
812                 'koi8-ru'       => TRUE, // ru, KOI8-r
813                 'koi8-uk'       => TRUE, // ru, KOI8-ru
814                 'ua'            => TRUE, // ru, KOI8-ru
815                 'ucs2'          => TRUE, // ru, ISO-10646-UCS-2
816                 'ucs4'          => TRUE, // ru, ISO-10646-UCS-4
817                 'utf8'          => TRUE,
818
819                 // Reference: Apache 2.0.59 default 'index.html' variants
820                 'euc-kr'        => TRUE,
821                 'gb2312'        => TRUE,
822         );
823
824         // May uncompress by web browsers on the fly
825         // Must be at the last of the filename
826         // Reference: Apache 2.0.59 'AddEncoding'
827         static $encoding_suffix = array(
828                 'z'             => TRUE,
829                 'gz'    => TRUE,
830         );
831
832         if (! is_string($file)) return '';
833         $_file = strtolower($file);
834         if (isset($simple_defaults[$_file])) return '';
835
836
837         // Roughly removing language/character-set/encoding suffixes
838         // References:
839         //  * Apache 2 document about 'Content-negotiaton', 'mod_mime' and 'mod_negotiation'
840         //    http://httpd.apache.org/docs/2.0/content-negotiation.html
841         //    http://httpd.apache.org/docs/2.0/mod/mod_mime.html
842         //    http://httpd.apache.org/docs/2.0/mod/mod_negotiation.html
843         //  * http://www.iana.org/assignments/character-sets
844         //  * RFC3066: Tags for the Identification of Languages
845         //    http://www.ietf.org/rfc/rfc3066.txt
846         //  * ISO 639: codes of 'language names'
847         $suffixes = explode('.', $_file);
848         $body = array_shift($suffixes);
849         if ($suffixes) {
850                 // Remove the last .gz/.z
851                 $last_key = end(array_keys($suffixes));
852                 if (isset($encoding_suffix[$suffixes[$last_key]])) {
853                         unset($suffixes[$last_key]);
854                 }
855         }
856         // Cut language and charset suffixes
857         foreach($suffixes as $key => $value){
858                 if (isset($language_suffix[$value]) || isset($charset_suffix[$value])) {
859                         unset($suffixes[$key]);
860                 }
861         }
862         if (empty($suffixes)) return $body;
863
864         // Index.xxx
865         $count = count($suffixes);
866         reset($suffixes);
867         $current = current($suffixes);
868         if ($body == 'index' && $count == 1 && isset($content_suffix[$current])) return '';
869
870         return $file;
871 }
872
873 // Sort query-strings if possible (Destructive and rough)
874 // [OK] &&&&f=d&b&d&c&a=0dd  =>  a=0dd&b&c&d&f=d
875 // [OK] nothing==&eg=dummy&eg=padding&eg=foobar  =>  eg=foobar
876 function query_normalize($string = '', $equal = TRUE, $equal_cutempty = TRUE, $stortolower = TRUE)
877 {
878         if (! is_string($string)) return '';
879         if ($stortolower) $string = strtolower($string);
880
881         $array = explode('&', $string);
882
883         // Remove '&' paddings
884         foreach(array_keys($array) as $key) {
885                 if ($array[$key] == '') {
886                          unset($array[$key]);
887                 }
888         }
889
890         // Consider '='-sepalated input and paddings
891         if ($equal) {
892                 $equals = $not_equals = array();
893                 foreach ($array as $part) {
894                         if (strpos($part, '=') === FALSE) {
895                                  $not_equals[] = $part;
896                         } else {
897                                 list($key, $value) = explode('=', $part, 2);
898                                 $value = ltrim($value, '=');
899                                 if (! $equal_cutempty || $value != '') {
900                                         $equals[$key] = $value;
901                                 }
902                         }
903                 }
904
905                 $array = & $not_equals;
906                 foreach ($equals as $key => $value) {
907                         $array[] = $key . '=' . $value;
908                 }
909                 unset($equals);
910         }
911
912         natsort($array);
913         return implode('&', $array);
914 }
915
916 // ---------------------
917 // Part One : Checker
918
919 // Rough implementation of globbing
920 //
921 // USAGE: $regex = '/^' . generate_glob_regex('*.txt', '/') . '$/i';
922 //
923 function generate_glob_regex($string = '', $divider = '/')
924 {
925         static $from = array(
926                          1 => '*',
927                         11 => '?',
928         //              22 => '[',      // Maybe cause regex compilation error (e.g. '[]')
929         //              23 => ']',      //
930                 );
931         static $mid = array(
932                          1 => '_AST_',
933                         11 => '_QUE_',
934         //              22 => '_RBR_',
935         //              23 => '_LBR_',
936                 );
937         static $to = array(
938                          1 => '.*',
939                         11 => '.',
940         //              22 => '[',
941         //              23 => ']',
942                 );
943
944         if (! is_string($string)) return '';
945
946         $string = str_replace($from, $mid, $string); // Hide
947         $string = preg_quote($string, $divider);
948         $string = str_replace($mid, $to, $string);   // Unhide
949
950         return $string;
951 }
952
953 // Rough hostname checker
954 // [OK] 192.168.
955 // TODO: Strict digit, 0x, CIDR, IPv6
956 function is_ip($string = '')
957 {
958         if (preg_match('/^' .
959                 '(?:[0-9]{1,3}\.){3}[0-9]{1,3}' . '|' .
960                 '(?:[0-9]{1,3}\.){1,3}' . '$/',
961                 $string)) {
962                 return 4;       // Seems IPv4(dot-decimal)
963         } else {
964                 return 0;       // Seems not IP
965         }
966 }
967
968 // Generate host (FQDN, IPv4, ...) regex
969 // 'localhost'     : Matches with 'localhost' only
970 // 'example.org'   : Matches with 'example.org' only (See host_normalize() about 'www')
971 // '.example.org'  : Matches with ALL FQDN ended with '.example.org'
972 // '*.example.org' : Almost the same of '.example.org' except 'www.example.org'
973 // '10.20.30.40'   : Matches with IPv4 address '10.20.30.40' only
974 // [TODO] '192.'   : Matches with all IPv4 hosts started with '192.'
975 // TODO: IPv4, CIDR?, IPv6
976 function generate_host_regex($string = '', $divider = '/')
977 {
978         if (! is_string($string)) return '';
979
980         if (mb_strpos($string, '.') === FALSE)
981                 return generate_glob_regex($string, $divider);
982
983         $result = '';
984         if (is_ip($string)) {
985                 // IPv4
986                 return generate_glob_regex($string, $divider);
987         } else {
988                 // FQDN or something
989                 $part = explode('.', $string, 2);
990                 if ($part[0] == '') {
991                         $part[0] = '(?:.*\.)?'; // And all related FQDN
992                 } else if ($part[0] == '*') {
993                         $part[0] = '.*\.';      // All subdomains/hosts only
994                 } else {
995                         return generate_glob_regex($string, $divider);
996                 }
997                 $part[1] = generate_glob_regex($part[1], $divider);
998                 return implode('', $part);
999         }
1000 }
1001
1002 function get_blocklist($list = '')
1003 {
1004         static $regexs;
1005
1006         if (! isset($regexs)) {
1007                 $regexs = array();
1008                 if (file_exists(SPAM_INI_FILE)) {
1009                         $blocklist = array();
1010                         include(SPAM_INI_FILE);
1011                         //      $blocklist['badhost'] = array(
1012                         //              '*.blogspot.com',       // Blog services's subdomains (only)
1013                         //              'IANA-examples' => '#^(?:.*\.)?example\.(?:com|net|org)$#',
1014                         //      );
1015                         if (isset($blocklist['list'])) {
1016                                 $regexs['list'] = & $blocklist['list'];
1017                         } else {
1018                                 // Default
1019                                 $blocklist['list'] = array(
1020                                         'goodhost' => FALSE,
1021                                         'badhost'  => TRUE,
1022                                 );
1023                         }
1024                         foreach(array_keys($blocklist['list']) as $_list) {
1025                                 if (! isset($blocklist[$_list])) continue;
1026                                 foreach ($blocklist[$_list] as $key => $value) {
1027                                         if (is_array($value)) {
1028                                                 $regexs[$_list][$key] = array();
1029                                                 foreach($value as $_key => $_value) {
1030                                                         get_blocklist_add($regexs[$_list][$key], $_key, $_value);
1031                                                 }
1032                                         } else {
1033                                                 get_blocklist_add($regexs[$_list], $key, $value);
1034                                         }
1035                                 }
1036                                 unset($blocklist[$_list]);
1037                         }
1038                 }
1039         }
1040
1041         if ($list == '') {
1042                 return $regexs; // ALL
1043         } else if (isset($regexs[$list])) {
1044                 return $regexs[$list];
1045         } else {        
1046                 return array();
1047         }
1048 }
1049
1050 // Subroutine of get_blocklist()
1051 function get_blocklist_add(& $array, $key = 0, $value = '*.example.org')
1052 {
1053         if (is_string($key)) {
1054                 $array[$key] = & $value; // Treat $value as a regex
1055         } else {
1056                 $array[$value] = '/^' . generate_host_regex($value, '/') . '$/i';
1057         }
1058 }
1059
1060 // Blocklist metrics: Separate $host, to $blocked and not blocked
1061 function blocklist_distiller(& $hosts, $keys = array('goodhost', 'badhost'), $asap = FALSE)
1062 {
1063         if (! is_array($hosts)) $hosts = array($hosts);
1064         if (! is_array($keys))  $keys  = array($keys);
1065
1066         $list = get_blocklist('list');
1067         $blocked = array();
1068
1069         foreach($keys as $key){
1070                 foreach (get_blocklist($key) as $label => $regex) {
1071                         if (is_array($regex)) {
1072                                 foreach($regex as $_label => $_regex) {
1073                                         $group = preg_grep($_regex, $hosts);
1074                                         if ($group) {
1075                                                 $hosts = array_diff($hosts, $group);
1076                                                 $blocked[$key][$label][$_label] = $group;
1077                                                 if ($asap && $list[$key]) break;
1078                                         }
1079                                 }
1080                         } else {
1081                                 $group = preg_grep($regex, $hosts);
1082                                 if ($group) {
1083                                         $hosts = array_diff($hosts, $group);
1084                                         $blocked[$key][$label] = $group;
1085                                         if ($asap && $list[$key]) break;
1086                                 }
1087                         }
1088                 }
1089         }
1090
1091         return $blocked;
1092 }
1093
1094 // Simple example for badhost (not used now)
1095 function is_badhost($hosts = array(), $asap = TRUE, $bool = TRUE)
1096 {
1097         $list = get_blocklist('list');
1098         $blocked = blocklist_distiller($hosts, array_keys($list), $asap);
1099         foreach($list as $key=>$type){
1100                 if (! $type) unset($blocked[$key]); // Ignore goodhost etc
1101         }
1102
1103         return $bool ? ! empty($blocked) : $blocked;
1104 }
1105
1106 // Default (enabled) methods and thresholds (for content insertion)
1107 function check_uri_spam_method($times = 1, $t_area = 0, $rule = TRUE)
1108 {
1109         $times  = intval($times);
1110         $t_area = intval($t_area);
1111
1112         $positive = array(
1113                 // Thresholds
1114                 'quantity'     =>  8 * $times,  // Allow N URIs
1115                 'non_uniqhost' =>  3 * $times,  // Allow N duped (and normalized) Hosts
1116                 //'non_uniquri'=>  3 * $times,  // Allow N duped (and normalized) URIs
1117
1118                 // Areas
1119                 'area_anchor'  => $t_area,      // Using <a href> HTML tag
1120                 'area_bbcode'  => $t_area,      // Using [url] or [link] BBCode
1121                 //'uri_anchor' => $t_area,      // URI inside <a href> HTML tag
1122                 //'uri_bbcode' => $t_area,      // URI inside [url] or [link] BBCode
1123         );
1124         if ($rule) {
1125                 $bool = array(
1126                         // Rules
1127                         //'asap'   => TRUE,     // Quit or return As Soon As Possible
1128                         'uniqhost' => TRUE,     // Show uniq host (at block notification mail)
1129                         'badhost'  => TRUE,     // Check badhost
1130                 );
1131         } else {
1132                 $bool = array();
1133         }
1134
1135         // Remove non-$positive values
1136         foreach (array_keys($positive) as $key) {
1137                 if ($positive[$key] < 0) unset($positive[$key]);
1138         }
1139
1140         return $positive + $bool;
1141 }
1142
1143 // Simple/fast spam check
1144 function check_uri_spam($target = '', $method = array())
1145 {
1146         // Return value
1147         $progress = array(
1148                 'method'  => array(
1149                         // Theme to do  => Dummy, optional value, or optional array()
1150                         //'quantity'    => 8,
1151                         //'uniqhost'    => TRUE,
1152                         //'non_uniqhost'=> 3,
1153                         //'non_uniquri' => 3,
1154                         //'badhost'     => TRUE,
1155                         //'area_anchor' => 0,
1156                         //'area_bbcode' => 0,
1157                         //'uri_anchor'  => 0,
1158                         //'uri_bbcode'  => 0,
1159                 ),
1160                 'sum' => array(
1161                         // Theme        => Volume found (int)
1162                 ),
1163                 'is_spam' => array(
1164                         // Flag. If someting defined here,
1165                         // one or more spam will be included
1166                         // in this report
1167                 ),
1168                 'blocked' => array(
1169                         // Hosts blocked
1170                         //'category' => array(
1171                         //      'host',
1172                         //)
1173                 ),
1174                 'hosts' => array(
1175                         // Hosts not blocked
1176                 ),
1177         );
1178
1179         // Aliases
1180         $sum     = & $progress['sum'];
1181         $is_spam = & $progress['is_spam'];
1182         $progress['method'] = & $method;        // Argument
1183         $blocked = & $progress['blocked'];
1184         $hosts   = & $progress['hosts'];
1185         $asap    = isset($method['asap']);
1186
1187         // Init
1188         if (! is_array($method) || empty($method)) {
1189                 $method = check_uri_spam_method();
1190         }
1191         foreach(array_keys($method) as $key) {
1192                 if (! isset($sum[$key])) $sum[$key] = 0;
1193         }
1194
1195         if (is_array($target)) {
1196                 foreach($target as $str) {
1197                         if (! is_string($str)) continue;
1198
1199                         $_progress = check_uri_spam($str, $method);     // Recurse
1200
1201                         // Merge $sum
1202                         $_sum = & $_progress['sum'];
1203                         foreach (array_keys($_sum) as $key) {
1204                                 if (! isset($sum[$key])) {
1205                                         $sum[$key] = & $_sum[$key];
1206                                 } else {
1207                                         $sum[$key] += $_sum[$key];
1208                                 }
1209                         }
1210
1211                         // Merge $is_spam
1212                         $_is_spam = & $_progress['is_spam'];
1213                         foreach (array_keys($_is_spam) as $key) {
1214                                 $is_spam[$key] = TRUE;
1215                                 if ($asap) break;
1216                         }
1217                         if ($asap && $is_spam) break;
1218
1219                         // Merge only
1220                         $blocked = array_merge_leaves($blocked, $_progress['blocked'], FALSE, FALSE);
1221                         $hosts   = array_merge_leaves($hosts,   $_progress['hosts'],   FALSE, FALSE);
1222                 }
1223
1224                 // Unique values
1225                 $blocked = array_unique_recursive($blocked);
1226                 $hosts   = array_unique_recursive($hosts);
1227
1228                 // Renumber numeric keys
1229                 array_renumber_numeric_keys($blocked);
1230                 array_renumber_numeric_keys($hosts);
1231
1232                 // Recount $sum['badhost']
1233                 $sum['badhost'] = array_count_leaves($blocked);
1234
1235                 return $progress;
1236         }
1237
1238         // Area: There's HTML anchor tag
1239         if ((! $asap || ! $is_spam) && isset($method['area_anchor'])) {
1240                 $key = 'area_anchor';
1241                 $_asap = isset($method['asap']) ? array('asap' => TRUE) : array();
1242                 $result = area_pickup($target, array($key => TRUE) + $_asap);
1243                 if ($result) {
1244                         $sum[$key] = $result[$key];
1245                         if (isset($method[$key]) && $sum[$key] > $method[$key]) {
1246                                 $is_spam[$key] = TRUE;
1247                         }
1248                 }
1249         }
1250
1251         // Area: There's 'BBCode' linking tag
1252         if ((! $asap || ! $is_spam) && isset($method['area_bbcode'])) {
1253                 $key = 'area_bbcode';
1254                 $_asap = isset($method['asap']) ? array('asap' => TRUE) : array();
1255                 $result = area_pickup($target, array($key => TRUE) + $_asap);
1256                 if ($result) {
1257                         $sum[$key] = $result[$key];
1258                         if (isset($method[$key]) && $sum[$key] > $method[$key]) {
1259                                 $is_spam[$key] = TRUE;
1260                         }
1261                 }
1262         }
1263
1264         // Return if ...
1265         if ($asap && $is_spam) return $progress;
1266
1267         // URI: Pickup
1268         $pickups = uri_pickup_normalize(spam_uri_pickup($target, $method));
1269
1270         // Return if ...
1271         if (empty($pickups)) return $progress;
1272
1273         // URI: Check quantity
1274         $sum['quantity'] += count($pickups);
1275                 // URI quantity
1276         if ((! $asap || ! $is_spam) && isset($method['quantity']) &&
1277                 $sum['quantity'] > $method['quantity']) {
1278                 $is_spam['quantity'] = TRUE;
1279         }
1280
1281         // URI: used inside HTML anchor tag pair
1282         if ((! $asap || ! $is_spam) && isset($method['uri_anchor'])) {
1283                 $key = 'uri_anchor';
1284                 foreach($pickups as $pickup) {
1285                         if (isset($pickup['area'][$key])) {
1286                                 $sum[$key] += $pickup['area'][$key];
1287                                 if(isset($method[$key]) &&
1288                                         $sum[$key] > $method[$key]) {
1289                                         $is_spam[$key] = TRUE;
1290                                         if ($asap && $is_spam) break;
1291                                 }
1292                                 if ($asap && $is_spam) break;
1293                         }
1294                 }
1295         }
1296
1297         // URI: used inside 'BBCode' pair
1298         if ((! $asap || ! $is_spam) && isset($method['uri_bbcode'])) {
1299                 $key = 'uri_bbcode';
1300                 foreach($pickups as $pickup) {
1301                         if (isset($pickup['area'][$key])) {
1302                                 $sum[$key] += $pickup['area'][$key];
1303                                 if(isset($method[$key]) &&
1304                                         $sum[$key] > $method[$key]) {
1305                                         $is_spam[$key] = TRUE;
1306                                         if ($asap && $is_spam) break;
1307                                 }
1308                                 if ($asap && $is_spam) break;
1309                         }
1310                 }
1311         }
1312
1313         // URI: Uniqueness (and removing non-uniques)
1314         if ((! $asap || ! $is_spam) && isset($method['non_uniquri'])) {
1315
1316                 $uris = array();
1317                 foreach (array_keys($pickups) as $key) {
1318                         $uris[$key] = uri_pickup_implode($pickups[$key]);
1319                 }
1320                 $count = count($uris);
1321                 $uris  = array_unique($uris);
1322                 $sum['non_uniquri'] += $count - count($uris);
1323                 if ($sum['non_uniquri'] > $method['non_uniquri']) {
1324                         $is_spam['non_uniquri'] = TRUE;
1325                 }
1326                 if (! $asap || ! $is_spam) {
1327                         foreach (array_diff(array_keys($pickups),
1328                                 array_keys($uris)) as $remove) {
1329                                 unset($pickups[$remove]);
1330                         }
1331                 }
1332                 unset($uris);
1333         }
1334
1335         // Return if ...
1336         if ($asap && $is_spam) return $progress;
1337
1338         // Host: Uniqueness (uniq / non-uniq)
1339         foreach ($pickups as $pickup) $hosts[] = & $pickup['host'];
1340         $hosts = array_unique($hosts);
1341         $sum['uniqhost'] += count($hosts);
1342         if ((! $asap || ! $is_spam) && isset($method['non_uniqhost'])) {
1343                 $sum['non_uniqhost'] = $sum['quantity'] - $sum['uniqhost'];
1344                 if ($sum['non_uniqhost'] > $method['non_uniqhost']) {
1345                         $is_spam['non_uniqhost'] = TRUE;
1346                 }
1347         }
1348
1349         // Return if ...
1350         if ($asap && $is_spam) return $progress;
1351
1352         // URI: Bad host (Separate good/bad hosts from $hosts)
1353         if ((! $asap || ! $is_spam) && isset($method['badhost'])) {
1354
1355                 // is_badhost()
1356                 $list = get_blocklist('list');
1357                 $blocked = blocklist_distiller($hosts, array_keys($list), $asap);
1358                 foreach($list as $key=>$type){
1359                         if (! $type) unset($blocked[$key]); // Ignore goodhost etc
1360                 }
1361                 unset($list);
1362
1363                 if (! empty($blocked)) $is_spam['badhost'] = TRUE;
1364         }
1365
1366         return $progress;
1367 }
1368
1369 // Count leaves (A leaf = value that is not an array, or an empty array)
1370 function array_count_leaves($array = array(), $count_empty = FALSE)
1371 {
1372         if (! is_array($array) || (empty($array) && $count_empty)) return 1;
1373
1374         // Recurse
1375         $count = 0;
1376         foreach ($array as $part) {
1377                 $count += array_count_leaves($part, $count_empty);
1378         }
1379         return $count;
1380 }
1381
1382 // Merge two leaves' value
1383 function array_merge_leaves(& $array1, & $array2, $unique_values = TRUE, $renumber_numeric = TRUE)
1384 {
1385         $array = array_merge_recursive($array1, $array2);
1386
1387         // Redundant values (and keys) are vanished
1388         if ($unique_values) $array = array_unique_recursive($array);
1389
1390         // All NUMERIC keys are always renumbered from 0
1391         if ($renumber_numeric) array_renumber_numeric_keys($array);
1392
1393         return $array;
1394 }
1395
1396 // An array-leaves to a flat array
1397 function array_flat_leaves($array, $unique = TRUE)
1398 {
1399         if (! is_array($array)) return $array;
1400
1401         $tmp = array();
1402         foreach(array_keys($array) as $key) {
1403                 if (is_array($array[$key])) {
1404                         // Recurse
1405                         foreach(array_flat_leaves($array[$key]) as $_value) {
1406                                 $tmp[] = $_value;
1407                         }
1408                 } else {
1409                         $tmp[] = & $array[$key];
1410                 }
1411         }
1412
1413         return $unique ? array_values(array_unique($tmp)) : $tmp;
1414 }
1415
1416 // ---------------------
1417 // Reporting
1418
1419 // TODO: Don't show unused $method!
1420 // Summarize $progress (blocked only)
1421 function summarize_spam_progress($progress = array(), $blockedonly = FALSE)
1422 {
1423         if ($blockedonly) {
1424                 $tmp = array_keys($progress['is_spam']);
1425         } else {
1426                 $tmp = array();
1427                 $method = & $progress['method'];
1428                 if (isset($progress['sum'])) {
1429                         foreach ($progress['sum'] as $key => $value) {
1430                                 if (isset($method[$key]) && $value) {
1431                                         $tmp[] = $key . '(' . $value . ')';
1432                                 }
1433                         }
1434                 }
1435         }
1436
1437         return implode(', ', $tmp);
1438 }
1439
1440 function summarize_detail_badhost($progress = array())
1441 {
1442         if (! isset($progress['blocked']) || empty($progress['blocked'])) return '';
1443
1444         // Flat per group
1445         $blocked = array();
1446         foreach($progress['blocked'] as $list => $lvalue) {
1447                 foreach($lvalue as $group => $gvalue) {
1448                         $flat = implode(', ', array_flat_leaves($gvalue));
1449                         if ($flat == $group) {
1450                                 $blocked[$list][]       = $flat;
1451                         } else {
1452                                 $blocked[$list][$group] = $flat;
1453                         }
1454                 }
1455         }
1456
1457         // Shrink per list
1458         // From: 'A-1' => array('ie.to')
1459         // To:   'A-1' => 'ie.to'
1460         foreach($blocked as $list => $lvalue) {
1461                 if (is_array($lvalue) &&
1462                    count($lvalue) == 1 &&
1463                    is_numeric(key($lvalue))) {
1464                     $blocked[$list] = current($lvalue);
1465                 }
1466         }
1467
1468         return var_export_shrink($blocked, TRUE, TRUE);
1469 }
1470
1471 function summarize_detail_newtral($progress = array())
1472 {
1473         if (! isset($progress['hosts'])    ||
1474             ! is_array($progress['hosts']) ||
1475             empty($progress['hosts'])) return '';
1476
1477         // Sort by domain
1478         $tmp = array();
1479         foreach($progress['hosts'] as $value) {
1480                 $tmp[delimiter_reverse($value)] = $value;
1481         }
1482         ksort($tmp);
1483
1484         return count($tmp) . ' (' .implode(', ', $tmp) . ')';
1485 }
1486
1487
1488 // ---------------------
1489 // Exit
1490
1491 // Common bahavior for blocking
1492 // NOTE: Call this function from various blocking feature, to disgueise the reason 'why blocked'
1493 function spam_exit($mode = '', $data = array())
1494 {
1495         switch ($mode) {
1496                 case '':        echo("\n");     break;
1497                 case 'dump':
1498                         echo('<pre>' . "\n");
1499                         echo htmlspecialchars(var_export($data, TRUE));
1500                         echo('</pre>' . "\n");
1501                         break;
1502         };
1503
1504         // Force exit
1505         exit;
1506 }
1507
1508
1509 // ---------------------
1510 // Simple filtering
1511
1512 // TODO: Record them
1513 // Simple/fast spam filter ($target: 'a string' or an array())
1514 function pkwk_spamfilter($action, $page, $target = array('title' => ''), $method = array(), $exitmode = '')
1515 {
1516         $progress = check_uri_spam($target, $method);
1517
1518         if (! empty($progress['is_spam'])) {
1519                 // Mail to administrator(s)
1520                 pkwk_spamnotify($action, $page, $target, $progress, $method);
1521
1522                 // Exit
1523                 spam_exit($exitmode, $progress);
1524         }
1525 }
1526
1527 // ---------------------
1528 // PukiWiki original
1529
1530 // Mail to administrator(s)
1531 function pkwk_spamnotify($action, $page, $target = array('title' => ''), $progress = array(), $method = array())
1532 {
1533         global $notify, $notify_subject;
1534
1535         if (! $notify) return;
1536
1537         $asap = isset($method['asap']);
1538
1539         $summary['ACTION']  = 'Blocked by: ' . summarize_spam_progress($progress, TRUE);
1540         if (! $asap) {
1541                 $summary['METRICS'] = summarize_spam_progress($progress);
1542         }
1543
1544         $tmp = summarize_detail_badhost($progress);
1545         if ($tmp != '') $summary['DETAIL_BADHOST'] = $tmp;
1546
1547         $tmp = summarize_detail_newtral($progress);
1548         if (! $asap && $tmp != '') $summary['DETAIL_NEUTRAL_HOST'] = $tmp;
1549
1550         $summary['COMMENT'] = $action;
1551         $summary['PAGE']    = '[blocked] ' . (is_pagename($page) ? $page : '');
1552         $summary['URI']     = get_script_uri() . '?' . rawurlencode($page);
1553         $summary['USER_AGENT']  = TRUE;
1554         $summary['REMOTE_ADDR'] = TRUE;
1555         pkwk_mail_notify($notify_subject,  var_export($target, TRUE), $summary, TRUE);
1556 }
1557
1558 ?>