OSDN Git Service

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