OSDN Git Service

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