OSDN Git Service

file_normalize(): Clarify the regex
[pukiwiki/pukiwiki_sandbox.git] / spam / spam.php
1 <?php
2 // $Id: spam.php,v 1.126 2007/03/17 06:31:24 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']  = host_normalize($_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 // Hostname normlization
465 // www.foo     => www.foo   ('foo' seems TLD)
466 // www.foo.bar => foo.bar
467 // www.10.20   => www.10.20 (Invalid hostname)
468 // NOTE:
469 //   'www' is  mostly used as traditional hostname of WWW server.
470 //   'www.foo.bar' may be identical with 'foo.bar'.
471 function host_normalize($host = '')
472 {
473         $host = strtolower($host);
474
475         $matches = array();
476         if (preg_match('/^www\.(.+\.[a-z]+)$/', $host, $matches)) {
477                 return $matches[1];
478         } else {
479                 return $host;
480         }
481 }
482
483 // Port normalization: Suppress the (redundant) default port
484 // HTTP://example.org:80/ => http://example.org/
485 // HTTP://example.org:8080/ => http://example.org:8080/
486 // HTTPS://example.org:443/ => https://example.org/
487 function port_normalize($port, $scheme, $scheme_normalize = TRUE)
488 {
489         // Schemes that users _maybe_ want to add protocol-handlers
490         // to their web browsers. (and attackers _maybe_ want to use ...)
491         // Reference: http://www.iana.org/assignments/port-numbers
492         static $array = array(
493                 // scheme => default port
494                 'ftp'     =>    21,
495                 'ssh'     =>    22,
496                 'telnet'  =>    23,
497                 'smtp'    =>    25,
498                 'tftp'    =>    69,
499                 'gopher'  =>    70,
500                 'finger'  =>    79,
501                 'http'    =>    80,
502                 'pop3'    =>   110,
503                 'sftp'    =>   115,
504                 'nntp'    =>   119,
505                 'imap'    =>   143,
506                 'irc'     =>   194,
507                 'wais'    =>   210,
508                 'https'   =>   443,
509                 'nntps'   =>   563,
510                 'rsync'   =>   873,
511                 'ftps'    =>   990,
512                 'telnets' =>   992,
513                 'imaps'   =>   993,
514                 'ircs'    =>   994,
515                 'pop3s'   =>   995,
516                 'mysql'   =>  3306,
517         );
518
519         $port = trim($port);
520         if ($port === '') return $port;
521
522         if ($scheme_normalize) $scheme = scheme_normalize($scheme);
523         if (isset($array[$scheme]) && $port == $array[$scheme])
524                 $port = ''; // Ignore the defaults
525
526         return $port;
527 }
528
529 // Path normalization
530 // http://example.org => http://example.org/
531 // http://example.org#hoge => http://example.org/#hoge
532 // http://example.org/path/a/b/./c////./d => http://example.org/path/a/b/c/d
533 // http://example.org/path/../../a/../back => http://example.org/back
534 function path_normalize($path = '', $divider = '/', $addroot = TRUE)
535 {
536         if (! is_string($path) || $path == '')
537                 return $addroot ? $divider : '';
538
539         $path = trim($path);
540         $last = ($path[strlen($path) - 1] == $divider) ? $divider : '';
541         $array = explode($divider, $path);
542
543         // Remove paddings
544         foreach(array_keys($array) as $key) {
545                 if ($array[$key] == '' || $array[$key] == '.')
546                          unset($array[$key]);
547         }
548         // Back-track
549         $tmp = array();
550         foreach($array as $value) {
551                 if ($value == '..') {
552                         array_pop($tmp);
553                 } else {
554                         array_push($tmp, $value);
555                 }
556         }
557         $array = & $tmp;
558
559         $path = $addroot ? $divider : '';
560         if (! empty($array)) $path .= implode($divider, $array) . $last;
561
562         return $path;
563 }
564
565 // DirectoryIndex normalize (Destructive and rough)
566 function file_normalize($string = 'index.html.en')
567 {
568         static $array = array(
569                 'index'                 => TRUE,        // Some system can omit the suffix
570                 'index.htm'             => TRUE,
571                 'index.html'    => TRUE,
572                 'index.shtml'   => TRUE,
573                 'index.jsp'             => TRUE,
574                 'index.php'             => TRUE,
575                 'index.php3'    => TRUE,
576                 'index.php4'    => TRUE,
577                 //'index.pl'    => TRUE,
578                 //'index.py'    => TRUE,
579                 //'index.rb'    => TRUE,
580                 'index.cgi'             => TRUE,
581                 'default.htm'   => TRUE,
582                 'default.html'  => TRUE,
583                 'default.asp'   => TRUE,
584                 'default.aspx'  => TRUE,
585         );
586
587         // Content-negothiation filter:
588         // Roughly removing ISO 639 -like
589         // 2-letter suffixes (See RFC3066)
590         $matches = array();
591         if (preg_match('/(.+)\.[a-z][a-z](?:-[a-z][a-z])?$/i', $string, $matches)) {
592                 $_string = $matches[1];
593         } else {
594                 $_string = & $string;
595         }
596
597         if (isset($array[strtolower($_string)])) {
598                 return '';
599         } else {
600                 return $string;
601         }
602 }
603
604 // Sort query-strings if possible (Destructive and rough)
605 // [OK] &&&&f=d&b&d&c&a=0dd  =>  a=0dd&b&c&d&f=d
606 // [OK] nothing==&eg=dummy&eg=padding&eg=foobar  =>  eg=foobar
607 function query_normalize($string = '', $equal = FALSE, $equal_cutempty = TRUE)
608 {
609         $array = explode('&', $string);
610
611         // Remove '&' paddings
612         foreach(array_keys($array) as $key) {
613                 if ($array[$key] == '') {
614                          unset($array[$key]);
615                 }
616         }
617
618         // Consider '='-sepalated input and paddings
619         if ($equal) {
620                 $equals = $not_equals = array();
621                 foreach ($array as $part) {
622                         if (strpos($part, '=') === FALSE) {
623                                  $not_equals[] = $part;
624                         } else {
625                                 list($key, $value) = explode('=', $part, 2);
626                                 $value = ltrim($value, '=');
627                                 if (! $equal_cutempty || $value != '') {
628                                         $equals[$key] = $value;
629                                 }
630                         }
631                 }
632
633                 $array = & $not_equals;
634                 foreach ($equals as $key => $value) {
635                         $array[] = $key . '=' . $value;
636                 }
637                 unset($equals);
638         }
639
640         natsort($array);
641         return implode('&', $array);
642 }
643
644 // ---------------------
645 // Part One : Checker
646
647 // Rough implementation of globbing
648 //
649 // USAGE: $regex = '/^' . generate_glob_regex('*.txt', '/') . '$/i';
650 //
651 function generate_glob_regex($string = '', $divider = '/')
652 {
653         static $from = array(
654                          1 => '*',
655                         11 => '?',
656         //              22 => '[',      // Maybe cause regex compilation error (e.g. '[]')
657         //              23 => ']',      //
658                 );
659         static $mid = array(
660                          1 => '_AST_',
661                         11 => '_QUE_',
662         //              22 => '_RBR_',
663         //              23 => '_LBR_',
664                 );
665         static $to = array(
666                          1 => '.*',
667                         11 => '.',
668         //              22 => '[',
669         //              23 => ']',
670                 );
671
672         $string = str_replace($from, $mid, $string); // Hide
673         $string = preg_quote($string, $divider);
674         $string = str_replace($mid, $to, $string);   // Unhide
675
676         return $string;
677 }
678
679 // Rough hostname checker
680 // [OK] 192.168.
681 // TODO: Strict digit, 0x, CIDR, IPv6
682 function is_ip($string = '')
683 {
684         if (preg_match('/^' .
685                 '(?:[0-9]{1,3}\.){3}[0-9]{1,3}' . '|' .
686                 '(?:[0-9]{1,3}\.){1,3}' . '$/',
687                 $string)) {
688                 return 4;       // Seems IPv4(dot-decimal)
689         } else {
690                 return 0;       // Seems not IP
691         }
692 }
693
694 // Generate host (FQDN, IPv4, ...) regex
695 // 'localhost'     : Matches with 'localhost' only
696 // 'example.org'   : Matches with 'example.org' only (See host_normalize() about 'www')
697 // '.example.org'  : Matches with ALL FQDN ended with '.example.org'
698 // '*.example.org' : Almost the same of '.example.org' except 'www.example.org'
699 // '10.20.30.40'   : Matches with IPv4 address '10.20.30.40' only
700 // [TODO] '192.'   : Matches with all IPv4 hosts started with '192.'
701 // TODO: IPv4, CIDR?, IPv6
702 function generate_host_regex($string = '', $divider = '/')
703 {
704         if (mb_strpos($string, '.') === FALSE)
705                 return generate_glob_regex($string, $divider);
706
707         $result = '';
708         if (is_ip($string)) {
709                 // IPv4
710                 return generate_glob_regex($string, $divider);
711         } else {
712                 // FQDN or something
713                 $part = explode('.', $string, 2);
714                 if ($part[0] == '') {
715                         $part[0] = '(?:.*\.)?'; // And all related FQDN
716                 } else if ($part[0] == '*') {
717                         $part[0] = '.*\.';      // All subdomains/hosts only
718                 } else {
719                         return generate_glob_regex($string, $divider);
720                 }
721                 $part[1] = generate_glob_regex($part[1], $divider);
722                 return implode('', $part);
723         }
724 }
725
726 function get_blocklist($list = '')
727 {
728         static $regexs;
729
730         if (! isset($regexs)) {
731                 $regexs = array();
732                 if (file_exists(SPAM_INI_FILE)) {
733                         $blocklist = array();
734                         include(SPAM_INI_FILE);
735                         //      $blocklist['badhost'] = array(
736                         //              '*.blogspot.com',       // Blog services's subdomains (only)
737                         //              'IANA-examples' => '#^(?:.*\.)?example\.(?:com|net|org)$#',
738                         //      );
739                         foreach(array('goodhost', 'badhost') as $_list) {
740                                 if (! isset($blocklist[$list])) continue;
741                                 foreach ($blocklist[$_list] as $key => $value) {
742                                         if (is_array($value)) {
743                                                 $regexs[$_list][$key] = array();
744                                                 foreach($value as $_key => $_value) {
745                                                         get_blocklist_add($regexs[$_list][$key], $_key, $_value);
746                                                 }
747                                         } else {
748                                                 get_blocklist_add($regexs[$_list], $key, $value);
749                                         }
750                                 }
751                         }
752                 }
753         }
754
755         if ($list == '') {
756                 return $regexs; // ALL
757         } else if (isset($regexs[$list])) {
758                 return $regexs[$list];
759         } else {        
760                 return array();
761         }
762 }
763
764 // Subroutine of get_blocklist()
765 function get_blocklist_add(& $array, $key = 0, $value = '*.example.org')
766 {
767         if (is_string($key)) {
768                 $array[$key] = & $value; // Treat $value as a regex
769         } else {
770                 $array[$value] = '/^' . generate_host_regex($value, '/') . '$/i';
771         }
772
773
774 function is_badhost($hosts = array(), $asap = TRUE, & $remains)
775 {
776         $result = array();
777         if (! is_array($hosts)) $hosts = array($hosts);
778         foreach(array_keys($hosts) as $key) {
779                 if (! is_string($hosts[$key])) unset($hosts[$key]);
780         }
781         if (empty($hosts)) return $result;
782
783         foreach (get_blocklist('goodhost') as $regex) {
784                 $hosts = preg_grep_invert($regex, $hosts);
785         }
786         if (empty($hosts)) return $result;
787
788         $tmp = array();
789         foreach (get_blocklist('badhost') as $label => $regex) {
790                 if (is_array($regex)) {
791                         $result[$label] = array();
792                         foreach($regex as $_label => $_regex) {
793                                 if (is_badhost_avail($_label, $_regex, $hosts, $result[$label]) && $asap) break;
794                         }
795                         if (empty($result[$label])) unset($result[$label]);
796                 } else {
797                         if (is_badhost_avail($label, $regex, $hosts, $result) && $asap) break;
798                 }
799         }
800
801         $remains = $hosts;
802
803         return $result;
804 }
805
806 // Subroutine for is_badhost()
807 function is_badhost_avail($label = '*.example.org', $regex = '/^.*\.example\.org$/', & $hosts, & $result)
808 {
809         $group = preg_grep($regex, $hosts);
810         if ($group) {
811                 $result[$label] = & $group;
812                 $hosts = array_diff($hosts, $result[$label]);
813                 return TRUE;
814         } else {
815                 return FALSE;
816         }
817 }
818
819 // Default (enabled) methods and thresholds (for content insertion)
820 function check_uri_spam_method($times = 1, $t_area = 0, $rule = TRUE)
821 {
822         $times  = intval($times);
823         $t_area = intval($t_area);
824
825         $positive = array(
826                 // Thresholds
827                 'quantity'     =>  8 * $times,  // Allow N URIs
828                 'non_uniqhost' =>  3 * $times,  // Allow N duped (and normalized) Hosts
829                 //'non_uniquri'=>  3 * $times,  // Allow N duped (and normalized) URIs
830
831                 // Areas
832                 'area_anchor'  => $t_area,      // Using <a href> HTML tag
833                 'area_bbcode'  => $t_area,      // Using [url] or [link] BBCode
834                 //'uri_anchor' => $t_area,      // URI inside <a href> HTML tag
835                 //'uri_bbcode' => $t_area,      // URI inside [url] or [link] BBCode
836         );
837         if ($rule) {
838                 $bool = array(
839                         // Rules
840                         //'asap'   => TRUE,     // Quit or return As Soon As Possible
841                         'uniqhost' => TRUE,     // Show uniq host (at block notification mail)
842                         'badhost'  => TRUE,     // Check badhost
843                 );
844         } else {
845                 $bool = array();
846         }
847
848         // Remove non-$positive values
849         foreach (array_keys($positive) as $key) {
850                 if ($positive[$key] < 0) unset($positive[$key]);
851         }
852
853         return $positive + $bool;
854 }
855
856 // Simple/fast spam check
857 function check_uri_spam($target = '', $method = array())
858 {
859         if (! is_array($method) || empty($method)) {
860                 $method = check_uri_spam_method();
861         }
862         $progress = array(
863                 'sum' => array(
864                         'quantity'    => 0,
865                         'uniqhost'    => 0,
866                         'non_uniqhost'=> 0,
867                         'non_uniquri' => 0,
868                         'badhost'     => 0,
869                         'area_anchor' => 0,
870                         'area_bbcode' => 0,
871                         'uri_anchor'  => 0,
872                         'uri_bbcode'  => 0,
873                 ),
874                 'is_spam' => array(),
875                 'method'  => & $method,
876                 'remains' => array(),
877                 'error'   => array(),
878         );
879         $sum     = & $progress['sum'];
880         $is_spam = & $progress['is_spam'];
881         $remains = & $progress['remains'];
882         $error   = & $progress['error'];
883         $asap    = isset($method['asap']);
884
885         // Recurse
886         if (is_array($target)) {
887                 foreach($target as $str) {
888                         // Recurse
889                         $_progress = check_uri_spam($str, $method);
890                         $_sum      = & $_progress['sum'];
891                         $_is_spam  = & $_progress['is_spam'];
892                         $_remains  = & $_progress['remains'];
893                         $_error    = & $_progress['error'];
894                         foreach (array_keys($_sum) as $key) {
895                                 $sum[$key] += $_sum[$key];
896                         }
897                         foreach (array_keys($_is_spam) as $key) {
898                                 if (is_array($_is_spam[$key])) {
899                                         // Marge keys (badhost)
900                                         foreach(array_keys($_is_spam[$key]) as $_key) {
901                                                 if (! isset($is_spam[$key][$_key])) {
902                                                         $is_spam[$key][$_key] =  $_is_spam[$key][$_key];
903                                                 } else {
904                                                         $is_spam[$key][$_key] += $_is_spam[$key][$_key];
905                                                 }
906                                         }
907                                 } else {
908                                         $is_spam[$key] = TRUE;
909                                 }
910                         }
911                         foreach ($_remains as $key=>$value) {
912                                 foreach ($value as $_key=>$_value) {
913                                         if (is_int($_key)) {
914                                                 $remains[$key][]      = $_value;
915                                         } else {
916                                                 $remains[$key][$_key] = $_value;
917                                         }
918                                 }
919                         }
920                         if (! empty($_error)) $error += $_error;
921                         if ($asap && $is_spam) break;
922                 }
923                 return $progress;
924         }
925
926         // Area: There's HTML anchor tag
927         if ((! $asap || ! $is_spam) && isset($method['area_anchor'])) {
928                 $key = 'area_anchor';
929                 $_asap = isset($method['asap']) ? array('asap' => TRUE) : array();
930                 $result = area_pickup($target, array($key => TRUE) + $_asap);
931                 if ($result) {
932                         $sum[$key] = $result[$key];
933                         if (isset($method[$key]) && $sum[$key] > $method[$key]) {
934                                 $is_spam[$key] = TRUE;
935                         }
936                 }
937         }
938
939         // Area: There's 'BBCode' linking tag
940         if ((! $asap || ! $is_spam) && isset($method['area_bbcode'])) {
941                 $key = 'area_bbcode';
942                 $_asap = isset($method['asap']) ? array('asap' => TRUE) : array();
943                 $result = area_pickup($target, array($key => TRUE) + $_asap);
944                 if ($result) {
945                         $sum[$key] = $result[$key];
946                         if (isset($method[$key]) && $sum[$key] > $method[$key]) {
947                                 $is_spam[$key] = TRUE;
948                         }
949                 }
950         }
951
952         // Return if ...
953         if ($asap && $is_spam) return $progress;
954
955         // URI: Pickup
956         $pickups = spam_uri_pickup($target, $method);
957         //$remains['uri_pickup'] = & $pickups;
958
959         // Return if ...
960         if (empty($pickups)) return $progress;
961
962         // URI: Check quantity
963         $sum['quantity'] += count($pickups);
964                 // URI quantity
965         if ((! $asap || ! $is_spam) && isset($method['quantity']) &&
966                 $sum['quantity'] > $method['quantity']) {
967                 $is_spam['quantity'] = TRUE;
968         }
969
970         // URI: used inside HTML anchor tag pair
971         if ((! $asap || ! $is_spam) && isset($method['uri_anchor'])) {
972                 $key = 'uri_anchor';
973                 foreach($pickups as $pickup) {
974                         if (isset($pickup['area'][$key])) {
975                                 $sum[$key] += $pickup['area'][$key];
976                                 if(isset($method[$key]) &&
977                                         $sum[$key] > $method[$key]) {
978                                         $is_spam[$key] = TRUE;
979                                         if ($asap && $is_spam) break;
980                                 }
981                                 if ($asap && $is_spam) break;
982                         }
983                 }
984         }
985
986         // URI: used inside 'BBCode' pair
987         if ((! $asap || ! $is_spam) && isset($method['uri_bbcode'])) {
988                 $key = 'uri_bbcode';
989                 foreach($pickups as $pickup) {
990                         if (isset($pickup['area'][$key])) {
991                                 $sum[$key] += $pickup['area'][$key];
992                                 if(isset($method[$key]) &&
993                                         $sum[$key] > $method[$key]) {
994                                         $is_spam[$key] = TRUE;
995                                         if ($asap && $is_spam) break;
996                                 }
997                                 if ($asap && $is_spam) break;
998                         }
999                 }
1000         }
1001
1002         // URI: Uniqueness (and removing non-uniques)
1003         if ((! $asap || ! $is_spam) && isset($method['non_uniquri'])) {
1004
1005                 // Destructive normalize of URIs
1006                 uri_array_normalize($pickups);
1007
1008                 $uris = array();
1009                 foreach (array_keys($pickups) as $key) {
1010                         $uris[$key] = uri_array_implode($pickups[$key]);
1011                 }
1012                 $count = count($uris);
1013                 $uris  = array_unique($uris);
1014                 $sum['non_uniquri'] += $count - count($uris);
1015                 if ($sum['non_uniquri'] > $method['non_uniquri']) {
1016                         $is_spam['non_uniquri'] = TRUE;
1017                 }
1018                 if (! $asap || ! $is_spam) {
1019                         foreach (array_diff(array_keys($pickups),
1020                                 array_keys($uris)) as $remove) {
1021                                 unset($pickups[$remove]);
1022                         }
1023                 }
1024                 unset($uris);
1025         }
1026
1027         // Return if ...
1028         if ($asap && $is_spam) return $progress;
1029
1030         // Host: Uniqueness (uniq / non-uniq)
1031         $hosts = array();
1032         foreach ($pickups as $pickup) $hosts[] = & $pickup['host'];
1033         $hosts = array_unique($hosts);
1034         //$remains['uniqhost'] = & $hosts;
1035         $sum['uniqhost'] += count($hosts);
1036         if ((! $asap || ! $is_spam) && isset($method['non_uniqhost'])) {
1037                 $sum['non_uniqhost'] = $sum['quantity'] - $sum['uniqhost'];
1038                 if ($sum['non_uniqhost'] > $method['non_uniqhost']) {
1039                         $is_spam['non_uniqhost'] = TRUE;
1040                 }
1041         }
1042
1043         // Return if ...
1044         if ($asap && $is_spam) return $progress;
1045
1046         // URI: Bad host
1047         if ((! $asap || ! $is_spam) && isset($method['badhost'])) {
1048                 $__remains = array();
1049                 $badhost = is_badhost($hosts, $asap, $__remains);
1050                 if (! $asap) {
1051                         if ($__remains) {
1052                                 $remains['badhost'] = array();
1053                                 foreach ($__remains as $value) {
1054                                         $remains['badhost'][$value] = TRUE;
1055                                 }
1056                         }
1057                 }
1058                 unset($__remains);
1059                 if (! empty($badhost)) {
1060                         //var_dump($badhost);   // BADHOST detail
1061                         $sum['badhost'] += array_count_leaves($badhost);
1062                         foreach(array_keys($badhost) as $keys) {
1063                                 $is_spam['badhost'][$keys] =
1064                                         array_count_leaves($badhost[$keys]);
1065                         }
1066                         unset($badhost);
1067                 }
1068         }
1069
1070         return $progress;
1071 }
1072
1073 // Count leaves
1074 function array_count_leaves($array = array(), $count_empty_array = FALSE)
1075 {
1076         if (! is_array($array) || (empty($array) && $count_empty_array))
1077                 return 1;
1078
1079         // Recurse
1080         $result = 0;
1081         foreach ($array as $part) {
1082                 $result += array_count_leaves($part, $count_empty_array);
1083         }
1084         return $result;
1085 }
1086
1087 // ---------------------
1088 // Reporting
1089
1090 // TODO: Don't show unused $method!
1091 // Summarize $progress (blocked only)
1092 function summarize_spam_progress($progress = array(), $blockedonly = FALSE)
1093 {
1094         if ($blockedonly) {
1095                 $tmp = array_keys($progress['is_spam']);
1096         } else {
1097                 $tmp = array();
1098                 $method = & $progress['method'];
1099                 if (isset($progress['sum'])) {
1100                         foreach ($progress['sum'] as $key => $value) {
1101                                 if (isset($method[$key])) {
1102                                         $tmp[] = $key . '(' . $value . ')';
1103                                 }
1104                         }
1105                 }
1106         }
1107
1108         return implode(', ', $tmp);
1109 }
1110
1111 // ---------------------
1112 // Exit
1113
1114 // Common bahavior for blocking
1115 // NOTE: Call this function from various blocking feature, to disgueise the reason 'why blocked'
1116 function spam_exit($mode = '', $data = array())
1117 {
1118         switch ($mode) {
1119                 case '':        echo("\n");     break;
1120                 case 'dump':
1121                         echo('<pre>' . "\n");
1122                         echo htmlspecialchars(var_export($data, TRUE));
1123                         echo('</pre>' . "\n");
1124                         break;
1125         };
1126
1127         // Force exit
1128         exit;
1129 }
1130
1131
1132 // ---------------------
1133 // Simple filtering
1134
1135 // TODO: Record them
1136 // Simple/fast spam filter ($target: 'a string' or an array())
1137 function pkwk_spamfilter($action, $page, $target = array('title' => ''), $method = array(), $exitmode = '')
1138 {
1139         $progress = check_uri_spam($target, $method);
1140
1141         if (! empty($progress['is_spam'])) {
1142                 // Mail to administrator(s)
1143                 pkwk_spamnotify($action, $page, $target, $progress, $method);
1144
1145                 // Exit
1146                 spam_exit($exitmode, $progress);
1147         }
1148 }
1149
1150 // ---------------------
1151 // PukiWiki original
1152
1153 // Mail to administrator(s)
1154 function pkwk_spamnotify($action, $page, $target = array('title' => ''), $progress = array(), $method = array())
1155 {
1156         global $notify, $notify_subject;
1157
1158         if (! $notify) return;
1159
1160         $asap = isset($method['asap']);
1161
1162         $summary['ACTION']  = 'Blocked by: ' . summarize_spam_progress($progress, TRUE);
1163         if (! $asap) {
1164                 $summary['METRICS'] = summarize_spam_progress($progress);
1165         }
1166         if (isset($progress['is_spam']['badhost'])) {
1167                 $badhost = array();
1168                 foreach($progress['is_spam']['badhost'] as $glob=>$number) {
1169                         $badhost[] = $glob . '(' . $number . ')';
1170                 }
1171                 $summary['DETAIL_BADHOST'] = implode(', ', $badhost);
1172         }
1173         if (! $asap && $progress['remains']['badhost']) {
1174                 $count = count($progress['remains']['badhost']);
1175                 $summary['DETAIL_NEUTRAL_HOST'] = $count .
1176                         ' (' .
1177                                 preg_replace(
1178                                         '/[^, a-z0-9.-]/i', '',
1179                                         implode(', ', array_keys($progress['remains']['badhost']))
1180                                 ) .
1181                         ')';
1182         }
1183         $summary['COMMENT'] = $action;
1184         $summary['PAGE']    = '[blocked] ' . (is_pagename($page) ? $page : '');
1185         $summary['URI']     = get_script_uri() . '?' . rawurlencode($page);
1186         $summary['USER_AGENT']  = TRUE;
1187         $summary['REMOTE_ADDR'] = TRUE;
1188         pkwk_mail_notify($notify_subject,  var_export($target, TRUE), $summary, TRUE);
1189 }
1190
1191 ?>