OSDN Git Service

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