OSDN Git Service

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