2 // $Id: spam.php,v 1.127 2007/03/25 13:46:43 henoheno Exp $
3 // Copyright (C) 2006-2007 PukiWiki Developers Team
4 // License: GPL v2 or (at your option) any later version
6 // Functions for Concept-work of spam-uri metrics
8 // (PHP 4 >= 4.3.0): preg_match_all(PREG_OFFSET_CAPTURE): $method['uri_XXX'] related feature
10 if (! defined('SPAM_INI_FILE')) define('SPAM_INI_FILE', 'spam.ini.php');
12 // ---------------------
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";
22 // (PHP 4 >= 4.2.0): preg_grep() enables invert option
23 function preg_grep_invert($pattern = '//', $input = array())
26 if (! isset($invert)) $invert = defined('PREG_GREP_INVERT');
29 return preg_grep($pattern, $input, PREG_GREP_INVERT);
31 $result = preg_grep($pattern, $input);
33 return array_diff($input, preg_grep($pattern, $input));
40 // ---------------------
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 = '')
50 if (! is_string($string)) return array();
52 // Not available for: IDN(ignored)
55 // scheme://userinfo@host:port/path/or/pathinfo/maybefile.and?query=string#fragment
56 // Refer RFC3986 (Regex below is not strict)
57 '#(\b[a-z][a-z0-9.+-]{1,8}):/+' . // 1: Scheme
59 '([^\s<>"\'\[\]/\#?@]*)' . // 2: Userinfo (Username)
63 '\[[0-9a-f:.]+\]' . '|' . // IPv6([colon-hex and dot]): RFC2732
64 '(?:[0-9]{1,3}\.){3}[0-9]{1,3}' . '|' . // IPv4(dot-decimal): 001.22.3.44
65 '[a-z0-9.-]+' . // hostname(FQDN) : foo.example.org
67 '(?::([0-9]*))?' . // 4: Port
68 '((?:/+[^\s<>"\'\[\]/\#]+)*/+)?' . // 5: Directory path or path-info
69 '([^\s<>"\'\[\]\#?]+)?' . // 6: File?
70 '(?:\?([^\s<>"\'\[\]\#]+))?' . // 7: Query string
71 '(?:\#([a-z0-9._~%!$&\'()*+,;=:@-]*))?' . // 8: Fragment
73 $string, $array, PREG_SET_ORDER | PREG_OFFSET_CAPTURE
77 static $parts = array(
78 1 => 'scheme', 2 => 'userinfo', 3 => 'host', 4 => 'port',
79 5 => 'path', 6 => 'file', 7 => 'query', 8 => 'fragment'
82 foreach(array_keys($array) as $uri) {
83 $_uri = & $array[$uri];
84 array_rename_keys($_uri, $parts, TRUE, $default);
85 $offset = $_uri['scheme'][1]; // Scheme's offset = URI's offset
86 foreach(array_keys($_uri) as $part) {
87 $_uri[$part] = & $_uri[$part][0]; // Remove offsets
91 foreach(array_keys($array) as $uri) {
92 $_uri = & $array[$uri];
93 if ($_uri['scheme'] === '') {
94 unset($array[$uri]); // Considererd harmless
97 unset($_uri[0]); // Matched string itself
98 $_uri['area']['offset'] = $offset; // Area offset for area_measure()
104 // Normalize an array of URI arrays
105 // NOTE: Give me the uri_pickup() results
106 function uri_pickup_normalize(& $pickups, $destructive = TRUE)
108 if (! is_array($pickups)) return $pickups;
111 foreach (array_keys($pickups) as $key) {
112 $_key = & $pickups[$key];
113 $_key['scheme'] = isset($_key['scheme']) ? scheme_normalize($_key['scheme']) : '';
114 $_key['host'] = isset($_key['host']) ? host_normalize($_key['host']) : '';
115 $_key['port'] = isset($_key['port']) ? port_normalize($_key['port'], $_key['scheme'], FALSE) : '';
116 $_key['path'] = isset($_key['path']) ? strtolower(path_normalize($_key['path'])) : '';
117 $_key['file'] = isset($_key['file']) ? file_normalize($_key['file']) : '';
118 $_key['query'] = isset($_key['query']) ? query_normalize($_key['query']) : '';
119 $_key['fragment'] = isset($_key['fragment']) ? strtolower($_key['fragment']) : '';
122 foreach (array_keys($pickups) as $key) {
123 $_key = & $pickups[$key];
124 $_key['scheme'] = isset($_key['scheme']) ? scheme_normalize($_key['scheme']) : '';
125 $_key['host'] = isset($_key['host']) ? strtolower($_key['host']) : '';
126 $_key['port'] = isset($_key['port']) ? port_normalize($_key['port'], $_key['scheme'], FALSE) : '';
127 $_key['path'] = isset($_key['path']) ? path_normalize($_key['path']) : '';
135 // An URI array => An URI (See uri_pickup())
137 // $pickups = uri_pickup('a string include some URIs');
139 // foreach (array_keys($pickups) as $key) {
140 // $uris[$key] = uri_pickup_implode($pickups[$key]);
142 function uri_pickup_implode($uri = array())
144 if (empty($uri) || ! is_array($uri)) return NULL;
147 if (isset($uri['scheme']) && $uri['scheme'] !== '') {
148 $tmp[] = & $uri['scheme'];
151 if (isset($uri['userinfo']) && $uri['userinfo'] !== '') {
152 $tmp[] = & $uri['userinfo'];
155 if (isset($uri['host']) && $uri['host'] !== '') {
156 $tmp[] = & $uri['host'];
158 if (isset($uri['port']) && $uri['port'] !== '') {
160 $tmp[] = & $uri['port'];
162 if (isset($uri['path']) && $uri['path'] !== '') {
163 $tmp[] = & $uri['path'];
165 if (isset($uri['file']) && $uri['file'] !== '') {
166 $tmp[] = & $uri['file'];
168 if (isset($uri['query']) && $uri['query'] !== '') {
170 $tmp[] = & $uri['query'];
172 if (isset($uri['fragment']) && $uri['fragment'] !== '') {
174 $tmp[] = & $uri['fragment'];
177 return implode('', $tmp);
180 // $array['something'] => $array['wanted']
181 function array_rename_keys(& $array, $keys = array('from' => 'to'), $force = FALSE, $default = '')
183 if (! is_array($array) || ! is_array($keys)) return FALSE;
185 // Nondestructive test
187 foreach(array_keys($keys) as $from)
188 if (! isset($array[$from]))
191 foreach($keys as $from => $to) {
192 if ($from === $to) continue;
193 if (! $force || isset($array[$from])) {
194 $array[$to] = & $array[$from];
195 unset($array[$from]);
197 $array[$to] = $default;
204 // ---------------------
207 // Pickup all of markup areas
208 function area_pickup($string = '', $method = array())
211 if (empty($method)) return $area;
213 // Anchor tag pair by preg_match and preg_match_all()
215 // [OK] <a href= >Good site!</a>
216 // [OK] <a href= "#" >test</a>
217 // [OK] <a href="http://nasty.example.com">visit http://nasty.example.com/</a>
218 // [OK] <a href=\'http://nasty.example.com/\' >discount foobar</a>
219 // [NG] <a href="http://ng.example.com">visit http://ng.example.com _not_ended_
220 $regex = '#<a\b[^>]*\bhref\b[^>]*>.*?</a\b[^>]*(>)#i';
221 if (isset($method['area_anchor'])) {
223 $count = isset($method['asap']) ?
224 preg_match($regex, $string) :
225 preg_match_all($regex, $string, $areas);
226 if (! empty($count)) $area['area_anchor'] = $count;
228 if (isset($method['uri_anchor'])) {
230 preg_match_all($regex, $string, $areas, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
231 foreach(array_keys($areas) as $_area) {
232 $areas[$_area] = array(
233 $areas[$_area][0][1], // Area start (<a href>)
234 $areas[$_area][1][1], // Area end (</a>)
237 if (! empty($areas)) $area['uri_anchor'] = $areas;
240 // phpBB's "BBCode" pair by preg_match and preg_match_all()
242 // [OK] [url]http://nasty.example.com/[/url]
243 // [OK] [link]http://nasty.example.com/[/link]
244 // [OK] [url=http://nasty.example.com]visit http://nasty.example.com/[/url]
245 // [OK] [link http://nasty.example.com/]buy something[/link]
246 $regex = '#\[(url|link)\b[^\]]*\].*?\[/\1\b[^\]]*(\])#i';
247 if (isset($method['area_bbcode'])) {
249 $count = isset($method['asap']) ?
250 preg_match($regex, $string) :
251 preg_match_all($regex, $string, $areas, PREG_SET_ORDER);
252 if (! empty($count)) $area['area_bbcode'] = $count;
254 if (isset($method['uri_bbcode'])) {
256 preg_match_all($regex, $string, $areas, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
257 foreach(array_keys($areas) as $_area) {
258 $areas[$_area] = array(
259 $areas[$_area][0][1], // Area start ([url])
260 $areas[$_area][2][1], // Area end ([/url])
263 if (! empty($areas)) $area['uri_bbcode'] = $areas;
266 // Various Wiki syntax
267 // [text_or_uri>text_or_uri]
268 // [text_or_uri:text_or_uri]
269 // [text_or_uri|text_or_uri]
270 // [text_or_uri->text_or_uri]
271 // [text_or_uri text_or_uri] // MediaWiki
272 // MediaWiki: [http://nasty.example.com/ visit http://nasty.example.com/]
277 // If in doubt, it's a little doubtful
278 // if (Area => inside <= Area) $brief += -1
279 function area_measure($areas, & $array, $belief = -1, $a_key = 'area', $o_key = 'offset')
281 if (! is_array($areas) || ! is_array($array)) return;
283 $areas_keys = array_keys($areas);
284 foreach(array_keys($array) as $u_index) {
285 $offset = isset($array[$u_index][$o_key]) ?
286 intval($array[$u_index][$o_key]) : 0;
287 foreach($areas_keys as $a_index) {
288 if (isset($array[$u_index][$a_key])) {
289 $offset_s = intval($areas[$a_index][0]);
290 $offset_e = intval($areas[$a_index][1]);
291 // [Area => inside <= Area]
292 if ($offset_s < $offset && $offset < $offset_e) {
293 $array[$u_index][$a_key] += $belief;
300 // ---------------------
303 // Domain exposure callback (See spam_uri_pickup_preprocess())
304 // http://victim.example.org/?foo+site:nasty.example.com+bar
305 // => http://nasty.example.com/?refer=victim.example.org
306 // NOTE: 'refer=' is not so good for (at this time).
307 // Consider about using IP address of the victim, try to avoid that.
308 function _preg_replace_callback_domain_exposure($matches = array())
312 // Preserve the victim URI as a complicity or ...
313 if (isset($matches[5])) {
315 $matches[1] . '://' . // scheme
316 $matches[2] . '/' . // victim.example.org
317 $matches[3]; // The rest of all (before victim)
321 if (isset($matches[4])) {
323 $matches[1] . '://' . // scheme
324 $matches[4] . // nasty.example.com
325 '/?refer=' . strtolower($matches[2]) . // victim.example.org
332 // Preprocess: rawurldecode() and adding space(s) and something
333 // to detect/count some URIs _if possible_
334 // NOTE: It's maybe danger to var_dump(result). [e.g. 'javascript:']
335 // [OK] http://victim.example.org/go?http%3A%2F%2Fnasty.example.org
336 // [OK] http://victim.example.org/http://nasty.example.org
337 // TODO: link.toolbot.com, urlx.org
338 function spam_uri_pickup_preprocess($string = '')
340 if (! is_string($string)) return '';
342 $string = rawurldecode($string);
344 // Domain exposure (See _preg_replace_callback_domain_exposure())
345 $string = preg_replace_callback(
349 // Something Google: http://www.google.com/supported_domains
350 '(?:[a-z0-9.]+\.)?google\.[a-z]{2,3}(?:\.[a-z]{2})?' .
353 '(?:[a-z0-9.]+\.)?altavista.com' .
357 '([a-z0-9?=&.%_/\'\\\+-]+)' . // path/?query=foo+bar+
358 '\bsite:([a-z0-9.%_-]+\.[a-z0-9.%_-]+)' . // site:nasty.example.com
359 //'()' . // Preserve or remove?
362 '_preg_replace_callback_domain_exposure',
366 // URI exposure (uriuri => uri uri)
367 $string = preg_replace(
369 '#(?<! )(?:https?|ftp):/#i',
370 // '#[a-z][a-z0-9.+-]{1,8}://#i',
371 // '#[a-z][a-z0-9.+-]{1,8}://#i'
380 // Main function of spam-uri pickup,
381 // A wrapper function of uri_pickup()
382 function spam_uri_pickup($string = '', $method = array())
384 if (! is_array($method) || empty($method)) {
385 $method = check_uri_spam_method();
388 $string = spam_uri_pickup_preprocess($string);
390 $array = uri_pickup($string);
392 // Area elevation of URIs, for '(especially external)link' intension
393 if (! empty($array)) {
395 if (isset($method['uri_anchor'])) $_method['uri_anchor'] = & $method['uri_anchor'];
396 if (isset($method['uri_bbcode'])) $_method['uri_bbcode'] = & $method['uri_bbcode'];
397 $areas = area_pickup($string, $_method, TRUE);
398 if (! empty($areas)) {
399 $area_shadow = array();
400 foreach (array_keys($array) as $key) {
401 $area_shadow[$key] = & $array[$key]['area'];
402 foreach (array_keys($_method) as $_key) {
403 $area_shadow[$key][$_key] = 0;
406 foreach (array_keys($_method) as $_key) {
407 if (isset($areas[$_key])) {
408 area_measure($areas[$_key], $area_shadow, 1, $_key);
414 // Remove 'offset's for area_measure()
415 foreach(array_keys($array) as $key)
416 unset($array[$key]['area']['offset']);
422 // ---------------------
425 // Scheme normalization: Renaming the schemes
426 // snntp://example.org => nntps://example.org
427 // NOTE: Keep the static lists simple. See also port_normalize().
428 function scheme_normalize($scheme = '', $abbrevs_harmfull = TRUE)
430 // Abbreviations they have no intention of link
431 static $abbrevs = array(
436 // Aliases => normalized ones
437 static $aliases = array(
447 if (! is_string($scheme)) return '';
449 $scheme = strtolower($scheme);
450 if (isset($abbrevs[$scheme])) {
451 $scheme = $abbrevs_harmfull ? $abbrevs[$scheme] : '';
453 if (isset($aliases[$scheme])) {
454 $scheme = $aliases[$scheme];
460 // Hostname normlization (Destructive)
461 // www.foo => www.foo ('foo' seems TLD)
462 // www.foo.bar => foo.bar
463 // www.10.20 => www.10.20 (Invalid hostname)
465 // 'www' is mostly used as traditional hostname of WWW server.
466 // 'www.foo.bar' may be identical with 'foo.bar'.
467 function host_normalize($host = '')
469 if (! is_string($host)) return '';
471 $host = strtolower($host);
473 if (preg_match('/^www\.(.+\.[a-z]+)$/', $host, $matches)) {
480 // Port normalization: Suppress the (redundant) default port
481 // HTTP://example.org:80/ => http://example.org/
482 // HTTP://example.org:8080/ => http://example.org:8080/
483 // HTTPS://example.org:443/ => https://example.org/
484 function port_normalize($port, $scheme, $scheme_normalize = FALSE)
486 // Schemes that users _maybe_ want to add protocol-handlers
487 // to their web browsers. (and attackers _maybe_ want to use ...)
488 // Reference: http://www.iana.org/assignments/port-numbers
489 static $array = array(
490 // scheme => default port
516 // intval() converts '0-1' to '0', so preg_match() rejects these invalid ones
517 if (! is_numeric($port) || $port < 0 || preg_match('/[^0-9]/i', $port))
520 $port = intval($port);
521 if ($scheme_normalize) $scheme = scheme_normalize($scheme);
522 if (isset($array[$scheme]) && $port == $array[$scheme])
523 $port = ''; // Ignore the defaults
528 // Path normalization
529 // http://example.org => http://example.org/
530 // http://example.org#hoge => http://example.org/#hoge
531 // http://example.org/path/a/b/./c////./d => http://example.org/path/a/b/c/d
532 // http://example.org/path/../../a/../back => http://example.org/back
533 function path_normalize($path = '', $divider = '/', $add_root = TRUE)
535 if (! is_string($divider)) return is_string($path) ? $path : '';
538 $first_div = & $divider;
542 if (! is_string($path) || $path == '') return $first_div;
544 if (strpos($path, $divider, strlen($path) - strlen($divider)) === FALSE) {
547 $last_div = & $divider;
550 $array = explode($divider, $path);
552 // Remove paddings ('//' and '/./')
553 foreach(array_keys($array) as $key) {
554 if ($array[$key] == '' || $array[$key] == '.') {
559 // Remove back-tracks ('/../')
561 foreach($array as $value) {
562 if ($value == '..') {
565 array_push($tmp, $value);
573 return $first_div . implode($divider, $array) . $last_div;
577 // DirectoryIndex normalize (Destructive and rough)
578 // TODO: sample.en.ja.html.gz => sample.html
579 function file_normalize($file = 'index.html.en')
581 static $simple_defaults = array(
582 'default.htm' => TRUE,
583 'default.html' => TRUE,
584 'default.asp' => TRUE,
585 'default.aspx' => TRUE,
586 'index' => TRUE, // Some system can omit the suffix
589 static $content_suffix = array(
590 // index.xxx, sample.xxx
605 static $language_suffix = array(
606 // Reference: Apache 2.0.59 'AddLanguage' default
635 // Reference: Apache 2.0.59 default 'index.html' variants
641 static $charset_suffix = array(
642 // Reference: Apache 2.0.59 'AddCharset' default
643 'iso8859-1' => TRUE, // ISO-8859-1
644 'latin1' => TRUE, // ISO-8859-1
645 'iso8859-2' => TRUE, // ISO-8859-2
646 'latin2' => TRUE, // ISO-8859-2
647 'cen' => TRUE, // ISO-8859-2
648 'iso8859-3' => TRUE, // ISO-8859-3
649 'latin3' => TRUE, // ISO-8859-3
650 'iso8859-4' => TRUE, // ISO-8859-4
651 'latin4' => TRUE, // ISO-8859-4
652 'iso8859-5' => TRUE, // ISO-8859-5
653 'latin5' => TRUE, // ISO-8859-5
654 'cyr' => TRUE, // ISO-8859-5
655 'iso-ru' => TRUE, // ISO-8859-5
656 'iso8859-6' => TRUE, // ISO-8859-6
657 'latin6' => TRUE, // ISO-8859-6
658 'arb' => TRUE, // ISO-8859-6
659 'iso8859-7' => TRUE, // ISO-8859-7
660 'latin7' => TRUE, // ISO-8859-7
661 'grk' => TRUE, // ISO-8859-7
662 'iso8859-8' => TRUE, // ISO-8859-8
663 'latin8' => TRUE, // ISO-8859-8
664 'heb' => TRUE, // ISO-8859-8
665 'iso8859-9' => TRUE, // ISO-8859-9
666 'latin9' => TRUE, // ISO-8859-9
667 'trk' => TRUE, // ISO-8859-9
668 'iso2022-jp'=> TRUE, // ISO-2022-JP
669 'jis' => TRUE, // ISO-2022-JP
670 'iso2022-kr'=> TRUE, // ISO-2022-KR
671 'kis' => TRUE, // ISO-2022-KR
672 'iso2022-cn'=> TRUE, // ISO-2022-CN
673 'cis' => TRUE, // ISO-2022-CN
675 'cp-1251' => TRUE, // ru, WINDOWS-1251
676 'win-1251' => TRUE, // ru, WINDOWS-1251
677 'cp866' => TRUE, // ru
678 'koi8-r' => TRUE, // ru, KOI8-r
679 'koi8-ru' => TRUE, // ru, KOI8-r
680 'koi8-uk' => TRUE, // ru, KOI8-ru
681 'ua' => TRUE, // ru, KOI8-ru
682 'ucs2' => TRUE, // ru, ISO-10646-UCS-2
683 'ucs4' => TRUE, // ru, ISO-10646-UCS-4
686 // Reference: Apache 2.0.59 default 'index.html' variants
691 // May uncompress by web browsers on the fly
692 // Must be at the last of the filename
693 // Reference: Apache 2.0.59 'AddEncoding'
694 static $encoding_suffix = array(
699 if (! is_string($file)) return '';
700 $_file = strtolower($file);
701 if (isset($simple_defaults[$_file])) return '';
704 // [Apache 2 Content-negotiation (type-map)]
705 // Roughly removing language/character-set/encoding suffixes,
706 // (See Apache 2 document about 'mod_mime' and 'mod_negotiation',
707 // http://www.iana.org/assignments/character-sets, RFC3066, and ISO 639))
708 $suffixes = explode('.', $_file);
709 $body = array_shift($suffixes);
711 // Remove the liast .gz/.z
712 $last_key = end(array_keys($suffixes));
713 if (isset($encoding_suffix[$suffixes[$last_key]])) {
714 unset($suffixes[$last_key]);
717 // Cut language and charset suffixes
718 foreach($suffixes as $key => $value){
719 if (isset($language_suffix[$value]) || isset($charset_suffix[$value])) {
720 unset($suffixes[$key]);
723 if (empty($suffixes)) return $body;
726 $count = count($suffixes);
728 $current = current($suffixes);
729 if ($body == 'index' && $count == 1 && isset($content_suffix[$current])) return '';
734 // Sort query-strings if possible (Destructive and rough)
735 // [OK] &&&&f=d&b&d&c&a=0dd => a=0dd&b&c&d&f=d
736 // [OK] nothing==&eg=dummy&eg=padding&eg=foobar => eg=foobar
737 function query_normalize($string = '', $equal = TRUE, $equal_cutempty = TRUE, $stortolower = TRUE)
739 if ($stortolower) $string = strtolower($string);
741 $array = explode('&', $string);
743 // Remove '&' paddings
744 foreach(array_keys($array) as $key) {
745 if ($array[$key] == '') {
750 // Consider '='-sepalated input and paddings
752 $equals = $not_equals = array();
753 foreach ($array as $part) {
754 if (strpos($part, '=') === FALSE) {
755 $not_equals[] = $part;
757 list($key, $value) = explode('=', $part, 2);
758 $value = ltrim($value, '=');
759 if (! $equal_cutempty || $value != '') {
760 $equals[$key] = $value;
765 $array = & $not_equals;
766 foreach ($equals as $key => $value) {
767 $array[] = $key . '=' . $value;
773 return implode('&', $array);
776 // ---------------------
777 // Part One : Checker
779 // Rough implementation of globbing
781 // USAGE: $regex = '/^' . generate_glob_regex('*.txt', '/') . '$/i';
783 function generate_glob_regex($string = '', $divider = '/')
785 static $from = array(
788 // 22 => '[', // Maybe cause regex compilation error (e.g. '[]')
804 $string = str_replace($from, $mid, $string); // Hide
805 $string = preg_quote($string, $divider);
806 $string = str_replace($mid, $to, $string); // Unhide
811 // Rough hostname checker
813 // TODO: Strict digit, 0x, CIDR, IPv6
814 function is_ip($string = '')
816 if (preg_match('/^' .
817 '(?:[0-9]{1,3}\.){3}[0-9]{1,3}' . '|' .
818 '(?:[0-9]{1,3}\.){1,3}' . '$/',
820 return 4; // Seems IPv4(dot-decimal)
822 return 0; // Seems not IP
826 // Generate host (FQDN, IPv4, ...) regex
827 // 'localhost' : Matches with 'localhost' only
828 // 'example.org' : Matches with 'example.org' only (See host_normalize() about 'www')
829 // '.example.org' : Matches with ALL FQDN ended with '.example.org'
830 // '*.example.org' : Almost the same of '.example.org' except 'www.example.org'
831 // '10.20.30.40' : Matches with IPv4 address '10.20.30.40' only
832 // [TODO] '192.' : Matches with all IPv4 hosts started with '192.'
833 // TODO: IPv4, CIDR?, IPv6
834 function generate_host_regex($string = '', $divider = '/')
836 if (mb_strpos($string, '.') === FALSE)
837 return generate_glob_regex($string, $divider);
840 if (is_ip($string)) {
842 return generate_glob_regex($string, $divider);
845 $part = explode('.', $string, 2);
846 if ($part[0] == '') {
847 $part[0] = '(?:.*\.)?'; // And all related FQDN
848 } else if ($part[0] == '*') {
849 $part[0] = '.*\.'; // All subdomains/hosts only
851 return generate_glob_regex($string, $divider);
853 $part[1] = generate_glob_regex($part[1], $divider);
854 return implode('', $part);
858 function get_blocklist($list = '')
862 if (! isset($regexs)) {
864 if (file_exists(SPAM_INI_FILE)) {
865 $blocklist = array();
866 include(SPAM_INI_FILE);
867 // $blocklist['badhost'] = array(
868 // '*.blogspot.com', // Blog services's subdomains (only)
869 // 'IANA-examples' => '#^(?:.*\.)?example\.(?:com|net|org)$#',
871 foreach(array('goodhost', 'badhost') as $_list) {
872 if (! isset($blocklist[$list])) continue;
873 foreach ($blocklist[$_list] as $key => $value) {
874 if (is_array($value)) {
875 $regexs[$_list][$key] = array();
876 foreach($value as $_key => $_value) {
877 get_blocklist_add($regexs[$_list][$key], $_key, $_value);
880 get_blocklist_add($regexs[$_list], $key, $value);
888 return $regexs; // ALL
889 } else if (isset($regexs[$list])) {
890 return $regexs[$list];
896 // Subroutine of get_blocklist()
897 function get_blocklist_add(& $array, $key = 0, $value = '*.example.org')
899 if (is_string($key)) {
900 $array[$key] = & $value; // Treat $value as a regex
902 $array[$value] = '/^' . generate_host_regex($value, '/') . '$/i';
906 function is_badhost($hosts = array(), $asap = TRUE, & $remains)
909 if (! is_array($hosts)) $hosts = array($hosts);
910 foreach(array_keys($hosts) as $key) {
911 if (! is_string($hosts[$key])) unset($hosts[$key]);
913 if (empty($hosts)) return $result;
915 foreach (get_blocklist('goodhost') as $regex) {
916 $hosts = preg_grep_invert($regex, $hosts);
918 if (empty($hosts)) return $result;
921 foreach (get_blocklist('badhost') as $label => $regex) {
922 if (is_array($regex)) {
923 $result[$label] = array();
924 foreach($regex as $_label => $_regex) {
925 if (is_badhost_avail($_label, $_regex, $hosts, $result[$label]) && $asap) break;
927 if (empty($result[$label])) unset($result[$label]);
929 if (is_badhost_avail($label, $regex, $hosts, $result) && $asap) break;
938 // Subroutine for is_badhost()
939 function is_badhost_avail($label = '*.example.org', $regex = '/^.*\.example\.org$/', & $hosts, & $result)
941 $group = preg_grep($regex, $hosts);
943 $result[$label] = & $group;
944 $hosts = array_diff($hosts, $result[$label]);
951 // Default (enabled) methods and thresholds (for content insertion)
952 function check_uri_spam_method($times = 1, $t_area = 0, $rule = TRUE)
954 $times = intval($times);
955 $t_area = intval($t_area);
959 'quantity' => 8 * $times, // Allow N URIs
960 'non_uniqhost' => 3 * $times, // Allow N duped (and normalized) Hosts
961 //'non_uniquri'=> 3 * $times, // Allow N duped (and normalized) URIs
964 'area_anchor' => $t_area, // Using <a href> HTML tag
965 'area_bbcode' => $t_area, // Using [url] or [link] BBCode
966 //'uri_anchor' => $t_area, // URI inside <a href> HTML tag
967 //'uri_bbcode' => $t_area, // URI inside [url] or [link] BBCode
972 //'asap' => TRUE, // Quit or return As Soon As Possible
973 'uniqhost' => TRUE, // Show uniq host (at block notification mail)
974 'badhost' => TRUE, // Check badhost
980 // Remove non-$positive values
981 foreach (array_keys($positive) as $key) {
982 if ($positive[$key] < 0) unset($positive[$key]);
985 return $positive + $bool;
988 // Simple/fast spam check
989 function check_uri_spam($target = '', $method = array())
991 if (! is_array($method) || empty($method)) {
992 $method = check_uri_spam_method();
1006 'is_spam' => array(),
1007 'method' => & $method,
1008 'remains' => array(),
1011 $sum = & $progress['sum'];
1012 $is_spam = & $progress['is_spam'];
1013 $remains = & $progress['remains'];
1014 $error = & $progress['error'];
1015 $asap = isset($method['asap']);
1018 if (is_array($target)) {
1019 foreach($target as $str) {
1021 $_progress = check_uri_spam($str, $method);
1022 $_sum = & $_progress['sum'];
1023 $_is_spam = & $_progress['is_spam'];
1024 $_remains = & $_progress['remains'];
1025 $_error = & $_progress['error'];
1026 foreach (array_keys($_sum) as $key) {
1027 $sum[$key] += $_sum[$key];
1029 foreach (array_keys($_is_spam) as $key) {
1030 if (is_array($_is_spam[$key])) {
1031 // Marge keys (badhost)
1032 foreach(array_keys($_is_spam[$key]) as $_key) {
1033 if (! isset($is_spam[$key][$_key])) {
1034 $is_spam[$key][$_key] = $_is_spam[$key][$_key];
1036 $is_spam[$key][$_key] += $_is_spam[$key][$_key];
1040 $is_spam[$key] = TRUE;
1043 foreach ($_remains as $key=>$value) {
1044 foreach ($value as $_key=>$_value) {
1045 if (is_int($_key)) {
1046 $remains[$key][] = $_value;
1048 $remains[$key][$_key] = $_value;
1052 if (! empty($_error)) $error += $_error;
1053 if ($asap && $is_spam) break;
1058 // Area: There's HTML anchor tag
1059 if ((! $asap || ! $is_spam) && isset($method['area_anchor'])) {
1060 $key = 'area_anchor';
1061 $_asap = isset($method['asap']) ? array('asap' => TRUE) : array();
1062 $result = area_pickup($target, array($key => TRUE) + $_asap);
1064 $sum[$key] = $result[$key];
1065 if (isset($method[$key]) && $sum[$key] > $method[$key]) {
1066 $is_spam[$key] = TRUE;
1071 // Area: There's 'BBCode' linking tag
1072 if ((! $asap || ! $is_spam) && isset($method['area_bbcode'])) {
1073 $key = 'area_bbcode';
1074 $_asap = isset($method['asap']) ? array('asap' => TRUE) : array();
1075 $result = area_pickup($target, array($key => TRUE) + $_asap);
1077 $sum[$key] = $result[$key];
1078 if (isset($method[$key]) && $sum[$key] > $method[$key]) {
1079 $is_spam[$key] = TRUE;
1085 if ($asap && $is_spam) return $progress;
1088 $pickups = spam_uri_pickup($target, $method);
1089 //$remains['uri_pickup'] = & $pickups;
1092 if (empty($pickups)) return $progress;
1094 // URI: Check quantity
1095 $sum['quantity'] += count($pickups);
1097 if ((! $asap || ! $is_spam) && isset($method['quantity']) &&
1098 $sum['quantity'] > $method['quantity']) {
1099 $is_spam['quantity'] = TRUE;
1102 // URI: used inside HTML anchor tag pair
1103 if ((! $asap || ! $is_spam) && isset($method['uri_anchor'])) {
1104 $key = 'uri_anchor';
1105 foreach($pickups as $pickup) {
1106 if (isset($pickup['area'][$key])) {
1107 $sum[$key] += $pickup['area'][$key];
1108 if(isset($method[$key]) &&
1109 $sum[$key] > $method[$key]) {
1110 $is_spam[$key] = TRUE;
1111 if ($asap && $is_spam) break;
1113 if ($asap && $is_spam) break;
1118 // URI: used inside 'BBCode' pair
1119 if ((! $asap || ! $is_spam) && isset($method['uri_bbcode'])) {
1120 $key = 'uri_bbcode';
1121 foreach($pickups as $pickup) {
1122 if (isset($pickup['area'][$key])) {
1123 $sum[$key] += $pickup['area'][$key];
1124 if(isset($method[$key]) &&
1125 $sum[$key] > $method[$key]) {
1126 $is_spam[$key] = TRUE;
1127 if ($asap && $is_spam) break;
1129 if ($asap && $is_spam) break;
1134 // URI: Uniqueness (and removing non-uniques)
1135 if ((! $asap || ! $is_spam) && isset($method['non_uniquri'])) {
1137 uri_pickup_normalize($pickups);
1140 foreach (array_keys($pickups) as $key) {
1141 $uris[$key] = uri_pickup_implode($pickups[$key]);
1143 $count = count($uris);
1144 $uris = array_unique($uris);
1145 $sum['non_uniquri'] += $count - count($uris);
1146 if ($sum['non_uniquri'] > $method['non_uniquri']) {
1147 $is_spam['non_uniquri'] = TRUE;
1149 if (! $asap || ! $is_spam) {
1150 foreach (array_diff(array_keys($pickups),
1151 array_keys($uris)) as $remove) {
1152 unset($pickups[$remove]);
1159 if ($asap && $is_spam) return $progress;
1161 // Host: Uniqueness (uniq / non-uniq)
1163 foreach ($pickups as $pickup) $hosts[] = & $pickup['host'];
1164 $hosts = array_unique($hosts);
1165 //$remains['uniqhost'] = & $hosts;
1166 $sum['uniqhost'] += count($hosts);
1167 if ((! $asap || ! $is_spam) && isset($method['non_uniqhost'])) {
1168 $sum['non_uniqhost'] = $sum['quantity'] - $sum['uniqhost'];
1169 if ($sum['non_uniqhost'] > $method['non_uniqhost']) {
1170 $is_spam['non_uniqhost'] = TRUE;
1175 if ($asap && $is_spam) return $progress;
1178 if ((! $asap || ! $is_spam) && isset($method['badhost'])) {
1179 $__remains = array();
1180 $badhost = is_badhost($hosts, $asap, $__remains);
1183 $remains['badhost'] = array();
1184 foreach ($__remains as $value) {
1185 $remains['badhost'][$value] = TRUE;
1190 if (! empty($badhost)) {
1191 //var_dump($badhost); // BADHOST detail
1192 $sum['badhost'] += array_count_leaves($badhost);
1193 foreach(array_keys($badhost) as $keys) {
1194 $is_spam['badhost'][$keys] =
1195 array_count_leaves($badhost[$keys]);
1205 function array_count_leaves($array = array(), $count_empty_array = FALSE)
1207 if (! is_array($array) || (empty($array) && $count_empty_array))
1212 foreach ($array as $part) {
1213 $result += array_count_leaves($part, $count_empty_array);
1218 // ---------------------
1221 // TODO: Don't show unused $method!
1222 // Summarize $progress (blocked only)
1223 function summarize_spam_progress($progress = array(), $blockedonly = FALSE)
1226 $tmp = array_keys($progress['is_spam']);
1229 $method = & $progress['method'];
1230 if (isset($progress['sum'])) {
1231 foreach ($progress['sum'] as $key => $value) {
1232 if (isset($method[$key])) {
1233 $tmp[] = $key . '(' . $value . ')';
1239 return implode(', ', $tmp);
1242 // ---------------------
1245 // Common bahavior for blocking
1246 // NOTE: Call this function from various blocking feature, to disgueise the reason 'why blocked'
1247 function spam_exit($mode = '', $data = array())
1250 case '': echo("\n"); break;
1252 echo('<pre>' . "\n");
1253 echo htmlspecialchars(var_export($data, TRUE));
1254 echo('</pre>' . "\n");
1263 // ---------------------
1266 // TODO: Record them
1267 // Simple/fast spam filter ($target: 'a string' or an array())
1268 function pkwk_spamfilter($action, $page, $target = array('title' => ''), $method = array(), $exitmode = '')
1270 $progress = check_uri_spam($target, $method);
1272 if (! empty($progress['is_spam'])) {
1273 // Mail to administrator(s)
1274 pkwk_spamnotify($action, $page, $target, $progress, $method);
1277 spam_exit($exitmode, $progress);
1281 // ---------------------
1282 // PukiWiki original
1284 // Mail to administrator(s)
1285 function pkwk_spamnotify($action, $page, $target = array('title' => ''), $progress = array(), $method = array())
1287 global $notify, $notify_subject;
1289 if (! $notify) return;
1291 $asap = isset($method['asap']);
1293 $summary['ACTION'] = 'Blocked by: ' . summarize_spam_progress($progress, TRUE);
1295 $summary['METRICS'] = summarize_spam_progress($progress);
1297 if (isset($progress['is_spam']['badhost'])) {
1299 foreach($progress['is_spam']['badhost'] as $glob=>$number) {
1300 $badhost[] = $glob . '(' . $number . ')';
1302 $summary['DETAIL_BADHOST'] = implode(', ', $badhost);
1304 if (! $asap && $progress['remains']['badhost']) {
1305 $count = count($progress['remains']['badhost']);
1306 $summary['DETAIL_NEUTRAL_HOST'] = $count .
1309 '/[^, a-z0-9.-]/i', '',
1310 implode(', ', array_keys($progress['remains']['badhost']))
1314 $summary['COMMENT'] = $action;
1315 $summary['PAGE'] = '[blocked] ' . (is_pagename($page) ? $page : '');
1316 $summary['URI'] = get_script_uri() . '?' . rawurlencode($page);
1317 $summary['USER_AGENT'] = TRUE;
1318 $summary['REMOTE_ADDR'] = TRUE;
1319 pkwk_mail_notify($notify_subject, var_export($target, TRUE), $summary, TRUE);