OSDN Git Service

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