OSDN Git Service

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