2 // $Id: spam.php,v 1.136 2007/04/28 13:13:30 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));
41 // http://www.freebsd.org/cgi/man.cgi?query=strings (Man-page of GNU strings)
42 // http://www.pcre.org/pcre.txt
43 function strings($binary = '', $min_len = 4, $ignore_space = FALSE)
46 $binary = preg_replace(
48 '/(?:[^[:graph:] \t\n]|[\r])+/s',
61 $binary = preg_replace('/(?:[^[:graph:][:space:]]|[\r])+/s', "\n", $binary);
65 $min_len = min(1024, intval($min_len));
68 preg_grep('/^.{' . $min_len . ',}/S',
69 explode("\n", $binary)
78 // ---------------------
81 // Return an array of URIs in the $string
82 // [OK] http://nasty.example.org#nasty_string
83 // [OK] http://nasty.example.org:80/foo/xxx#nasty_string/bar
84 // [OK] ftp://nasty.example.org:80/dfsdfs
85 // [OK] ftp://cnn.example.com&story=breaking_news@10.0.0.1/top_story.htm (from RFC3986)
86 function uri_pickup($string = '')
88 if (! is_string($string)) return array();
90 // Not available for: IDN(ignored)
93 // scheme://userinfo@host:port/path/or/pathinfo/maybefile.and?query=string#fragment
94 // Refer RFC3986 (Regex below is not strict)
95 '#(\b[a-z][a-z0-9.+-]{1,8}):/+' . // 1: Scheme
97 '([^\s<>"\'\[\]/\#?@]*)' . // 2: Userinfo (Username)
101 '\[[0-9a-f:.]+\]' . '|' . // IPv6([colon-hex and dot]): RFC2732
102 '(?:[0-9]{1,3}\.){3}[0-9]{1,3}' . '|' . // IPv4(dot-decimal): 001.22.3.44
103 '[a-z0-9.-]+' . // hostname(FQDN) : foo.example.org
105 '(?::([0-9]*))?' . // 4: Port
106 '((?:/+[^\s<>"\'\[\]/\#]+)*/+)?' . // 5: Directory path or path-info
107 '([^\s<>"\'\[\]\#?]+)?' . // 6: File?
108 '(?:\?([^\s<>"\'\[\]\#]+))?' . // 7: Query string
109 '(?:\#([a-z0-9._~%!$&\'()*+,;=:@-]*))?' . // 8: Fragment
111 $string, $array, PREG_SET_ORDER | PREG_OFFSET_CAPTURE
115 static $parts = array(
116 1 => 'scheme', 2 => 'userinfo', 3 => 'host', 4 => 'port',
117 5 => 'path', 6 => 'file', 7 => 'query', 8 => 'fragment'
119 $default = array('');
120 foreach(array_keys($array) as $uri) {
121 $_uri = & $array[$uri];
122 array_rename_keys($_uri, $parts, TRUE, $default);
123 $offset = $_uri['scheme'][1]; // Scheme's offset = URI's offset
124 foreach(array_keys($_uri) as $part) {
125 $_uri[$part] = & $_uri[$part][0]; // Remove offsets
129 foreach(array_keys($array) as $uri) {
130 $_uri = & $array[$uri];
131 if ($_uri['scheme'] === '') {
132 unset($array[$uri]); // Considererd harmless
135 unset($_uri[0]); // Matched string itself
136 $_uri['area']['offset'] = $offset; // Area offset for area_measure()
142 // Normalize an array of URI arrays
143 // NOTE: Give me the uri_pickup() results
144 function uri_pickup_normalize(& $pickups, $destructive = TRUE)
146 if (! is_array($pickups)) return $pickups;
149 foreach (array_keys($pickups) as $key) {
150 $_key = & $pickups[$key];
151 $_key['scheme'] = isset($_key['scheme']) ? scheme_normalize($_key['scheme']) : '';
152 $_key['host'] = isset($_key['host']) ? host_normalize($_key['host']) : '';
153 $_key['port'] = isset($_key['port']) ? port_normalize($_key['port'], $_key['scheme'], FALSE) : '';
154 $_key['path'] = isset($_key['path']) ? strtolower(path_normalize($_key['path'])) : '';
155 $_key['file'] = isset($_key['file']) ? file_normalize($_key['file']) : '';
156 $_key['query'] = isset($_key['query']) ? query_normalize($_key['query']) : '';
157 $_key['fragment'] = isset($_key['fragment']) ? strtolower($_key['fragment']) : '';
160 foreach (array_keys($pickups) as $key) {
161 $_key = & $pickups[$key];
162 $_key['scheme'] = isset($_key['scheme']) ? scheme_normalize($_key['scheme']) : '';
163 $_key['host'] = isset($_key['host']) ? strtolower($_key['host']) : '';
164 $_key['port'] = isset($_key['port']) ? port_normalize($_key['port'], $_key['scheme'], FALSE) : '';
165 $_key['path'] = isset($_key['path']) ? path_normalize($_key['path']) : '';
172 // An URI array => An URI (See uri_pickup())
174 // $pickups = uri_pickup('a string include some URIs');
176 // foreach (array_keys($pickups) as $key) {
177 // $uris[$key] = uri_pickup_implode($pickups[$key]);
179 function uri_pickup_implode($uri = array())
181 if (empty($uri) || ! is_array($uri)) return NULL;
184 if (isset($uri['scheme']) && $uri['scheme'] !== '') {
185 $tmp[] = & $uri['scheme'];
188 if (isset($uri['userinfo']) && $uri['userinfo'] !== '') {
189 $tmp[] = & $uri['userinfo'];
192 if (isset($uri['host']) && $uri['host'] !== '') {
193 $tmp[] = & $uri['host'];
195 if (isset($uri['port']) && $uri['port'] !== '') {
197 $tmp[] = & $uri['port'];
199 if (isset($uri['path']) && $uri['path'] !== '') {
200 $tmp[] = & $uri['path'];
202 if (isset($uri['file']) && $uri['file'] !== '') {
203 $tmp[] = & $uri['file'];
205 if (isset($uri['query']) && $uri['query'] !== '') {
207 $tmp[] = & $uri['query'];
209 if (isset($uri['fragment']) && $uri['fragment'] !== '') {
211 $tmp[] = & $uri['fragment'];
214 return implode('', $tmp);
217 // $array['something'] => $array['wanted']
218 function array_rename_keys(& $array, $keys = array('from' => 'to'), $force = FALSE, $default = '')
220 if (! is_array($array) || ! is_array($keys)) return FALSE;
222 // Nondestructive test
224 foreach(array_keys($keys) as $from)
225 if (! isset($array[$from]))
228 foreach($keys as $from => $to) {
229 if ($from === $to) continue;
230 if (! $force || isset($array[$from])) {
231 $array[$to] = & $array[$from];
232 unset($array[$from]);
234 $array[$to] = $default;
241 // ---------------------
244 // Pickup all of markup areas
245 function area_pickup($string = '', $method = array())
248 if (empty($method)) return $area;
250 // Anchor tag pair by preg_match and preg_match_all()
252 // [OK] <a href= >Good site!</a>
253 // [OK] <a href= "#" >test</a>
254 // [OK] <a href="http://nasty.example.com">visit http://nasty.example.com/</a>
255 // [OK] <a href=\'http://nasty.example.com/\' >discount foobar</a>
256 // [NG] <a href="http://ng.example.com">visit http://ng.example.com _not_ended_
257 $regex = '#<a\b[^>]*\bhref\b[^>]*>.*?</a\b[^>]*(>)#is';
258 if (isset($method['area_anchor'])) {
260 $count = isset($method['asap']) ?
261 preg_match($regex, $string) :
262 preg_match_all($regex, $string, $areas);
263 if (! empty($count)) $area['area_anchor'] = $count;
265 if (isset($method['uri_anchor'])) {
267 preg_match_all($regex, $string, $areas, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
268 foreach(array_keys($areas) as $_area) {
269 $areas[$_area] = array(
270 $areas[$_area][0][1], // Area start (<a href>)
271 $areas[$_area][1][1], // Area end (</a>)
274 if (! empty($areas)) $area['uri_anchor'] = $areas;
277 // phpBB's "BBCode" pair by preg_match and preg_match_all()
279 // [OK] [url]http://nasty.example.com/[/url]
280 // [OK] [link]http://nasty.example.com/[/link]
281 // [OK] [url=http://nasty.example.com]visit http://nasty.example.com/[/url]
282 // [OK] [link http://nasty.example.com/]buy something[/link]
283 $regex = '#\[(url|link)\b[^\]]*\].*?\[/\1\b[^\]]*(\])#is';
284 if (isset($method['area_bbcode'])) {
286 $count = isset($method['asap']) ?
287 preg_match($regex, $string) :
288 preg_match_all($regex, $string, $areas, PREG_SET_ORDER);
289 if (! empty($count)) $area['area_bbcode'] = $count;
291 if (isset($method['uri_bbcode'])) {
293 preg_match_all($regex, $string, $areas, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
294 foreach(array_keys($areas) as $_area) {
295 $areas[$_area] = array(
296 $areas[$_area][0][1], // Area start ([url])
297 $areas[$_area][2][1], // Area end ([/url])
300 if (! empty($areas)) $area['uri_bbcode'] = $areas;
303 // Various Wiki syntax
304 // [text_or_uri>text_or_uri]
305 // [text_or_uri:text_or_uri]
306 // [text_or_uri|text_or_uri]
307 // [text_or_uri->text_or_uri]
308 // [text_or_uri text_or_uri] // MediaWiki
309 // MediaWiki: [http://nasty.example.com/ visit http://nasty.example.com/]
314 // If in doubt, it's a little doubtful
315 // if (Area => inside <= Area) $brief += -1
316 function area_measure($areas, & $array, $belief = -1, $a_key = 'area', $o_key = 'offset')
318 if (! is_array($areas) || ! is_array($array)) return;
320 $areas_keys = array_keys($areas);
321 foreach(array_keys($array) as $u_index) {
322 $offset = isset($array[$u_index][$o_key]) ?
323 intval($array[$u_index][$o_key]) : 0;
324 foreach($areas_keys as $a_index) {
325 if (isset($array[$u_index][$a_key])) {
326 $offset_s = intval($areas[$a_index][0]);
327 $offset_e = intval($areas[$a_index][1]);
328 // [Area => inside <= Area]
329 if ($offset_s < $offset && $offset < $offset_e) {
330 $array[$u_index][$a_key] += $belief;
337 // ---------------------
340 // Domain exposure callback (See spam_uri_pickup_preprocess())
341 // http://victim.example.org/?foo+site:nasty.example.com+bar
342 // => http://nasty.example.com/?refer=victim.example.org
343 // NOTE: 'refer=' is not so good for (at this time).
344 // Consider about using IP address of the victim, try to avoid that.
345 function _preg_replace_callback_domain_exposure($matches = array())
349 // Preserve the victim URI as a complicity or ...
350 if (isset($matches[5])) {
352 $matches[1] . '://' . // scheme
353 $matches[2] . '/' . // victim.example.org
354 $matches[3]; // The rest of all (before victim)
358 if (isset($matches[4])) {
360 $matches[1] . '://' . // scheme
361 $matches[4] . // nasty.example.com
362 '/?refer=' . strtolower($matches[2]) . // victim.example.org
369 // Preprocess: rawurldecode() and adding space(s) and something
370 // to detect/count some URIs _if possible_
371 // NOTE: It's maybe danger to var_dump(result). [e.g. 'javascript:']
372 // [OK] http://victim.example.org/go?http%3A%2F%2Fnasty.example.org
373 // [OK] http://victim.example.org/http://nasty.example.org
374 // TODO: link.toolbot.com, urlx.org
375 function spam_uri_pickup_preprocess($string = '')
377 if (! is_string($string)) return '';
379 $string = rawurldecode($string);
381 // Domain exposure (See _preg_replace_callback_domain_exposure())
382 $string = preg_replace_callback(
386 // Something Google: http://www.google.com/supported_domains
387 '(?:[a-z0-9.]+\.)?google\.[a-z]{2,3}(?:\.[a-z]{2})?' .
390 '(?:[a-z0-9.]+\.)?altavista.com' .
394 '([a-z0-9?=&.%_/\'\\\+-]+)' . // path/?query=foo+bar+
395 '\bsite:([a-z0-9.%_-]+\.[a-z0-9.%_-]+)' . // site:nasty.example.com
396 //'()' . // Preserve or remove?
399 '_preg_replace_callback_domain_exposure',
403 // URI exposure (uriuri => uri uri)
404 $string = preg_replace(
406 '#(?<! )(?:https?|ftp):/#i',
407 // '#[a-z][a-z0-9.+-]{1,8}://#i',
408 // '#[a-z][a-z0-9.+-]{1,8}://#i'
417 // Main function of spam-uri pickup,
418 // A wrapper function of uri_pickup()
419 function spam_uri_pickup($string = '', $method = array())
421 if (! is_array($method) || empty($method)) {
422 $method = check_uri_spam_method();
425 $string = spam_uri_pickup_preprocess($string);
427 $array = uri_pickup($string);
429 // Area elevation of URIs, for '(especially external)link' intension
430 if (! empty($array)) {
432 if (isset($method['uri_anchor'])) $_method['uri_anchor'] = & $method['uri_anchor'];
433 if (isset($method['uri_bbcode'])) $_method['uri_bbcode'] = & $method['uri_bbcode'];
434 $areas = area_pickup($string, $_method, TRUE);
435 if (! empty($areas)) {
436 $area_shadow = array();
437 foreach (array_keys($array) as $key) {
438 $area_shadow[$key] = & $array[$key]['area'];
439 foreach (array_keys($_method) as $_key) {
440 $area_shadow[$key][$_key] = 0;
443 foreach (array_keys($_method) as $_key) {
444 if (isset($areas[$_key])) {
445 area_measure($areas[$_key], $area_shadow, 1, $_key);
451 // Remove 'offset's for area_measure()
452 foreach(array_keys($array) as $key)
453 unset($array[$key]['area']['offset']);
459 // ---------------------
462 // Scheme normalization: Renaming the schemes
463 // snntp://example.org => nntps://example.org
464 // NOTE: Keep the static lists simple. See also port_normalize().
465 function scheme_normalize($scheme = '', $abbrevs_harmfull = TRUE)
467 // Abbreviations they have no intention of link
468 static $abbrevs = array(
473 // Aliases => normalized ones
474 static $aliases = array(
484 if (! is_string($scheme)) return '';
486 $scheme = strtolower($scheme);
487 if (isset($abbrevs[$scheme])) {
488 $scheme = $abbrevs_harmfull ? $abbrevs[$scheme] : '';
490 if (isset($aliases[$scheme])) {
491 $scheme = $aliases[$scheme];
497 // Hostname normlization (Destructive)
498 // www.foo => www.foo ('foo' seems TLD)
499 // www.foo.bar => foo.bar
500 // www.10.20 => www.10.20 (Invalid hostname)
502 // 'www' is mostly used as traditional hostname of WWW server.
503 // 'www.foo.bar' may be identical with 'foo.bar'.
504 function host_normalize($host = '')
506 if (! is_string($host)) return '';
508 $host = strtolower($host);
510 if (preg_match('/^www\.(.+\.[a-z]+)$/', $host, $matches)) {
517 // Port normalization: Suppress the (redundant) default port
518 // HTTP://example.org:80/ => http://example.org/
519 // HTTP://example.org:8080/ => http://example.org:8080/
520 // HTTPS://example.org:443/ => https://example.org/
521 function port_normalize($port, $scheme, $scheme_normalize = FALSE)
523 // Schemes that users _maybe_ want to add protocol-handlers
524 // to their web browsers. (and attackers _maybe_ want to use ...)
525 // Reference: http://www.iana.org/assignments/port-numbers
526 static $array = array(
527 // scheme => default port
553 // intval() converts '0-1' to '0', so preg_match() rejects these invalid ones
554 if (! is_numeric($port) || $port < 0 || preg_match('/[^0-9]/i', $port))
557 $port = intval($port);
558 if ($scheme_normalize) $scheme = scheme_normalize($scheme);
559 if (isset($array[$scheme]) && $port == $array[$scheme])
560 $port = ''; // Ignore the defaults
565 // Path normalization
566 // http://example.org => http://example.org/
567 // http://example.org#hoge => http://example.org/#hoge
568 // http://example.org/path/a/b/./c////./d => http://example.org/path/a/b/c/d
569 // http://example.org/path/../../a/../back => http://example.org/back
570 function path_normalize($path = '', $divider = '/', $add_root = TRUE)
572 if (! is_string($divider)) return is_string($path) ? $path : '';
575 $first_div = & $divider;
579 if (! is_string($path) || $path == '') return $first_div;
581 if (strpos($path, $divider, strlen($path) - strlen($divider)) === FALSE) {
584 $last_div = & $divider;
587 $array = explode($divider, $path);
589 // Remove paddings ('//' and '/./')
590 foreach(array_keys($array) as $key) {
591 if ($array[$key] == '' || $array[$key] == '.') {
596 // Remove back-tracks ('/../')
598 foreach($array as $value) {
599 if ($value == '..') {
602 array_push($tmp, $value);
610 return $first_div . implode($divider, $array) . $last_div;
614 // DirectoryIndex normalize (Destructive and rough)
615 // TODO: sample.en.ja.html.gz => sample.html
616 function file_normalize($file = 'index.html.en')
618 static $simple_defaults = array(
619 'default.htm' => TRUE,
620 'default.html' => TRUE,
621 'default.asp' => TRUE,
622 'default.aspx' => TRUE,
623 'index' => TRUE, // Some system can omit the suffix
626 static $content_suffix = array(
627 // index.xxx, sample.xxx
642 static $language_suffix = array(
643 // Reference: Apache 2.0.59 'AddLanguage' default
672 // Reference: Apache 2.0.59 default 'index.html' variants
678 static $charset_suffix = array(
679 // Reference: Apache 2.0.59 'AddCharset' default
680 'iso8859-1' => TRUE, // ISO-8859-1
681 'latin1' => TRUE, // ISO-8859-1
682 'iso8859-2' => TRUE, // ISO-8859-2
683 'latin2' => TRUE, // ISO-8859-2
684 'cen' => TRUE, // ISO-8859-2
685 'iso8859-3' => TRUE, // ISO-8859-3
686 'latin3' => TRUE, // ISO-8859-3
687 'iso8859-4' => TRUE, // ISO-8859-4
688 'latin4' => TRUE, // ISO-8859-4
689 'iso8859-5' => TRUE, // ISO-8859-5
690 'latin5' => TRUE, // ISO-8859-5
691 'cyr' => TRUE, // ISO-8859-5
692 'iso-ru' => TRUE, // ISO-8859-5
693 'iso8859-6' => TRUE, // ISO-8859-6
694 'latin6' => TRUE, // ISO-8859-6
695 'arb' => TRUE, // ISO-8859-6
696 'iso8859-7' => TRUE, // ISO-8859-7
697 'latin7' => TRUE, // ISO-8859-7
698 'grk' => TRUE, // ISO-8859-7
699 'iso8859-8' => TRUE, // ISO-8859-8
700 'latin8' => TRUE, // ISO-8859-8
701 'heb' => TRUE, // ISO-8859-8
702 'iso8859-9' => TRUE, // ISO-8859-9
703 'latin9' => TRUE, // ISO-8859-9
704 'trk' => TRUE, // ISO-8859-9
705 'iso2022-jp'=> TRUE, // ISO-2022-JP
706 'jis' => TRUE, // ISO-2022-JP
707 'iso2022-kr'=> TRUE, // ISO-2022-KR
708 'kis' => TRUE, // ISO-2022-KR
709 'iso2022-cn'=> TRUE, // ISO-2022-CN
710 'cis' => TRUE, // ISO-2022-CN
712 'cp-1251' => TRUE, // ru, WINDOWS-1251
713 'win-1251' => TRUE, // ru, WINDOWS-1251
714 'cp866' => TRUE, // ru
715 'koi8-r' => TRUE, // ru, KOI8-r
716 'koi8-ru' => TRUE, // ru, KOI8-r
717 'koi8-uk' => TRUE, // ru, KOI8-ru
718 'ua' => TRUE, // ru, KOI8-ru
719 'ucs2' => TRUE, // ru, ISO-10646-UCS-2
720 'ucs4' => TRUE, // ru, ISO-10646-UCS-4
723 // Reference: Apache 2.0.59 default 'index.html' variants
728 // May uncompress by web browsers on the fly
729 // Must be at the last of the filename
730 // Reference: Apache 2.0.59 'AddEncoding'
731 static $encoding_suffix = array(
736 if (! is_string($file)) return '';
737 $_file = strtolower($file);
738 if (isset($simple_defaults[$_file])) return '';
741 // Roughly removing language/character-set/encoding suffixes
743 // * Apache 2 document about 'Content-negotiaton', 'mod_mime' and 'mod_negotiation'
744 // http://httpd.apache.org/docs/2.0/content-negotiation.html
745 // http://httpd.apache.org/docs/2.0/mod/mod_mime.html
746 // http://httpd.apache.org/docs/2.0/mod/mod_negotiation.html
747 // * http://www.iana.org/assignments/character-sets
748 // * RFC3066: Tags for the Identification of Languages
749 // http://www.ietf.org/rfc/rfc3066.txt
750 // * ISO 639: codes of 'language names'
751 $suffixes = explode('.', $_file);
752 $body = array_shift($suffixes);
754 // Remove the last .gz/.z
755 $last_key = end(array_keys($suffixes));
756 if (isset($encoding_suffix[$suffixes[$last_key]])) {
757 unset($suffixes[$last_key]);
760 // Cut language and charset suffixes
761 foreach($suffixes as $key => $value){
762 if (isset($language_suffix[$value]) || isset($charset_suffix[$value])) {
763 unset($suffixes[$key]);
766 if (empty($suffixes)) return $body;
769 $count = count($suffixes);
771 $current = current($suffixes);
772 if ($body == 'index' && $count == 1 && isset($content_suffix[$current])) return '';
777 // Sort query-strings if possible (Destructive and rough)
778 // [OK] &&&&f=d&b&d&c&a=0dd => a=0dd&b&c&d&f=d
779 // [OK] nothing==&eg=dummy&eg=padding&eg=foobar => eg=foobar
780 function query_normalize($string = '', $equal = TRUE, $equal_cutempty = TRUE, $stortolower = TRUE)
782 if (! is_string($string)) return '';
783 if ($stortolower) $string = strtolower($string);
785 $array = explode('&', $string);
787 // Remove '&' paddings
788 foreach(array_keys($array) as $key) {
789 if ($array[$key] == '') {
794 // Consider '='-sepalated input and paddings
796 $equals = $not_equals = array();
797 foreach ($array as $part) {
798 if (strpos($part, '=') === FALSE) {
799 $not_equals[] = $part;
801 list($key, $value) = explode('=', $part, 2);
802 $value = ltrim($value, '=');
803 if (! $equal_cutempty || $value != '') {
804 $equals[$key] = $value;
809 $array = & $not_equals;
810 foreach ($equals as $key => $value) {
811 $array[] = $key . '=' . $value;
817 return implode('&', $array);
820 // ---------------------
821 // Part One : Checker
823 // Rough implementation of globbing
825 // USAGE: $regex = '/^' . generate_glob_regex('*.txt', '/') . '$/i';
827 function generate_glob_regex($string = '', $divider = '/')
829 static $from = array(
832 // 22 => '[', // Maybe cause regex compilation error (e.g. '[]')
848 if (! is_string($string)) return '';
850 $string = str_replace($from, $mid, $string); // Hide
851 $string = preg_quote($string, $divider);
852 $string = str_replace($mid, $to, $string); // Unhide
857 // Rough hostname checker
859 // TODO: Strict digit, 0x, CIDR, IPv6
860 function is_ip($string = '')
862 if (preg_match('/^' .
863 '(?:[0-9]{1,3}\.){3}[0-9]{1,3}' . '|' .
864 '(?:[0-9]{1,3}\.){1,3}' . '$/',
866 return 4; // Seems IPv4(dot-decimal)
868 return 0; // Seems not IP
872 // Generate host (FQDN, IPv4, ...) regex
873 // 'localhost' : Matches with 'localhost' only
874 // 'example.org' : Matches with 'example.org' only (See host_normalize() about 'www')
875 // '.example.org' : Matches with ALL FQDN ended with '.example.org'
876 // '*.example.org' : Almost the same of '.example.org' except 'www.example.org'
877 // '10.20.30.40' : Matches with IPv4 address '10.20.30.40' only
878 // [TODO] '192.' : Matches with all IPv4 hosts started with '192.'
879 // TODO: IPv4, CIDR?, IPv6
880 function generate_host_regex($string = '', $divider = '/')
882 if (! is_string($string)) return '';
884 if (mb_strpos($string, '.') === FALSE)
885 return generate_glob_regex($string, $divider);
888 if (is_ip($string)) {
890 return generate_glob_regex($string, $divider);
893 $part = explode('.', $string, 2);
894 if ($part[0] == '') {
895 $part[0] = '(?:.*\.)?'; // And all related FQDN
896 } else if ($part[0] == '*') {
897 $part[0] = '.*\.'; // All subdomains/hosts only
899 return generate_glob_regex($string, $divider);
901 $part[1] = generate_glob_regex($part[1], $divider);
902 return implode('', $part);
906 function get_blocklist($list = '')
910 if (! isset($regexs)) {
912 if (file_exists(SPAM_INI_FILE)) {
913 $blocklist = array();
914 include(SPAM_INI_FILE);
915 // $blocklist['badhost'] = array(
916 // '*.blogspot.com', // Blog services's subdomains (only)
917 // 'IANA-examples' => '#^(?:.*\.)?example\.(?:com|net|org)$#',
919 if (isset($blocklist['list'])) {
920 $regexs['list'] = & $blocklist['list'];
923 $blocklist['list'] = array(
928 foreach(array_keys($blocklist['list']) as $_list) {
929 if (! isset($blocklist[$_list])) continue;
930 foreach ($blocklist[$_list] as $key => $value) {
931 if (is_array($value)) {
932 $regexs[$_list][$key] = array();
933 foreach($value as $_key => $_value) {
934 get_blocklist_add($regexs[$_list][$key], $_key, $_value);
937 get_blocklist_add($regexs[$_list], $key, $value);
940 unset($blocklist[$_list]);
946 return $regexs; // ALL
947 } else if (isset($regexs[$list])) {
948 return $regexs[$list];
954 // Subroutine of get_blocklist()
955 function get_blocklist_add(& $array, $key = 0, $value = '*.example.org')
957 if (is_string($key)) {
958 $array[$key] = & $value; // Treat $value as a regex
960 $array[$value] = '/^' . generate_host_regex($value, '/') . '$/i';
965 // Blocklist metrics: Separate $host, to $blocked and not blocked
966 function blocklist_distiller(& $hosts, $keys = array('goodhost', 'badhost'), $asap = FALSE)
968 if (! is_array($hosts)) $hosts = array($hosts);
969 if (! is_array($keys)) $keys = array($keys);
971 $list = get_blocklist('list');
974 foreach($keys as $key){
975 foreach (get_blocklist($key) as $label => $regex) {
976 if (is_array($regex)) {
977 foreach($regex as $_label => $_regex) {
978 $group = preg_grep($_regex, $hosts);
980 $hosts = array_diff($hosts, $group);
981 $blocked[$key][$label][$_label] = $group;
982 if ($asap && $list[$key]) break;
986 $group = preg_grep($regex, $hosts);
988 $hosts = array_diff($hosts, $group);
989 $blocked[$key][$label] = $group;
990 if ($asap && $list[$key]) break;
999 function is_badhost($hosts = array(), $asap = TRUE, & $remains)
1003 if (! is_array($hosts)) $hosts = array($hosts);
1004 foreach(array_keys($hosts) as $key) {
1005 if (! is_string($hosts[$key])) {
1006 unset($hosts[$key]);
1009 if (empty($hosts)) return $result;
1011 $list = get_blocklist('list');
1012 $blocked = blocklist_distiller($hosts, array_keys($list), $asap);
1013 foreach($list as $key=>$type){
1015 unset($blocked[$key]); // Ignore goodhost etc
1024 // Default (enabled) methods and thresholds (for content insertion)
1025 function check_uri_spam_method($times = 1, $t_area = 0, $rule = TRUE)
1027 $times = intval($times);
1028 $t_area = intval($t_area);
1032 'quantity' => 8 * $times, // Allow N URIs
1033 'non_uniqhost' => 3 * $times, // Allow N duped (and normalized) Hosts
1034 //'non_uniquri'=> 3 * $times, // Allow N duped (and normalized) URIs
1037 'area_anchor' => $t_area, // Using <a href> HTML tag
1038 'area_bbcode' => $t_area, // Using [url] or [link] BBCode
1039 //'uri_anchor' => $t_area, // URI inside <a href> HTML tag
1040 //'uri_bbcode' => $t_area, // URI inside [url] or [link] BBCode
1045 //'asap' => TRUE, // Quit or return As Soon As Possible
1046 'uniqhost' => TRUE, // Show uniq host (at block notification mail)
1047 'badhost' => TRUE, // Check badhost
1053 // Remove non-$positive values
1054 foreach (array_keys($positive) as $key) {
1055 if ($positive[$key] < 0) unset($positive[$key]);
1058 return $positive + $bool;
1061 // Simple/fast spam check
1062 function check_uri_spam($target = '', $method = array())
1064 if (! is_array($method) || empty($method)) {
1065 $method = check_uri_spam_method();
1079 'is_spam' => array(),
1080 'method' => & $method,
1081 'remains' => array(),
1084 $sum = & $progress['sum'];
1085 $is_spam = & $progress['is_spam'];
1086 $remains = & $progress['remains'];
1087 $error = & $progress['error'];
1088 $asap = isset($method['asap']);
1091 if (is_array($target)) {
1092 foreach($target as $str) {
1094 $_progress = check_uri_spam($str, $method);
1095 $_sum = & $_progress['sum'];
1096 $_is_spam = & $_progress['is_spam'];
1097 $_remains = & $_progress['remains'];
1098 $_error = & $_progress['error'];
1099 foreach (array_keys($_sum) as $key) {
1100 $sum[$key] += $_sum[$key];
1102 foreach (array_keys($_is_spam) as $key) {
1103 if (is_array($_is_spam[$key])) {
1104 // Marge keys (badhost)
1105 foreach(array_keys($_is_spam[$key]) as $_key) {
1106 if (! isset($is_spam[$key][$_key])) {
1107 $is_spam[$key][$_key] = $_is_spam[$key][$_key];
1109 $is_spam[$key][$_key] += $_is_spam[$key][$_key];
1113 $is_spam[$key] = TRUE;
1116 foreach ($_remains as $key=>$value) {
1117 foreach ($value as $_key=>$_value) {
1118 if (is_int($_key)) {
1119 $remains[$key][] = $_value;
1121 $remains[$key][$_key] = $_value;
1125 if (! empty($_error)) $error += $_error;
1126 if ($asap && $is_spam) break;
1131 // Area: There's HTML anchor tag
1132 if ((! $asap || ! $is_spam) && isset($method['area_anchor'])) {
1133 $key = 'area_anchor';
1134 $_asap = isset($method['asap']) ? array('asap' => TRUE) : array();
1135 $result = area_pickup($target, array($key => TRUE) + $_asap);
1137 $sum[$key] = $result[$key];
1138 if (isset($method[$key]) && $sum[$key] > $method[$key]) {
1139 $is_spam[$key] = TRUE;
1144 // Area: There's 'BBCode' linking tag
1145 if ((! $asap || ! $is_spam) && isset($method['area_bbcode'])) {
1146 $key = 'area_bbcode';
1147 $_asap = isset($method['asap']) ? array('asap' => TRUE) : array();
1148 $result = area_pickup($target, array($key => TRUE) + $_asap);
1150 $sum[$key] = $result[$key];
1151 if (isset($method[$key]) && $sum[$key] > $method[$key]) {
1152 $is_spam[$key] = TRUE;
1158 if ($asap && $is_spam) return $progress;
1161 $pickups = uri_pickup_normalize(spam_uri_pickup($target, $method));
1162 //$remains['uri_pickup'] = & $pickups;
1165 if (empty($pickups)) return $progress;
1167 // URI: Check quantity
1168 $sum['quantity'] += count($pickups);
1170 if ((! $asap || ! $is_spam) && isset($method['quantity']) &&
1171 $sum['quantity'] > $method['quantity']) {
1172 $is_spam['quantity'] = TRUE;
1175 // URI: used inside HTML anchor tag pair
1176 if ((! $asap || ! $is_spam) && isset($method['uri_anchor'])) {
1177 $key = 'uri_anchor';
1178 foreach($pickups as $pickup) {
1179 if (isset($pickup['area'][$key])) {
1180 $sum[$key] += $pickup['area'][$key];
1181 if(isset($method[$key]) &&
1182 $sum[$key] > $method[$key]) {
1183 $is_spam[$key] = TRUE;
1184 if ($asap && $is_spam) break;
1186 if ($asap && $is_spam) break;
1191 // URI: used inside 'BBCode' pair
1192 if ((! $asap || ! $is_spam) && isset($method['uri_bbcode'])) {
1193 $key = 'uri_bbcode';
1194 foreach($pickups as $pickup) {
1195 if (isset($pickup['area'][$key])) {
1196 $sum[$key] += $pickup['area'][$key];
1197 if(isset($method[$key]) &&
1198 $sum[$key] > $method[$key]) {
1199 $is_spam[$key] = TRUE;
1200 if ($asap && $is_spam) break;
1202 if ($asap && $is_spam) break;
1207 // URI: Uniqueness (and removing non-uniques)
1208 if ((! $asap || ! $is_spam) && isset($method['non_uniquri'])) {
1211 foreach (array_keys($pickups) as $key) {
1212 $uris[$key] = uri_pickup_implode($pickups[$key]);
1214 $count = count($uris);
1215 $uris = array_unique($uris);
1216 $sum['non_uniquri'] += $count - count($uris);
1217 if ($sum['non_uniquri'] > $method['non_uniquri']) {
1218 $is_spam['non_uniquri'] = TRUE;
1220 if (! $asap || ! $is_spam) {
1221 foreach (array_diff(array_keys($pickups),
1222 array_keys($uris)) as $remove) {
1223 unset($pickups[$remove]);
1230 if ($asap && $is_spam) return $progress;
1232 // Host: Uniqueness (uniq / non-uniq)
1234 foreach ($pickups as $pickup) $hosts[] = & $pickup['host'];
1235 $hosts = array_unique($hosts);
1236 //$remains['uniqhost'] = & $hosts;
1237 $sum['uniqhost'] += count($hosts);
1238 if ((! $asap || ! $is_spam) && isset($method['non_uniqhost'])) {
1239 $sum['non_uniqhost'] = $sum['quantity'] - $sum['uniqhost'];
1240 if ($sum['non_uniqhost'] > $method['non_uniqhost']) {
1241 $is_spam['non_uniqhost'] = TRUE;
1246 if ($asap && $is_spam) return $progress;
1249 if ((! $asap || ! $is_spam) && isset($method['badhost'])) {
1250 $__remains = array();
1251 $badhost = is_badhost($hosts, $asap, $__remains);
1254 $remains['badhost'] = array();
1255 foreach ($__remains as $value) {
1256 $remains['badhost'][$value] = TRUE;
1261 if (! empty($badhost)) {
1263 //var_dump($badhost); // BADHOST detail
1265 $sum['badhost'] += array_count_leaves($badhost);
1266 foreach(array_keys($badhost) as $keys) {
1267 $is_spam['badhost'][$keys] =
1268 array_count_leaves($badhost[$keys]);
1277 // Count leaves (A leaf = value that is not an array, or an empty array)
1278 function array_count_leaves($array = array(), $count_empty = FALSE)
1280 if (! is_array($array) || (empty($array) && $count_empty)) return 1;
1284 foreach ($array as $part) {
1285 $count += array_count_leaves($part, $count_empty);
1290 // ---------------------
1293 // TODO: Don't show unused $method!
1294 // Summarize $progress (blocked only)
1295 function summarize_spam_progress($progress = array(), $blockedonly = FALSE)
1298 $tmp = array_keys($progress['is_spam']);
1301 $method = & $progress['method'];
1302 if (isset($progress['sum'])) {
1303 foreach ($progress['sum'] as $key => $value) {
1304 if (isset($method[$key])) {
1305 $tmp[] = $key . '(' . $value . ')';
1311 return implode(', ', $tmp);
1314 // ---------------------
1317 // Common bahavior for blocking
1318 // NOTE: Call this function from various blocking feature, to disgueise the reason 'why blocked'
1319 function spam_exit($mode = '', $data = array())
1322 case '': echo("\n"); break;
1324 echo('<pre>' . "\n");
1325 echo htmlspecialchars(var_export($data, TRUE));
1326 echo('</pre>' . "\n");
1335 // ---------------------
1338 // TODO: Record them
1339 // Simple/fast spam filter ($target: 'a string' or an array())
1340 function pkwk_spamfilter($action, $page, $target = array('title' => ''), $method = array(), $exitmode = '')
1342 $progress = check_uri_spam($target, $method);
1344 if (! empty($progress['is_spam'])) {
1345 // Mail to administrator(s)
1346 pkwk_spamnotify($action, $page, $target, $progress, $method);
1349 spam_exit($exitmode, $progress);
1353 // ---------------------
1354 // PukiWiki original
1356 // Mail to administrator(s)
1357 function pkwk_spamnotify($action, $page, $target = array('title' => ''), $progress = array(), $method = array())
1359 global $notify, $notify_subject;
1361 if (! $notify) return;
1363 $asap = isset($method['asap']);
1365 $summary['ACTION'] = 'Blocked by: ' . summarize_spam_progress($progress, TRUE);
1367 $summary['METRICS'] = summarize_spam_progress($progress);
1369 if (isset($progress['is_spam']['badhost'])) {
1371 foreach($progress['is_spam']['badhost'] as $glob=>$number) {
1372 $badhost[] = $glob . '(' . $number . ')';
1374 $summary['DETAIL_BADHOST'] = implode(', ', $badhost);
1376 if (! $asap && $progress['remains']['badhost']) {
1377 $count = count($progress['remains']['badhost']);
1378 $summary['DETAIL_NEUTRAL_HOST'] = $count .
1381 '/[^, a-z0-9.-]/i', '',
1382 implode(', ', array_keys($progress['remains']['badhost']))
1386 $summary['COMMENT'] = $action;
1387 $summary['PAGE'] = '[blocked] ' . (is_pagename($page) ? $page : '');
1388 $summary['URI'] = get_script_uri() . '?' . rawurlencode($page);
1389 $summary['USER_AGENT'] = TRUE;
1390 $summary['REMOTE_ADDR'] = TRUE;
1391 pkwk_mail_notify($notify_subject, var_export($target, TRUE), $summary, TRUE);