OSDN Git Service

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