OSDN Git Service

Reporting badhost detail (by *.example.org, *.foobar, ...)
[pukiwiki/pukiwiki_sandbox.git] / spam / spam.php
1 <?php
2 // $Id: spam.php,v 1.82 2006/12/30 02:06:30 henoheno Exp $
3 // Copyright (C) 2006 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 // (PHP 4 >= 4.3.0): preg_match_all(PREG_OFFSET_CAPTURE): $method['uri_XXX'] related feature
8 // (PHP 4 >= 4.2.0): var_export(): mail-reporting and dump related
9
10 if (! defined('SPAM_INI_FILE')) define('SPAM_INI_FILE', 'spam.ini.php');
11
12 // ---------------------
13 // URI pickup
14
15 // Return an array of URIs in the $string
16 // [OK] http://nasty.example.org#nasty_string
17 // [OK] http://nasty.example.org:80/foo/xxx#nasty_string/bar
18 // [OK] ftp://nasty.example.org:80/dfsdfs
19 // [OK] ftp://cnn.example.com&story=breaking_news@10.0.0.1/top_story.htm (from RFC3986)
20 function uri_pickup($string = '', $normalize = TRUE,
21         $preserve_rawuri = FALSE, $preserve_chunk = TRUE)
22 {
23         // Not available for: IDN(ignored)
24         $array = array();
25         preg_match_all(
26                 // scheme://userinfo@host:port/path/or/pathinfo/maybefile.and?query=string#fragment
27                 // Refer RFC3986 (Regex below is not strict)
28                 '#(\b[a-z][a-z0-9.+-]{1,8})://' .       // 1: Scheme
29                 '(?:' .
30                         '([^\s<>"\'\[\]/\#?@]*)' .              // 2: Userinfo (Username)
31                 '@)?' .
32                 '(' .
33                         // 3: Host
34                         '\[[0-9a-f:.]+\]' . '|' .                               // IPv6([colon-hex and dot]): RFC2732
35                         '(?:[0-9]{1-3}\.){3}[0-9]{1-3}' . '|' . // IPv4(dot-decimal): 001.22.3.44
36                         '[^\s<>"\'\[\]:/\#?]+' .                                // FQDN: foo.example.org
37                 ')' .
38                 '(?::([0-9]*))?' .                                      // 4: Port
39                 '((?:/+[^\s<>"\'\[\]/\#]+)*/+)?' .      // 5: Directory path or path-info
40                 '([^\s<>"\'\[\]\#?]+)?' .                       // 6: File?
41                 '(?:\?([^\s<>"\'\[\]\#]+))?' .          // 7: Query string
42                 '(?:\#([a-z0-9._~%!$&\'()*+,;=:@-]*))?' .       // 8: Fragment
43                 '#i',
44                  $string, $array, PREG_SET_ORDER | PREG_OFFSET_CAPTURE
45         );
46
47         // Shrink $array
48         static $parts = array(
49                 1 => 'scheme', 2 => 'userinfo', 3 => 'host', 4 => 'port',
50                 5 => 'path', 6 => 'file', 7 => 'query', 8 => 'fragment'
51         );
52         $default = array('');
53         foreach(array_keys($array) as $uri) {
54                 $_uri = & $array[$uri];
55                 array_rename_keys($_uri, $parts, TRUE, $default);
56
57                 $offset = $_uri['scheme'][1]; // Scheme's offset
58                 foreach(array_keys($_uri) as $part) {
59                         // Remove offsets for each part
60                         $_uri[$part] = & $_uri[$part][0];
61                 }
62
63                 if ($normalize) {
64                         $_uri['scheme'] = scheme_normalize($_uri['scheme']);
65                         if ($_uri['scheme'] === '') {
66                                 unset($array[$uri]);
67                                 continue;
68                         }
69                         $_uri['host']  = strtolower($_uri['host']);
70                         $_uri['port']  = port_normalize($_uri['port'], $_uri['scheme'], FALSE);
71                         $_uri['path']  = path_normalize($_uri['path']);
72                         if ($preserve_rawuri) $_uri['rawuri'] = & $_uri[0];
73
74                         // DEBUG
75                         //$_uri['uri'] = uri_array_implode($_uri);
76                 } else {
77                         $_uri['uri'] = & $_uri[0]; // Raw
78                 }
79                 unset($_uri[0]); // Matched string itself
80                 if (! $preserve_chunk) {
81                         unset(
82                                 $_uri['scheme'],
83                                 $_uri['userinfo'],
84                                 $_uri['host'],
85                                 $_uri['port'],
86                                 $_uri['path'],
87                                 $_uri['file'],
88                                 $_uri['query'],
89                                 $_uri['fragment']
90                         );
91                 }
92
93                 // Area offset for area_measure()
94                 $_uri['area']['offset'] = $offset;
95         }
96
97         return $array;
98 }
99
100 // Destructive normalize of URI array
101 // NOTE: Give me the uri_pickup() result with chunks
102 function uri_array_normalize(& $pickups, $preserve = TRUE)
103 {
104         if (! is_array($pickups)) return $pickups;
105
106         foreach (array_keys($pickups) as $key) {
107                 $_key = & $pickups[$key];
108                 $_key['path']     = isset($_key['path']) ? strtolower($_key['path']) : '';
109                 $_key['file']     = isset($_key['file']) ? file_normalize($_key['file']) : '';
110                 $_key['query']    = isset($_key['query']) ? query_normalize(strtolower($_key['query']), TRUE) : '';
111                 $_key['fragment'] = (isset($_key['fragment']) && $preserve) ?
112                         strtolower($_key['fragment']) : ''; // Just ignore
113         }
114
115         return $pickups;
116 }
117
118 // An URI array => An URI (See uri_pickup())
119 function uri_array_implode($uri = array())
120 {
121         if (empty($uri) || ! is_array($uri)) return NULL;
122
123         $tmp = array();
124         if (isset($uri['scheme']) && $uri['scheme'] !== '') {
125                 $tmp[] = & $uri['scheme'];
126                 $tmp[] = '://';
127         }
128         if (isset($uri['userinfo']) && $uri['userinfo'] !== '') {
129                 $tmp[] = & $uri['userinfo'];
130                 $tmp[] = '@';
131         }
132         if (isset($uri['host']) && $uri['host'] !== '') {
133                 $tmp[] = & $uri['host'];
134         }
135         if (isset($uri['port']) && $uri['port'] !== '') {
136                 $tmp[] = ':';
137                 $tmp[] = & $uri['port'];
138         }
139         if (isset($uri['path']) && $uri['path'] !== '') {
140                 $tmp[] = & $uri['path'];
141         }
142         if (isset($uri['file']) && $uri['file'] !== '') {
143                 $tmp[] = & $uri['file'];
144         }
145         if (isset($uri['query']) && $uri['query'] !== '') {
146                 $tmp[] = '?';
147                 $tmp[] = & $uri['query'];
148         }
149         if (isset($uri['fragment']) && $uri['fragment'] !== '') {
150                 $tmp[] = '#';
151                 $tmp[] = & $uri['fragment'];
152         }
153
154         return implode('', $tmp);
155 }
156
157 // $array['something'] => $array['wanted']
158 function array_rename_keys(& $array, $keys = array('from' => 'to'), $force = FALSE, $default = '')
159 {
160         if (! is_array($array) || ! is_array($keys)) return FALSE;
161
162         // Nondestructive test
163         if (! $force)
164                 foreach(array_keys($keys) as $from)
165                         if (! isset($array[$from]))
166                                 return FALSE;
167
168         foreach($keys as $from => $to) {
169                 if ($from === $to) continue;
170                 if (! $force || isset($array[$from])) {
171                         $array[$to] = & $array[$from];
172                         unset($array[$from]);
173                 } else  {
174                         $array[$to] = $default;
175                 }
176         }
177
178         return TRUE;
179 }
180
181 // ---------------------
182 // Area pickup
183
184 // Pickup all of markup areas
185 function area_pickup($string = '', $method = array())
186 {
187         $area = array();
188         if (empty($method)) return $area;
189
190         // Anchor tag pair by preg_match and preg_match_all()
191         // [OK] <a href></a>
192         // [OK] <a href=  >Good site!</a>
193         // [OK] <a href= "#" >test</a>
194         // [OK] <a href="http://nasty.example.com">visit http://nasty.example.com/</a>
195         // [OK] <a href=\'http://nasty.example.com/\' >discount foobar</a> 
196         // [NG] <a href="http://ng.example.com">visit http://ng.example.com _not_ended_
197         $regex = '#<a\b[^>]*\bhref\b[^>]*>.*?</a\b[^>]*(>)#i';
198         if (isset($method['area_anchor'])) {
199                 $areas = array();
200                 $count = isset($method['asap']) ?
201                         preg_match($regex, $string) :
202                         preg_match_all($regex, $string, $areas);
203                 if (! empty($count)) $area['area_anchor'] = $count;
204         }
205         if (isset($method['uri_anchor'])) {
206                 $areas = array();
207                 preg_match_all($regex, $string, $areas, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
208                 foreach(array_keys($areas) as $_area) {
209                         $areas[$_area] =  array(
210                                 $areas[$_area][0][1], // Area start (<a href>)
211                                 $areas[$_area][1][1], // Area end   (</a>)
212                         );
213                 }
214                 if (! empty($areas)) $area['uri_anchor'] = $areas;
215         }
216
217         // phpBB's "BBCode" pair by preg_match and preg_match_all()
218         // [OK] [url][/url]
219         // [OK] [url]http://nasty.example.com/[/url]
220         // [OK] [link]http://nasty.example.com/[/link]
221         // [OK] [url=http://nasty.example.com]visit http://nasty.example.com/[/url]
222         // [OK] [link http://nasty.example.com/]buy something[/link]
223         $regex = '#\[(url|link)\b[^\]]*\].*?\[/\1\b[^\]]*(\])#i';
224         if (isset($method['area_bbcode'])) {
225                 $areas = array();
226                 $count = isset($method['asap']) ?
227                         preg_match($regex, $string) :
228                         preg_match_all($regex, $string, $areas, PREG_SET_ORDER);
229                 if (! empty($count)) $area['area_bbcode'] = $count;
230         }
231         if (isset($method['uri_bbcode'])) {
232                 $areas = array();
233                 preg_match_all($regex, $string, $areas, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
234                 foreach(array_keys($areas) as $_area) {
235                         $areas[$_area] = array(
236                                 $areas[$_area][0][1], // Area start ([url])
237                                 $areas[$_area][2][1], // Area end   ([/url])
238                         );
239                 }
240                 if (! empty($areas)) $area['uri_bbcode'] = $areas;
241         }
242
243         // Various Wiki syntax
244         // [text_or_uri>text_or_uri]
245         // [text_or_uri:text_or_uri]
246         // [text_or_uri|text_or_uri]
247         // [text_or_uri->text_or_uri]
248         // [text_or_uri text_or_uri] // MediaWiki
249         // MediaWiki: [http://nasty.example.com/ visit http://nasty.example.com/]
250
251         return $area;
252 }
253
254 // If in doubt, it's a little doubtful
255 // if (Area => inside <= Area) $brief += -1
256 function area_measure($areas, & $array, $belief = -1, $a_key = 'area', $o_key = 'offset')
257 {
258         if (! is_array($areas) || ! is_array($array)) return;
259
260         $areas_keys = array_keys($areas);
261         foreach(array_keys($array) as $u_index) {
262                 $offset = isset($array[$u_index][$o_key]) ?
263                         intval($array[$u_index][$o_key]) : 0;
264                 foreach($areas_keys as $a_index) {
265                         if (isset($array[$u_index][$a_key])) {
266                                 $offset_s = intval($areas[$a_index][0]);
267                                 $offset_e = intval($areas[$a_index][1]);
268                                 // [Area => inside <= Area]
269                                 if ($offset_s < $offset && $offset < $offset_e) {
270                                         $array[$u_index][$a_key] += $belief;
271                                 }
272                         }
273                 }
274         }
275 }
276
277 // ---------------------
278 // Spam-uri pickup
279
280 // Domain exposure callback (See spam_uri_pickup_preprocess())
281 // http://victim.example.org/?foo+site:nasty.example.com+bar
282 // => http://nasty.example.com/?refer=victim.example.org
283 // NOTE: 'refer=' is not so good for (at this time).
284 // Consider about using IP address of the victim, try to avoid that.
285 function _preg_replace_callback_domain_exposure($matches = array())
286 {
287         $result = '';
288
289         // Preserve the victim URI as a complicity or ...
290         if (isset($matches[5])) {
291                 $result =
292                         $matches[1] . '://' .   // scheme
293                         $matches[2] . '/' .             // victim.example.org
294                         $matches[3];                    // The rest of all (before victim)
295         }
296
297         // Flipped URI
298         if (isset($matches[4])) {
299                 $result = 
300                         $matches[1] . '://' .   // scheme
301                         $matches[4] .                   // nasty.example.com
302                         '/?refer=' . strtolower($matches[2]) .  // victim.example.org
303                         ' ' . $result;
304         }
305
306         return $result;
307 }
308
309 // Preprocess: rawurldecode() and adding space(s) and something
310 // to detect/count some URIs _if possible_
311 // NOTE: It's maybe danger to var_dump(result). [e.g. 'javascript:']
312 // [OK] http://victim.example.org/go?http%3A%2F%2Fnasty.example.org
313 // [OK] http://victim.example.org/http://nasty.example.org
314 function spam_uri_pickup_preprocess($string = '')
315 {
316         if (! is_string($string)) return '';
317
318         $string = rawurldecode($string);
319
320         // Domain exposure (See _preg_replace_callback_domain_exposure())
321         $string = preg_replace_callback(
322                 array(
323                         // Something Google: http://www.google.com/supported_domains
324                         '#(http)://([a-z0-9.]+\.google\.[a-z]{2,3}(?:\.[a-z]{2})?)/' .
325                         '([a-z0-9?=&.%_+-]+)' .         // ?query=foo+
326                         '\bsite:([a-z0-9.%_-]+)' .      // site:nasty.example.com
327                         //'()' .        // Preserve or remove?
328                         '#i',
329                 ),
330                 '_preg_replace_callback_domain_exposure',
331                 $string
332         );
333
334         // URI exposure (uriuri => uri uri)
335         $string = preg_replace(
336                 array(
337                         '#(?<! )(?:https?|ftp):/#i',
338                 //      '#[a-z][a-z0-9.+-]{1,8}://#i',
339                 //      '#[a-z][a-z0-9.+-]{1,8}://#i'
340                 ),
341                 ' $0',
342                 $string
343         );
344
345         return $string;
346 }
347
348 // Main function of spam-uri pickup
349 function spam_uri_pickup($string = '', $method = array())
350 {
351         if (! is_array($method) || empty($method)) {
352                 $method = check_uri_spam_method();
353         }
354
355         $string = spam_uri_pickup_preprocess($string);
356
357         $array  = uri_pickup($string);
358
359         // Area elevation of URIs, for '(especially external)link' intension
360         if (! empty($array)) {
361                 $_method = array();
362                 if (isset($method['uri_anchor'])) $_method['uri_anchor'] = & $method['uri_anchor'];
363                 if (isset($method['uri_bbcode'])) $_method['uri_bbcode'] = & $method['uri_bbcode'];
364                 $areas = area_pickup($string, $_method, TRUE);
365                 if (! empty($areas)) {
366                         $area_shadow = array();
367                         foreach (array_keys($array) as $key) {
368                                 $area_shadow[$key] = & $array[$key]['area'];
369                                 foreach (array_keys($_method) as $_key) {
370                                         $area_shadow[$key][$_key] = 0;
371                                 }
372                         }
373                         foreach (array_keys($_method) as $_key) {
374                                 if (isset($areas[$_key])) {
375                                         area_measure($areas[$_key], $area_shadow, 1, $_key);
376                                 }
377                         }
378                 }
379         }
380
381         // Remove 'offset's for area_measure()
382         foreach(array_keys($array) as $key)
383                 unset($array[$key]['area']['offset']);
384
385         return $array;
386 }
387
388
389 // ---------------------
390 // Normalization
391
392 // Scheme normalization: Renaming the schemes
393 // snntp://example.org =>  nntps://example.org
394 // NOTE: Keep the static lists simple. See also port_normalize().
395 function scheme_normalize($scheme = '', $considerd_harmfull = TRUE)
396 {
397         // Abbreviations considerable they don't have link intension
398         static $abbrevs = array(
399                 'ttp'   => 'http',
400                 'ttps'  => 'https',
401         );
402
403         // Alias => normalized
404         static $aliases = array(
405                 'pop'   => 'pop3',
406                 'news'  => 'nntp',
407                 'imap4' => 'imap',
408                 'snntp' => 'nntps',
409                 'snews' => 'nntps',
410                 'spop3' => 'pop3s',
411                 'pops'  => 'pop3s',
412         );
413
414         $scheme = strtolower(trim($scheme));
415         if (isset($abbrevs[$scheme])) {
416                 if ($considerd_harmfull) {
417                         $scheme = $abbrevs[$scheme];
418                 } else {
419                         $scheme = '';
420                 }
421         }
422         if (isset($aliases[$scheme])) $scheme = $aliases[$scheme];
423
424         return $scheme;
425 }
426
427 // Port normalization: Suppress the (redundant) default port
428 // HTTP://example.org:80/ => http://example.org/
429 // HTTP://example.org:8080/ => http://example.org:8080/
430 // HTTPS://example.org:443/ => https://example.org/
431 function port_normalize($port, $scheme, $scheme_normalize = TRUE)
432 {
433         // Schemes that users _maybe_ want to add protocol-handlers
434         // to their web browsers. (and attackers _maybe_ want to use ...)
435         // Reference: http://www.iana.org/assignments/port-numbers
436         static $array = array(
437                 // scheme => default port
438                 'ftp'     =>    21,
439                 'ssh'     =>    22,
440                 'telnet'  =>    23,
441                 'smtp'    =>    25,
442                 'tftp'    =>    69,
443                 'gopher'  =>    70,
444                 'finger'  =>    79,
445                 'http'    =>    80,
446                 'pop3'    =>   110,
447                 'sftp'    =>   115,
448                 'nntp'    =>   119,
449                 'imap'    =>   143,
450                 'irc'     =>   194,
451                 'wais'    =>   210,
452                 'https'   =>   443,
453                 'nntps'   =>   563,
454                 'rsync'   =>   873,
455                 'ftps'    =>   990,
456                 'telnets' =>   992,
457                 'imaps'   =>   993,
458                 'ircs'    =>   994,
459                 'pop3s'   =>   995,
460                 'mysql'   =>  3306,
461         );
462
463         $port = trim($port);
464         if ($port === '') return $port;
465
466         if ($scheme_normalize) $scheme = scheme_normalize($scheme);
467         if (isset($array[$scheme]) && $port == $array[$scheme])
468                 $port = ''; // Ignore the defaults
469
470         return $port;
471 }
472
473 // Path normalization
474 // http://example.org => http://example.org/
475 // http://example.org#hoge => http://example.org/#hoge
476 // http://example.org/path/a/b/./c////./d => http://example.org/path/a/b/c/d
477 // http://example.org/path/../../a/../back => http://example.org/back
478 function path_normalize($path = '', $divider = '/', $addroot = TRUE)
479 {
480         if (! is_string($path) || $path == '')
481                 return $addroot ? $divider : '';
482
483         $path = trim($path);
484         $last = ($path[strlen($path) - 1] == $divider) ? $divider : '';
485         $array = explode($divider, $path);
486
487         // Remove paddings
488         foreach(array_keys($array) as $key) {
489                 if ($array[$key] == '' || $array[$key] == '.')
490                          unset($array[$key]);
491         }
492         // Back-track
493         $tmp = array();
494         foreach($array as $value) {
495                 if ($value == '..') {
496                         array_pop($tmp);
497                 } else {
498                         array_push($tmp, $value);
499                 }
500         }
501         $array = & $tmp;
502
503         $path = $addroot ? $divider : '';
504         if (! empty($array)) $path .= implode($divider, $array) . $last;
505
506         return $path;
507 }
508
509 // DirectoryIndex normalize (Destructive and rough)
510 function file_normalize($string = 'index.html.en')
511 {
512         static $array = array(
513                 'index'                 => TRUE,        // Some system can omit the suffix
514                 'index.htm'             => TRUE,
515                 'index.html'    => TRUE,
516                 'index.shtml'   => TRUE,
517                 'index.jsp'             => TRUE,
518                 'index.php'             => TRUE,
519                 'index.php3'    => TRUE,
520                 'index.php4'    => TRUE,
521                 //'index.pl'    => TRUE,
522                 //'index.py'    => TRUE,
523                 //'index.rb'    => TRUE,
524                 'index.cgi'             => TRUE,
525                 'default.htm'   => TRUE,
526                 'default.html'  => TRUE,
527                 'default.asp'   => TRUE,
528                 'default.aspx'  => TRUE,
529         );
530
531         // Content-negothiation filter:
532         // Roughly removing ISO 639 -like
533         // 2-letter suffixes (See RFC3066)
534         $matches = array();
535         if (preg_match('/(.*)\.[a-z][a-z](?:-[a-z][a-z])?$/i', $string, $matches)) {
536                 $_string = $matches[1];
537         } else {
538                 $_string = & $string;
539         }
540
541         if (isset($array[strtolower($_string)])) {
542                 return '';
543         } else {
544                 return $string;
545         }
546 }
547
548 // Sort query-strings if possible (Destructive and rough)
549 // [OK] &&&&f=d&b&d&c&a=0dd  =>  a=0dd&b&c&d&f=d
550 // [OK] nothing==&eg=dummy&eg=padding&eg=foobar  =>  eg=foobar
551 function query_normalize($string = '', $equal = FALSE, $equal_cutempty = TRUE)
552 {
553         $array = explode('&', $string);
554
555         // Remove '&' paddings
556         foreach(array_keys($array) as $key) {
557                 if ($array[$key] == '') {
558                          unset($array[$key]);
559                 }
560         }
561
562         // Consider '='-sepalated input and paddings
563         if ($equal) {
564                 $equals = $not_equals = array();
565                 foreach ($array as $part) {
566                         if (strpos($part, '=') === FALSE) {
567                                  $not_equals[] = $part;
568                         } else {
569                                 list($key, $value) = explode('=', $part, 2);
570                                 $value = ltrim($value, '=');
571                                 if (! $equal_cutempty || $value != '') {
572                                         $equals[$key] = $value;
573                                 }
574                         }
575                 }
576
577                 $array = & $not_equals;
578                 foreach ($equals as $key => $value) {
579                         $array[] = $key . '=' . $value;
580                 }
581                 unset($equals);
582         }
583
584         natsort($array);
585         return implode('&', $array);
586 }
587
588 // ---------------------
589 // Part One : Checker
590
591 function generate_glob_regex($string = '', $divider = '/')
592 {
593         static $from = array(
594                          1 => '*',
595                         11 => '?',
596         //              22 => '[',      // Maybe cause regex compilation error (e.g. '[]')
597         //              23 => ']',      //
598                 );
599         static $mid = array(
600                          1 => '_AST_',
601                         11 => '_QUE_',
602         //              22 => '_RBR_',
603         //              23 => '_LBR_',
604                 );
605         static $to = array(
606                          1 => '.*',
607                         11 => '.',
608         //              22 => '[',
609         //              23 => ']',
610                 );
611
612         if (is_array($string)) {
613                 // Recurse
614                 return '(?:' .
615                         implode('|',    // OR
616                                 array_map('generate_glob_regex',
617                                         $string,
618                                         array_pad(array(), count($string), $divider)
619                                 )
620                         ) .
621                 ')';
622         } else {
623                 $string = str_replace($from, $mid, $string); // Hide
624                 $string = preg_quote($string, $divider);
625                 $string = str_replace($mid, $to, $string);   // Unhide
626                 return $string;
627         }
628 }
629
630 // TODO: Ignore list
631 // TODO: preg_grep() ?
632 // TODO: Multi list
633 function is_badhost($hosts = '', $asap = TRUE)
634 {
635         static $regex;
636
637         if (! isset($regex)) {
638                 $regex = array();
639                 $regex['badhost'] = array();
640
641                 // Sample
642                 if (TRUE) {
643                         $blocklist['badhost'] = array(
644                                 //'*',                  // Deny all uri
645                                 //'10.20.*.*',  // 10.20.example.com also matches
646                                 //'*.blogspot.com',     // Blog services subdomains
647                                 //array('blogspot.com', '*.blogspot.com')
648
649                                 // Viral/Buzz marketers' site, trying to make people
650                                 // as commercial Wiki spammers
651                                 // http://pukiwiki.sourceforge.jp/image/2006-12-16_wikiviral_pressblog.gif
652                                 array('pressblog.jp', '*.pressblog.jp'),
653                         );
654                         foreach ($blocklist['badhost'] as $part) {
655                                 $_part = is_array($part) ? implode('/', $part) : $part;
656                                 $regex['badhost'][$_part] = '/^' . generate_glob_regex($part) . '$/i';
657                         }
658                 }
659
660                 // Load
661                 if (file_exists(SPAM_INI_FILE)) {
662                         $blocklist = array();
663                         require(SPAM_INI_FILE);
664                         foreach ($blocklist['badhost'] as $part) {
665                                 $_part = is_array($part) ? implode('/', $part) : $part;
666                                 $regex['badhost'][$_part] = '/^' . generate_glob_regex($part) . '$/i';
667                         }
668                 }
669         }
670
671         $result = array();
672         if (! is_array($hosts)) $hosts = array($hosts);
673
674         foreach($hosts as $host) {
675                 if (! is_string($host)) $host = '';
676                 foreach ($regex['badhost'] as $part => $_regex) {
677                         if (preg_match($_regex, $host)) {
678                                 if (! isset($result[$part]))  $result[$part] = array();
679                                 $result[$part][] = $host;
680                                 if ($asap) {
681                                         return $result;
682                                 } else {
683                                         break;
684                                 }
685                         }
686                 }
687         }
688
689         return $result;
690 }
691
692 // Default (enabled) methods and thresholds
693 function check_uri_spam_method($times = 1, $t_area = 0, $rule = TRUE)
694 {
695         $times  = intval($times);
696         $t_area = intval($t_area);
697
698         $positive = array(
699                 // Thresholds
700                 'quantity'    => 8 * $times,    // Allow N URIs
701                 'non_uniq'    => 3 * $times,    // Allow N duped (and normalized) URIs
702
703                 // Areas
704                 'area_anchor' => $t_area,       // Using <a href> HTML tag
705                 'area_bbcode' => $t_area,       // Using [url] or [link] BBCode
706                 //'uri_anchor'  => $t_area,     // URI inside <a href> HTML tag
707                 //'uri_bbcode'  => $t_area,     // URI inside [url] or [link] BBCode
708         );
709         if ($rule) {
710                 $bool = array(
711                         // Rules
712                         //'asap'      => TRUE,  // Quit or return As Soon As Possible
713                         'uniqhost'    => TRUE,  // Show uniq host (at block notification mail)
714                         'badhost'     => TRUE,  // Check badhost
715                 );
716         } else {
717                 $bool = array();
718         }
719
720         // Remove non-$positive values
721         foreach (array_keys($positive) as $key) {
722                 if ($positive[$key] < 0) unset($positive[$key]);
723         }
724
725         return $positive + $bool;
726 }
727
728 // Simple/fast spam check
729 function check_uri_spam($target = '', $method = array())
730 {
731         if (! is_array($method) || empty($method)) {
732                 $method = check_uri_spam_method();
733         }
734         $progress = array(
735                 'sum' => array(
736                         'quantity'    => 0,
737                         'uniqhost'    => 0,
738                         'non_uniq'    => 0,
739                         'badhost'     => 0,
740                         'area_anchor' => 0,
741                         'area_bbcode' => 0,
742                         'uri_anchor'  => 0,
743                         'uri_bbcode'  => 0,
744                 ),
745                 'is_spam' => array(),
746                 'method'  => & $method,
747         );
748         $sum     = & $progress['sum'];
749         $is_spam = & $progress['is_spam'];
750         $asap    = isset($method['asap']);
751
752         // Return if ...
753         if (is_array($target)) {
754                 foreach($target as $str) {
755                         // Recurse
756                         $_progress = check_uri_spam($str, $method);
757                         foreach (array_keys($_progress['sum']) as $key) {
758                                 $sum[$key] += $_progress['sum'][$key];
759                         }
760                         foreach(array_keys($_progress['is_spam']) as $key) {
761                                 if (is_array($_progress['is_spam'][$key])) {
762                                         // Marge keys
763                                         foreach(array_keys($_progress['is_spam'][$key]) as $_key) {
764                                                 $is_spam[$key][$_key] = TRUE;
765                                         }
766                                 } else {
767                                         $is_spam[$key] = TRUE;
768                                 }
769                         }
770                         if ($asap && $is_spam) break;
771                 }
772                 return $progress;
773         }
774
775         // Area: There's HTML anchor tag
776         if ((! $asap || ! $is_spam) && isset($method['area_anchor'])) {
777                 $key = 'area_anchor';
778                 $_asap = isset($method['asap']) ? array('asap' => TRUE) : array();
779                 $result = area_pickup($target, array($key => TRUE) + $_asap);
780                 if ($result) {
781                         $sum[$key] = $result[$key];
782                         if (isset($method[$key]) && $sum[$key] > $method[$key]) {
783                                 $is_spam[$key] = TRUE;
784                         }
785                 }
786         }
787
788         // Area: There's 'BBCode' linking tag
789         if ((! $asap || ! $is_spam) && isset($method['area_bbcode'])) {
790                 $key = 'area_bbcode';
791                 $_asap = isset($method['asap']) ? array('asap' => TRUE) : array();
792                 $result = area_pickup($target, array($key => TRUE) + $_asap);
793                 if ($result) {
794                         $sum[$key] = $result[$key];
795                         if (isset($method[$key]) && $sum[$key] > $method[$key]) {
796                                 $is_spam[$key] = TRUE;
797                         }
798                 }
799         }
800
801         // Return if ...
802         if ($asap && $is_spam) {
803                 return $progress;
804         }
805         // URI Init
806         $pickups = spam_uri_pickup($target, $method);
807         if (empty($pickups)) {
808                 return $progress;
809         }
810
811         // URI: Check quantity
812         $sum['quantity'] += count($pickups);
813                 // URI quantity
814         if ((! $asap || ! $is_spam) && isset($method['quantity']) &&
815                 $sum['quantity'] > $method['quantity']) {
816                 $is_spam['quantity'] = TRUE;
817         }
818
819         // URI: used inside HTML anchor tag pair
820         if ((! $asap || ! $is_spam) && isset($method['uri_anchor'])) {
821                 $key = 'uri_anchor';
822                 foreach($pickups as $pickup) {
823                         if (isset($pickup['area'][$key])) {
824                                 $sum[$key] += $pickup['area'][$key];
825                                 if(isset($method[$key]) &&
826                                         $sum[$key] > $method[$key]) {
827                                         $is_spam[$key] = TRUE;
828                                         if ($asap && $is_spam) break;
829                                 }
830                                 if ($asap && $is_spam) break;
831                         }
832                 }
833         }
834
835         // URI: used inside 'BBCode' pair
836         if ((! $asap || ! $is_spam) && isset($method['uri_bbcode'])) {
837                 $key = 'uri_bbcode';
838                 foreach($pickups as $pickup) {
839                         if (isset($pickup['area'][$key])) {
840                                 $sum[$key] += $pickup['area'][$key];
841                                 if(isset($method[$key]) &&
842                                         $sum[$key] > $method[$key]) {
843                                         $is_spam[$key] = TRUE;
844                                         if ($asap && $is_spam) break;
845                                 }
846                                 if ($asap && $is_spam) break;
847                         }
848                 }
849         }
850
851         // URI: Uniqueness (and removing non-uniques)
852         if ((! $asap || ! $is_spam) && isset($method['non_uniq'])) {
853
854                 // Destructive normalize of URIs
855                 uri_array_normalize($pickups);
856
857                 $uris = array();
858                 foreach (array_keys($pickups) as $key) {
859                         $uris[$key] = uri_array_implode($pickups[$key]);
860                 }
861                 $count = count($uris);
862                 $uris  = array_unique($uris);
863                 $sum['non_uniq'] += $count - count($uris);
864                 if ($sum['non_uniq'] > $method['non_uniq']) {
865                         $is_spam['non_uniq'] = TRUE;
866                 }
867                 if (! $asap || ! $is_spam) {
868                         foreach (array_diff(array_keys($pickups),
869                                 array_keys($uris)) as $remove) {
870                                 unset($pickups[$remove]);
871                         }
872                 }
873                 unset($uris);
874         }
875
876         // Return if ...
877         if ($asap && $is_spam) {
878                 return $progress;
879         }
880
881         // URI: Unique host
882         $hosts = array();
883         foreach ($pickups as $pickup) $hosts[] = & $pickup['host'];
884         $hosts = array_unique($hosts);
885         $sum['uniqhost'] += count($hosts);
886
887         // URI: Bad host
888         if ((! $asap || ! $is_spam) && isset($method['badhost'])) {
889                 $badhost = is_badhost($hosts, $asap);
890                 if (! empty($badhost)) {
891                         $sum['badhost'] += array_count_leaves($badhost);
892                         foreach(array_keys($badhost) as $keys) {
893                                 $is_spam['badhost'][$keys] = TRUE;
894                         }
895                         unset($badhost);
896                 }
897         }
898
899         return $progress;
900 }
901
902 // Count leaves
903 function array_count_leaves($array = array(), $count_empty_array = FALSE)
904 {
905         if (! is_array($array) || (empty($array) && $count_empty_array))
906                 return 1;
907
908         // Recurse
909         $result = 0;
910         foreach ($array as $part) {
911                 $result += array_count_leaves($part, $count_empty_array);
912         }
913         return $result;
914 }
915
916 // ---------------------
917 // Reporting
918
919 // TODO: Don't show unused $method!
920 // Summarize $progress (blocked only)
921 function summarize_spam_progress($progress = array(), $blockedonly = FALSE)
922 {
923         if ($blockedonly) {
924                 $tmp = array_keys($progress['is_spam']);
925         } else {
926                 $tmp = array();
927                 $method = & $progress['method'];
928                 if (isset($progress['sum'])) {
929                         foreach ($progress['sum'] as $key => $value) {
930                                 if (isset($method[$key])) {
931                                         $tmp[] = $key . '(' . $value . ')';
932                                 }
933                         }
934                 }
935         }
936
937         return implode(', ', $tmp);
938 }
939
940 // ---------------------
941 // Exit
942
943 // Common bahavior for blocking
944 // NOTE: Call this function from various blocking feature, to disgueise the reason 'why blocked'
945 function spam_exit($mode = '', $data = array())
946 {
947         switch ($mode) {
948                 case '':        echo("\n");     break;
949                 case 'dump':
950                         echo('<pre>' . "\n");
951                         echo htmlspecialchars(var_export($data, TRUE));
952                         echo('</pre>' . "\n");
953                         break;
954         };
955
956         // Force exit
957         exit;
958 }
959
960
961 // ---------------------
962 // Simple filtering
963
964 // TODO: Record them
965 // Simple/fast spam filter ($target: 'a string' or an array())
966 function pkwk_spamfilter($action, $page, $target = array('title' => ''), $method = array(), $exitmode = '')
967 {
968         $progress = check_uri_spam($target, $method);
969
970         if (! empty($progress['is_spam'])) {
971                 // Mail to administrator(s)
972                 pkwk_spamnotify($action, $page, $target, $progress, $method);
973
974                 // Exit
975                 spam_exit($exitmode, $progress);
976         }
977 }
978
979 // ---------------------
980 // PukiWiki original
981
982 // Mail to administrator(s)
983 function pkwk_spamnotify($action, $page, $target = array('title' => ''), $progress = array(), $method = array())
984 {
985         global $notify, $notify_subject;
986
987         if (! $notify) return;
988
989         $asap = isset($method['asap']);
990
991         $summary['ACTION']  = 'Blocked by: ' . summarize_spam_progress($progress, TRUE);
992         if (! $asap) {
993                 $summary['METRICS'] = summarize_spam_progress($progress);
994         }
995         if (isset($progress['is_spam']['badhost'])) {
996                 $summary['BADHOST'] =
997                         implode(', ', array_keys($progress['is_spam']['badhost']));
998         }
999         $summary['COMMENT'] = $action;
1000         $summary['PAGE']    = '[blocked] ' . (is_pagename($page) ? $page : '');
1001         $summary['URI']     = get_script_uri() . '?' . rawurlencode($page);
1002         $summary['USER_AGENT']  = TRUE;
1003         $summary['REMOTE_ADDR'] = TRUE;
1004         pkwk_mail_notify($notify_subject,  var_export($target, TRUE), $summary);
1005 }
1006
1007 ?>