OSDN Git Service

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