OSDN Git Service

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