OSDN Git Service

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