OSDN Git Service

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