OSDN Git Service

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