OSDN Git Service

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