OSDN Git Service

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