OSDN Git Service

(Default) Allow 3 duped host
[pukiwiki/pukiwiki_sandbox.git] / spam.php
1 <?php
2 // $Id: spam.php,v 1.88 2007/01/02 07:19:50 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 (for content insertion)
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_uniqhost' =>  3 * $times,  // Allow N duped (and normalized) Hosts
702                 'non_uniquri'  =>  0 * $times,  // Allow N duped (and normalized) URIs
703
704                 // Areas
705                 'area_anchor'  => $t_area,      // Using <a href> HTML tag
706                 'area_bbcode'  => $t_area,      // Using [url] or [link] BBCode
707                 //'uri_anchor' => $t_area,      // URI inside <a href> HTML tag
708                 //'uri_bbcode' => $t_area,      // URI inside [url] or [link] BBCode
709         );
710         if ($rule) {
711                 $bool = array(
712                         // Rules
713                         //'asap'   => TRUE,     // Quit or return As Soon As Possible
714                         'uniqhost' => TRUE,     // Show uniq host (at block notification mail)
715                         'badhost'  => TRUE,     // Check badhost
716                 );
717         } else {
718                 $bool = array();
719         }
720
721         // Remove non-$positive values
722         foreach (array_keys($positive) as $key) {
723                 if ($positive[$key] < 0) unset($positive[$key]);
724         }
725
726         return $positive + $bool;
727 }
728
729 // Simple/fast spam check
730 function check_uri_spam($target = '', $method = array())
731 {
732         if (! is_array($method) || empty($method)) {
733                 $method = check_uri_spam_method();
734         }
735         $progress = array(
736                 'sum' => array(
737                         'quantity'    => 0,
738                         'uniqhost'    => 0,
739                         'non_uniqhost'=> 0,
740                         'non_uniquri' => 0,
741                         'badhost'     => 0,
742                         'area_anchor' => 0,
743                         'area_bbcode' => 0,
744                         'uri_anchor'  => 0,
745                         'uri_bbcode'  => 0,
746                 ),
747                 'is_spam' => array(),
748                 'method'  => & $method,
749         );
750         $sum     = & $progress['sum'];
751         $is_spam = & $progress['is_spam'];
752         $asap    = isset($method['asap']);
753
754         // Return if ...
755         if (is_array($target)) {
756                 foreach($target as $str) {
757                         // Recurse
758                         $_progress = check_uri_spam($str, $method);
759                         $_sum      = & $_progress['sum'];
760                         $_is_spam  = & $_progress['is_spam'];
761                         foreach (array_keys($_sum) as $key) {
762                                 $sum[$key] += $_sum[$key];
763                         }
764                         foreach(array_keys($_is_spam) as $key) {
765                                 if (is_array($_is_spam[$key])) {
766                                         // Marge keys (badhost)
767                                         foreach(array_keys($_is_spam[$key]) as $_key) {
768                                                 if (! isset($is_spam[$key][$_key])) {
769                                                         $is_spam[$key][$_key] =  $_is_spam[$key][$_key];
770                                                 } else {
771                                                         $is_spam[$key][$_key] += $_is_spam[$key][$_key];
772                                                 }
773                                         }
774                                 } else {
775                                         $is_spam[$key] = TRUE;
776                                 }
777                         }
778                         if ($asap && $is_spam) break;
779                 }
780                 return $progress;
781         }
782
783         // Area: There's HTML anchor tag
784         if ((! $asap || ! $is_spam) && isset($method['area_anchor'])) {
785                 $key = 'area_anchor';
786                 $_asap = isset($method['asap']) ? array('asap' => TRUE) : array();
787                 $result = area_pickup($target, array($key => TRUE) + $_asap);
788                 if ($result) {
789                         $sum[$key] = $result[$key];
790                         if (isset($method[$key]) && $sum[$key] > $method[$key]) {
791                                 $is_spam[$key] = TRUE;
792                         }
793                 }
794         }
795
796         // Area: There's 'BBCode' linking tag
797         if ((! $asap || ! $is_spam) && isset($method['area_bbcode'])) {
798                 $key = 'area_bbcode';
799                 $_asap = isset($method['asap']) ? array('asap' => TRUE) : array();
800                 $result = area_pickup($target, array($key => TRUE) + $_asap);
801                 if ($result) {
802                         $sum[$key] = $result[$key];
803                         if (isset($method[$key]) && $sum[$key] > $method[$key]) {
804                                 $is_spam[$key] = TRUE;
805                         }
806                 }
807         }
808
809         // Return if ...
810         if ($asap && $is_spam) {
811                 return $progress;
812         }
813         // URI Init
814         $pickups = spam_uri_pickup($target, $method);
815         if (empty($pickups)) {
816                 return $progress;
817         }
818
819         // URI: Check quantity
820         $sum['quantity'] += count($pickups);
821                 // URI quantity
822         if ((! $asap || ! $is_spam) && isset($method['quantity']) &&
823                 $sum['quantity'] > $method['quantity']) {
824                 $is_spam['quantity'] = TRUE;
825         }
826
827         // URI: used inside HTML anchor tag pair
828         if ((! $asap || ! $is_spam) && isset($method['uri_anchor'])) {
829                 $key = 'uri_anchor';
830                 foreach($pickups as $pickup) {
831                         if (isset($pickup['area'][$key])) {
832                                 $sum[$key] += $pickup['area'][$key];
833                                 if(isset($method[$key]) &&
834                                         $sum[$key] > $method[$key]) {
835                                         $is_spam[$key] = TRUE;
836                                         if ($asap && $is_spam) break;
837                                 }
838                                 if ($asap && $is_spam) break;
839                         }
840                 }
841         }
842
843         // URI: used inside 'BBCode' pair
844         if ((! $asap || ! $is_spam) && isset($method['uri_bbcode'])) {
845                 $key = 'uri_bbcode';
846                 foreach($pickups as $pickup) {
847                         if (isset($pickup['area'][$key])) {
848                                 $sum[$key] += $pickup['area'][$key];
849                                 if(isset($method[$key]) &&
850                                         $sum[$key] > $method[$key]) {
851                                         $is_spam[$key] = TRUE;
852                                         if ($asap && $is_spam) break;
853                                 }
854                                 if ($asap && $is_spam) break;
855                         }
856                 }
857         }
858
859         // URI: Uniqueness (and removing non-uniques)
860         if ((! $asap || ! $is_spam) && isset($method['non_uniquri'])) {
861
862                 // Destructive normalize of URIs
863                 uri_array_normalize($pickups);
864
865                 $uris = array();
866                 foreach (array_keys($pickups) as $key) {
867                         $uris[$key] = uri_array_implode($pickups[$key]);
868                 }
869                 $count = count($uris);
870                 $uris  = array_unique($uris);
871                 $sum['non_uniquri'] += $count - count($uris);
872                 if ($sum['non_uniquri'] > $method['non_uniquri']) {
873                         $is_spam['non_uniquri'] = TRUE;
874                 }
875                 if (! $asap || ! $is_spam) {
876                         foreach (array_diff(array_keys($pickups),
877                                 array_keys($uris)) as $remove) {
878                                 unset($pickups[$remove]);
879                         }
880                 }
881                 unset($uris);
882         }
883
884         // Return if ...
885         if ($asap && $is_spam) {
886                 return $progress;
887         }
888
889         // Host: Uniqueness (uniq / non-uniq)
890         $hosts = array();
891         foreach ($pickups as $pickup) $hosts[] = & $pickup['host'];
892         $hosts = array_unique($hosts);
893         $sum['uniqhost'] += count($hosts);
894         if ((! $asap || ! $is_spam) && isset($method['non_uniqhost'])) {
895                 $sum['non_uniqhost'] = $sum['quantity'] - $sum['uniqhost'];
896                 if ($sum['non_uniqhost'] > $method['non_uniqhost']) {
897                         $is_spam['non_uniqhost'] = TRUE;
898                 }
899         }
900
901         // Return if ...
902         if ($asap && $is_spam) {
903                 return $progress;
904         }
905
906         // URI: Bad host
907         if ((! $asap || ! $is_spam) && isset($method['badhost'])) {
908                 $badhost = is_badhost($hosts, $asap);
909                 if (! empty($badhost)) {
910                         $sum['badhost'] += array_count_leaves($badhost);
911                         foreach(array_keys($badhost) as $keys) {
912                                 $is_spam['badhost'][$keys] =
913                                         array_count_leaves($badhost[$keys]);
914                         }
915                         unset($badhost);
916                 }
917         }
918
919         return $progress;
920 }
921
922 // Count leaves
923 function array_count_leaves($array = array(), $count_empty_array = FALSE)
924 {
925         if (! is_array($array) || (empty($array) && $count_empty_array))
926                 return 1;
927
928         // Recurse
929         $result = 0;
930         foreach ($array as $part) {
931                 $result += array_count_leaves($part, $count_empty_array);
932         }
933         return $result;
934 }
935
936 // ---------------------
937 // Reporting
938
939 // TODO: Don't show unused $method!
940 // Summarize $progress (blocked only)
941 function summarize_spam_progress($progress = array(), $blockedonly = FALSE)
942 {
943         if ($blockedonly) {
944                 $tmp = array_keys($progress['is_spam']);
945         } else {
946                 $tmp = array();
947                 $method = & $progress['method'];
948                 if (isset($progress['sum'])) {
949                         foreach ($progress['sum'] as $key => $value) {
950                                 if (isset($method[$key])) {
951                                         $tmp[] = $key . '(' . $value . ')';
952                                 }
953                         }
954                 }
955         }
956
957         return implode(', ', $tmp);
958 }
959
960 // ---------------------
961 // Exit
962
963 // Common bahavior for blocking
964 // NOTE: Call this function from various blocking feature, to disgueise the reason 'why blocked'
965 function spam_exit($mode = '', $data = array())
966 {
967         switch ($mode) {
968                 case '':        echo("\n");     break;
969                 case 'dump':
970                         echo('<pre>' . "\n");
971                         echo htmlspecialchars(var_export($data, TRUE));
972                         echo('</pre>' . "\n");
973                         break;
974         };
975
976         // Force exit
977         exit;
978 }
979
980
981 // ---------------------
982 // Simple filtering
983
984 // TODO: Record them
985 // Simple/fast spam filter ($target: 'a string' or an array())
986 function pkwk_spamfilter($action, $page, $target = array('title' => ''), $method = array(), $exitmode = '')
987 {
988         $progress = check_uri_spam($target, $method);
989
990         if (! empty($progress['is_spam'])) {
991                 // Mail to administrator(s)
992                 pkwk_spamnotify($action, $page, $target, $progress, $method);
993
994                 // Exit
995                 spam_exit($exitmode, $progress);
996         }
997 }
998
999 // ---------------------
1000 // PukiWiki original
1001
1002 // Mail to administrator(s)
1003 function pkwk_spamnotify($action, $page, $target = array('title' => ''), $progress = array(), $method = array())
1004 {
1005         global $notify, $notify_subject;
1006
1007         if (! $notify) return;
1008
1009         $asap = isset($method['asap']);
1010
1011         $summary['ACTION']  = 'Blocked by: ' . summarize_spam_progress($progress, TRUE);
1012         if (! $asap) {
1013                 $summary['METRICS'] = summarize_spam_progress($progress);
1014         }
1015         if (isset($progress['is_spam']['badhost'])) {
1016                 $badhost = array();
1017                 foreach($progress['is_spam']['badhost'] as $glob=>$number) {
1018                         $badhost[] = $glob . '(' . $number . ')';
1019                 }
1020                 $summary['BADHOST'] = implode(', ', $badhost);
1021         }
1022         $summary['COMMENT'] = $action;
1023         $summary['PAGE']    = '[blocked] ' . (is_pagename($page) ? $page : '');
1024         $summary['URI']     = get_script_uri() . '?' . rawurlencode($page);
1025         $summary['USER_AGENT']  = TRUE;
1026         $summary['REMOTE_ADDR'] = TRUE;
1027         pkwk_mail_notify($notify_subject,  var_export($target, TRUE), $summary);
1028 }
1029
1030 ?>