OSDN Git Service

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