OSDN Git Service

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