2 // $Id: spam.php,v 1.133 2007/04/28 03:00: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 // Very roughly strings(1)
41 function strings($binary = '')
43 // http://www.pcre.org/pcre.txt
44 return preg_replace('/[[:^graph:]]+/', "\n", $binary);
48 // ---------------------
51 // Return an array of URIs in the $string
52 // [OK] http://nasty.example.org#nasty_string
53 // [OK] http://nasty.example.org:80/foo/xxx#nasty_string/bar
54 // [OK] ftp://nasty.example.org:80/dfsdfs
55 // [OK] ftp://cnn.example.com&story=breaking_news@10.0.0.1/top_story.htm (from RFC3986)
56 function uri_pickup($string = '')
58 if (! is_string($string)) return array();
60 // Not available for: IDN(ignored)
63 // scheme://userinfo@host:port/path/or/pathinfo/maybefile.and?query=string#fragment
64 // Refer RFC3986 (Regex below is not strict)
65 '#(\b[a-z][a-z0-9.+-]{1,8}):/+' . // 1: Scheme
67 '([^\s<>"\'\[\]/\#?@]*)' . // 2: Userinfo (Username)
71 '\[[0-9a-f:.]+\]' . '|' . // IPv6([colon-hex and dot]): RFC2732
72 '(?:[0-9]{1,3}\.){3}[0-9]{1,3}' . '|' . // IPv4(dot-decimal): 001.22.3.44
73 '[a-z0-9.-]+' . // hostname(FQDN) : foo.example.org
75 '(?::([0-9]*))?' . // 4: Port
76 '((?:/+[^\s<>"\'\[\]/\#]+)*/+)?' . // 5: Directory path or path-info
77 '([^\s<>"\'\[\]\#?]+)?' . // 6: File?
78 '(?:\?([^\s<>"\'\[\]\#]+))?' . // 7: Query string
79 '(?:\#([a-z0-9._~%!$&\'()*+,;=:@-]*))?' . // 8: Fragment
81 $string, $array, PREG_SET_ORDER | PREG_OFFSET_CAPTURE
85 static $parts = array(
86 1 => 'scheme', 2 => 'userinfo', 3 => 'host', 4 => 'port',
87 5 => 'path', 6 => 'file', 7 => 'query', 8 => 'fragment'
90 foreach(array_keys($array) as $uri) {
91 $_uri = & $array[$uri];
92 array_rename_keys($_uri, $parts, TRUE, $default);
93 $offset = $_uri['scheme'][1]; // Scheme's offset = URI's offset
94 foreach(array_keys($_uri) as $part) {
95 $_uri[$part] = & $_uri[$part][0]; // Remove offsets
99 foreach(array_keys($array) as $uri) {
100 $_uri = & $array[$uri];
101 if ($_uri['scheme'] === '') {
102 unset($array[$uri]); // Considererd harmless
105 unset($_uri[0]); // Matched string itself
106 $_uri['area']['offset'] = $offset; // Area offset for area_measure()
112 // Normalize an array of URI arrays
113 // NOTE: Give me the uri_pickup() results
114 function uri_pickup_normalize(& $pickups, $destructive = TRUE)
116 if (! is_array($pickups)) return $pickups;
119 foreach (array_keys($pickups) as $key) {
120 $_key = & $pickups[$key];
121 $_key['scheme'] = isset($_key['scheme']) ? scheme_normalize($_key['scheme']) : '';
122 $_key['host'] = isset($_key['host']) ? host_normalize($_key['host']) : '';
123 $_key['port'] = isset($_key['port']) ? port_normalize($_key['port'], $_key['scheme'], FALSE) : '';
124 $_key['path'] = isset($_key['path']) ? strtolower(path_normalize($_key['path'])) : '';
125 $_key['file'] = isset($_key['file']) ? file_normalize($_key['file']) : '';
126 $_key['query'] = isset($_key['query']) ? query_normalize($_key['query']) : '';
127 $_key['fragment'] = isset($_key['fragment']) ? strtolower($_key['fragment']) : '';
130 foreach (array_keys($pickups) as $key) {
131 $_key = & $pickups[$key];
132 $_key['scheme'] = isset($_key['scheme']) ? scheme_normalize($_key['scheme']) : '';
133 $_key['host'] = isset($_key['host']) ? strtolower($_key['host']) : '';
134 $_key['port'] = isset($_key['port']) ? port_normalize($_key['port'], $_key['scheme'], FALSE) : '';
135 $_key['path'] = isset($_key['path']) ? path_normalize($_key['path']) : '';
142 // An URI array => An URI (See uri_pickup())
144 // $pickups = uri_pickup('a string include some URIs');
146 // foreach (array_keys($pickups) as $key) {
147 // $uris[$key] = uri_pickup_implode($pickups[$key]);
149 function uri_pickup_implode($uri = array())
151 if (empty($uri) || ! is_array($uri)) return NULL;
154 if (isset($uri['scheme']) && $uri['scheme'] !== '') {
155 $tmp[] = & $uri['scheme'];
158 if (isset($uri['userinfo']) && $uri['userinfo'] !== '') {
159 $tmp[] = & $uri['userinfo'];
162 if (isset($uri['host']) && $uri['host'] !== '') {
163 $tmp[] = & $uri['host'];
165 if (isset($uri['port']) && $uri['port'] !== '') {
167 $tmp[] = & $uri['port'];
169 if (isset($uri['path']) && $uri['path'] !== '') {
170 $tmp[] = & $uri['path'];
172 if (isset($uri['file']) && $uri['file'] !== '') {
173 $tmp[] = & $uri['file'];
175 if (isset($uri['query']) && $uri['query'] !== '') {
177 $tmp[] = & $uri['query'];
179 if (isset($uri['fragment']) && $uri['fragment'] !== '') {
181 $tmp[] = & $uri['fragment'];
184 return implode('', $tmp);
187 // $array['something'] => $array['wanted']
188 function array_rename_keys(& $array, $keys = array('from' => 'to'), $force = FALSE, $default = '')
190 if (! is_array($array) || ! is_array($keys)) return FALSE;
192 // Nondestructive test
194 foreach(array_keys($keys) as $from)
195 if (! isset($array[$from]))
198 foreach($keys as $from => $to) {
199 if ($from === $to) continue;
200 if (! $force || isset($array[$from])) {
201 $array[$to] = & $array[$from];
202 unset($array[$from]);
204 $array[$to] = $default;
211 // ---------------------
214 // Pickup all of markup areas
215 function area_pickup($string = '', $method = array())
218 if (empty($method)) return $area;
220 // Anchor tag pair by preg_match and preg_match_all()
222 // [OK] <a href= >Good site!</a>
223 // [OK] <a href= "#" >test</a>
224 // [OK] <a href="http://nasty.example.com">visit http://nasty.example.com/</a>
225 // [OK] <a href=\'http://nasty.example.com/\' >discount foobar</a>
226 // [NG] <a href="http://ng.example.com">visit http://ng.example.com _not_ended_
227 $regex = '#<a\b[^>]*\bhref\b[^>]*>.*?</a\b[^>]*(>)#i';
228 if (isset($method['area_anchor'])) {
230 $count = isset($method['asap']) ?
231 preg_match($regex, $string) :
232 preg_match_all($regex, $string, $areas);
233 if (! empty($count)) $area['area_anchor'] = $count;
235 if (isset($method['uri_anchor'])) {
237 preg_match_all($regex, $string, $areas, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
238 foreach(array_keys($areas) as $_area) {
239 $areas[$_area] = array(
240 $areas[$_area][0][1], // Area start (<a href>)
241 $areas[$_area][1][1], // Area end (</a>)
244 if (! empty($areas)) $area['uri_anchor'] = $areas;
247 // phpBB's "BBCode" pair by preg_match and preg_match_all()
249 // [OK] [url]http://nasty.example.com/[/url]
250 // [OK] [link]http://nasty.example.com/[/link]
251 // [OK] [url=http://nasty.example.com]visit http://nasty.example.com/[/url]
252 // [OK] [link http://nasty.example.com/]buy something[/link]
253 $regex = '#\[(url|link)\b[^\]]*\].*?\[/\1\b[^\]]*(\])#i';
254 if (isset($method['area_bbcode'])) {
256 $count = isset($method['asap']) ?
257 preg_match($regex, $string) :
258 preg_match_all($regex, $string, $areas, PREG_SET_ORDER);
259 if (! empty($count)) $area['area_bbcode'] = $count;
261 if (isset($method['uri_bbcode'])) {
263 preg_match_all($regex, $string, $areas, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
264 foreach(array_keys($areas) as $_area) {
265 $areas[$_area] = array(
266 $areas[$_area][0][1], // Area start ([url])
267 $areas[$_area][2][1], // Area end ([/url])
270 if (! empty($areas)) $area['uri_bbcode'] = $areas;
273 // Various Wiki syntax
274 // [text_or_uri>text_or_uri]
275 // [text_or_uri:text_or_uri]
276 // [text_or_uri|text_or_uri]
277 // [text_or_uri->text_or_uri]
278 // [text_or_uri text_or_uri] // MediaWiki
279 // MediaWiki: [http://nasty.example.com/ visit http://nasty.example.com/]
284 // If in doubt, it's a little doubtful
285 // if (Area => inside <= Area) $brief += -1
286 function area_measure($areas, & $array, $belief = -1, $a_key = 'area', $o_key = 'offset')
288 if (! is_array($areas) || ! is_array($array)) return;
290 $areas_keys = array_keys($areas);
291 foreach(array_keys($array) as $u_index) {
292 $offset = isset($array[$u_index][$o_key]) ?
293 intval($array[$u_index][$o_key]) : 0;
294 foreach($areas_keys as $a_index) {
295 if (isset($array[$u_index][$a_key])) {
296 $offset_s = intval($areas[$a_index][0]);
297 $offset_e = intval($areas[$a_index][1]);
298 // [Area => inside <= Area]
299 if ($offset_s < $offset && $offset < $offset_e) {
300 $array[$u_index][$a_key] += $belief;
307 // ---------------------
310 // Domain exposure callback (See spam_uri_pickup_preprocess())
311 // http://victim.example.org/?foo+site:nasty.example.com+bar
312 // => http://nasty.example.com/?refer=victim.example.org
313 // NOTE: 'refer=' is not so good for (at this time).
314 // Consider about using IP address of the victim, try to avoid that.
315 function _preg_replace_callback_domain_exposure($matches = array())
319 // Preserve the victim URI as a complicity or ...
320 if (isset($matches[5])) {
322 $matches[1] . '://' . // scheme
323 $matches[2] . '/' . // victim.example.org
324 $matches[3]; // The rest of all (before victim)
328 if (isset($matches[4])) {
330 $matches[1] . '://' . // scheme
331 $matches[4] . // nasty.example.com
332 '/?refer=' . strtolower($matches[2]) . // victim.example.org
339 // Preprocess: rawurldecode() and adding space(s) and something
340 // to detect/count some URIs _if possible_
341 // NOTE: It's maybe danger to var_dump(result). [e.g. 'javascript:']
342 // [OK] http://victim.example.org/go?http%3A%2F%2Fnasty.example.org
343 // [OK] http://victim.example.org/http://nasty.example.org
344 // TODO: link.toolbot.com, urlx.org
345 function spam_uri_pickup_preprocess($string = '')
347 if (! is_string($string)) return '';
349 $string = rawurldecode($string);
351 // Domain exposure (See _preg_replace_callback_domain_exposure())
352 $string = preg_replace_callback(
356 // Something Google: http://www.google.com/supported_domains
357 '(?:[a-z0-9.]+\.)?google\.[a-z]{2,3}(?:\.[a-z]{2})?' .
360 '(?:[a-z0-9.]+\.)?altavista.com' .
364 '([a-z0-9?=&.%_/\'\\\+-]+)' . // path/?query=foo+bar+
365 '\bsite:([a-z0-9.%_-]+\.[a-z0-9.%_-]+)' . // site:nasty.example.com
366 //'()' . // Preserve or remove?
369 '_preg_replace_callback_domain_exposure',
373 // URI exposure (uriuri => uri uri)
374 $string = preg_replace(
376 '#(?<! )(?:https?|ftp):/#i',
377 // '#[a-z][a-z0-9.+-]{1,8}://#i',
378 // '#[a-z][a-z0-9.+-]{1,8}://#i'
387 // Main function of spam-uri pickup,
388 // A wrapper function of uri_pickup()
389 function spam_uri_pickup($string = '', $method = array())
391 if (! is_array($method) || empty($method)) {
392 $method = check_uri_spam_method();
395 $string = spam_uri_pickup_preprocess($string);
397 $array = uri_pickup($string);
399 // Area elevation of URIs, for '(especially external)link' intension
400 if (! empty($array)) {
402 if (isset($method['uri_anchor'])) $_method['uri_anchor'] = & $method['uri_anchor'];
403 if (isset($method['uri_bbcode'])) $_method['uri_bbcode'] = & $method['uri_bbcode'];
404 $areas = area_pickup($string, $_method, TRUE);
405 if (! empty($areas)) {
406 $area_shadow = array();
407 foreach (array_keys($array) as $key) {
408 $area_shadow[$key] = & $array[$key]['area'];
409 foreach (array_keys($_method) as $_key) {
410 $area_shadow[$key][$_key] = 0;
413 foreach (array_keys($_method) as $_key) {
414 if (isset($areas[$_key])) {
415 area_measure($areas[$_key], $area_shadow, 1, $_key);
421 // Remove 'offset's for area_measure()
422 foreach(array_keys($array) as $key)
423 unset($array[$key]['area']['offset']);
429 // ---------------------
432 // Scheme normalization: Renaming the schemes
433 // snntp://example.org => nntps://example.org
434 // NOTE: Keep the static lists simple. See also port_normalize().
435 function scheme_normalize($scheme = '', $abbrevs_harmfull = TRUE)
437 // Abbreviations they have no intention of link
438 static $abbrevs = array(
443 // Aliases => normalized ones
444 static $aliases = array(
454 if (! is_string($scheme)) return '';
456 $scheme = strtolower($scheme);
457 if (isset($abbrevs[$scheme])) {
458 $scheme = $abbrevs_harmfull ? $abbrevs[$scheme] : '';
460 if (isset($aliases[$scheme])) {
461 $scheme = $aliases[$scheme];
467 // Hostname normlization (Destructive)
468 // www.foo => www.foo ('foo' seems TLD)
469 // www.foo.bar => foo.bar
470 // www.10.20 => www.10.20 (Invalid hostname)
472 // 'www' is mostly used as traditional hostname of WWW server.
473 // 'www.foo.bar' may be identical with 'foo.bar'.
474 function host_normalize($host = '')
476 if (! is_string($host)) return '';
478 $host = strtolower($host);
480 if (preg_match('/^www\.(.+\.[a-z]+)$/', $host, $matches)) {
487 // Port normalization: Suppress the (redundant) default port
488 // HTTP://example.org:80/ => http://example.org/
489 // HTTP://example.org:8080/ => http://example.org:8080/
490 // HTTPS://example.org:443/ => https://example.org/
491 function port_normalize($port, $scheme, $scheme_normalize = FALSE)
493 // Schemes that users _maybe_ want to add protocol-handlers
494 // to their web browsers. (and attackers _maybe_ want to use ...)
495 // Reference: http://www.iana.org/assignments/port-numbers
496 static $array = array(
497 // scheme => default port
523 // intval() converts '0-1' to '0', so preg_match() rejects these invalid ones
524 if (! is_numeric($port) || $port < 0 || preg_match('/[^0-9]/i', $port))
527 $port = intval($port);
528 if ($scheme_normalize) $scheme = scheme_normalize($scheme);
529 if (isset($array[$scheme]) && $port == $array[$scheme])
530 $port = ''; // Ignore the defaults
535 // Path normalization
536 // http://example.org => http://example.org/
537 // http://example.org#hoge => http://example.org/#hoge
538 // http://example.org/path/a/b/./c////./d => http://example.org/path/a/b/c/d
539 // http://example.org/path/../../a/../back => http://example.org/back
540 function path_normalize($path = '', $divider = '/', $add_root = TRUE)
542 if (! is_string($divider)) return is_string($path) ? $path : '';
545 $first_div = & $divider;
549 if (! is_string($path) || $path == '') return $first_div;
551 if (strpos($path, $divider, strlen($path) - strlen($divider)) === FALSE) {
554 $last_div = & $divider;
557 $array = explode($divider, $path);
559 // Remove paddings ('//' and '/./')
560 foreach(array_keys($array) as $key) {
561 if ($array[$key] == '' || $array[$key] == '.') {
566 // Remove back-tracks ('/../')
568 foreach($array as $value) {
569 if ($value == '..') {
572 array_push($tmp, $value);
580 return $first_div . implode($divider, $array) . $last_div;
584 // DirectoryIndex normalize (Destructive and rough)
585 // TODO: sample.en.ja.html.gz => sample.html
586 function file_normalize($file = 'index.html.en')
588 static $simple_defaults = array(
589 'default.htm' => TRUE,
590 'default.html' => TRUE,
591 'default.asp' => TRUE,
592 'default.aspx' => TRUE,
593 'index' => TRUE, // Some system can omit the suffix
596 static $content_suffix = array(
597 // index.xxx, sample.xxx
612 static $language_suffix = array(
613 // Reference: Apache 2.0.59 'AddLanguage' default
642 // Reference: Apache 2.0.59 default 'index.html' variants
648 static $charset_suffix = array(
649 // Reference: Apache 2.0.59 'AddCharset' default
650 'iso8859-1' => TRUE, // ISO-8859-1
651 'latin1' => TRUE, // ISO-8859-1
652 'iso8859-2' => TRUE, // ISO-8859-2
653 'latin2' => TRUE, // ISO-8859-2
654 'cen' => TRUE, // ISO-8859-2
655 'iso8859-3' => TRUE, // ISO-8859-3
656 'latin3' => TRUE, // ISO-8859-3
657 'iso8859-4' => TRUE, // ISO-8859-4
658 'latin4' => TRUE, // ISO-8859-4
659 'iso8859-5' => TRUE, // ISO-8859-5
660 'latin5' => TRUE, // ISO-8859-5
661 'cyr' => TRUE, // ISO-8859-5
662 'iso-ru' => TRUE, // ISO-8859-5
663 'iso8859-6' => TRUE, // ISO-8859-6
664 'latin6' => TRUE, // ISO-8859-6
665 'arb' => TRUE, // ISO-8859-6
666 'iso8859-7' => TRUE, // ISO-8859-7
667 'latin7' => TRUE, // ISO-8859-7
668 'grk' => TRUE, // ISO-8859-7
669 'iso8859-8' => TRUE, // ISO-8859-8
670 'latin8' => TRUE, // ISO-8859-8
671 'heb' => TRUE, // ISO-8859-8
672 'iso8859-9' => TRUE, // ISO-8859-9
673 'latin9' => TRUE, // ISO-8859-9
674 'trk' => TRUE, // ISO-8859-9
675 'iso2022-jp'=> TRUE, // ISO-2022-JP
676 'jis' => TRUE, // ISO-2022-JP
677 'iso2022-kr'=> TRUE, // ISO-2022-KR
678 'kis' => TRUE, // ISO-2022-KR
679 'iso2022-cn'=> TRUE, // ISO-2022-CN
680 'cis' => TRUE, // ISO-2022-CN
682 'cp-1251' => TRUE, // ru, WINDOWS-1251
683 'win-1251' => TRUE, // ru, WINDOWS-1251
684 'cp866' => TRUE, // ru
685 'koi8-r' => TRUE, // ru, KOI8-r
686 'koi8-ru' => TRUE, // ru, KOI8-r
687 'koi8-uk' => TRUE, // ru, KOI8-ru
688 'ua' => TRUE, // ru, KOI8-ru
689 'ucs2' => TRUE, // ru, ISO-10646-UCS-2
690 'ucs4' => TRUE, // ru, ISO-10646-UCS-4
693 // Reference: Apache 2.0.59 default 'index.html' variants
698 // May uncompress by web browsers on the fly
699 // Must be at the last of the filename
700 // Reference: Apache 2.0.59 'AddEncoding'
701 static $encoding_suffix = array(
706 if (! is_string($file)) return '';
707 $_file = strtolower($file);
708 if (isset($simple_defaults[$_file])) return '';
711 // Roughly removing language/character-set/encoding suffixes
713 // * Apache 2 document about 'Content-negotiaton', 'mod_mime' and 'mod_negotiation'
714 // http://httpd.apache.org/docs/2.0/content-negotiation.html
715 // http://httpd.apache.org/docs/2.0/mod/mod_mime.html
716 // http://httpd.apache.org/docs/2.0/mod/mod_negotiation.html
717 // * http://www.iana.org/assignments/character-sets
718 // * RFC3066: Tags for the Identification of Languages
719 // http://www.ietf.org/rfc/rfc3066.txt
720 // * ISO 639: codes of 'language names'
721 $suffixes = explode('.', $_file);
722 $body = array_shift($suffixes);
724 // Remove the last .gz/.z
725 $last_key = end(array_keys($suffixes));
726 if (isset($encoding_suffix[$suffixes[$last_key]])) {
727 unset($suffixes[$last_key]);
730 // Cut language and charset suffixes
731 foreach($suffixes as $key => $value){
732 if (isset($language_suffix[$value]) || isset($charset_suffix[$value])) {
733 unset($suffixes[$key]);
736 if (empty($suffixes)) return $body;
739 $count = count($suffixes);
741 $current = current($suffixes);
742 if ($body == 'index' && $count == 1 && isset($content_suffix[$current])) return '';
747 // Sort query-strings if possible (Destructive and rough)
748 // [OK] &&&&f=d&b&d&c&a=0dd => a=0dd&b&c&d&f=d
749 // [OK] nothing==&eg=dummy&eg=padding&eg=foobar => eg=foobar
750 function query_normalize($string = '', $equal = TRUE, $equal_cutempty = TRUE, $stortolower = TRUE)
752 if (! is_string($string)) return '';
753 if ($stortolower) $string = strtolower($string);
755 $array = explode('&', $string);
757 // Remove '&' paddings
758 foreach(array_keys($array) as $key) {
759 if ($array[$key] == '') {
764 // Consider '='-sepalated input and paddings
766 $equals = $not_equals = array();
767 foreach ($array as $part) {
768 if (strpos($part, '=') === FALSE) {
769 $not_equals[] = $part;
771 list($key, $value) = explode('=', $part, 2);
772 $value = ltrim($value, '=');
773 if (! $equal_cutempty || $value != '') {
774 $equals[$key] = $value;
779 $array = & $not_equals;
780 foreach ($equals as $key => $value) {
781 $array[] = $key . '=' . $value;
787 return implode('&', $array);
790 // ---------------------
791 // Part One : Checker
793 // Rough implementation of globbing
795 // USAGE: $regex = '/^' . generate_glob_regex('*.txt', '/') . '$/i';
797 function generate_glob_regex($string = '', $divider = '/')
799 static $from = array(
802 // 22 => '[', // Maybe cause regex compilation error (e.g. '[]')
818 if (! is_string($string)) return '';
820 $string = str_replace($from, $mid, $string); // Hide
821 $string = preg_quote($string, $divider);
822 $string = str_replace($mid, $to, $string); // Unhide
827 // Rough hostname checker
829 // TODO: Strict digit, 0x, CIDR, IPv6
830 function is_ip($string = '')
832 if (preg_match('/^' .
833 '(?:[0-9]{1,3}\.){3}[0-9]{1,3}' . '|' .
834 '(?:[0-9]{1,3}\.){1,3}' . '$/',
836 return 4; // Seems IPv4(dot-decimal)
838 return 0; // Seems not IP
842 // Generate host (FQDN, IPv4, ...) regex
843 // 'localhost' : Matches with 'localhost' only
844 // 'example.org' : Matches with 'example.org' only (See host_normalize() about 'www')
845 // '.example.org' : Matches with ALL FQDN ended with '.example.org'
846 // '*.example.org' : Almost the same of '.example.org' except 'www.example.org'
847 // '10.20.30.40' : Matches with IPv4 address '10.20.30.40' only
848 // [TODO] '192.' : Matches with all IPv4 hosts started with '192.'
849 // TODO: IPv4, CIDR?, IPv6
850 function generate_host_regex($string = '', $divider = '/')
852 if (! is_string($string)) return '';
854 if (mb_strpos($string, '.') === FALSE)
855 return generate_glob_regex($string, $divider);
858 if (is_ip($string)) {
860 return generate_glob_regex($string, $divider);
863 $part = explode('.', $string, 2);
864 if ($part[0] == '') {
865 $part[0] = '(?:.*\.)?'; // And all related FQDN
866 } else if ($part[0] == '*') {
867 $part[0] = '.*\.'; // All subdomains/hosts only
869 return generate_glob_regex($string, $divider);
871 $part[1] = generate_glob_regex($part[1], $divider);
872 return implode('', $part);
876 function get_blocklist($list = '')
880 if (! isset($regexs)) {
882 if (file_exists(SPAM_INI_FILE)) {
883 $blocklist = array();
884 include(SPAM_INI_FILE);
885 // $blocklist['badhost'] = array(
886 // '*.blogspot.com', // Blog services's subdomains (only)
887 // 'IANA-examples' => '#^(?:.*\.)?example\.(?:com|net|org)$#',
889 if (isset($blocklist['list'])) {
890 $regexs['list'] = & $blocklist['list'];
893 $blocklist['list'] = array(
898 foreach(array_keys($blocklist['list']) as $_list) {
899 if (! isset($blocklist[$_list])) continue;
900 foreach ($blocklist[$_list] as $key => $value) {
901 if (is_array($value)) {
902 $regexs[$_list][$key] = array();
903 foreach($value as $_key => $_value) {
904 get_blocklist_add($regexs[$_list][$key], $_key, $_value);
907 get_blocklist_add($regexs[$_list], $key, $value);
910 unset($blocklist[$_list]);
916 return $regexs; // ALL
917 } else if (isset($regexs[$list])) {
918 return $regexs[$list];
924 // Subroutine of get_blocklist()
925 function get_blocklist_add(& $array, $key = 0, $value = '*.example.org')
927 if (is_string($key)) {
928 $array[$key] = & $value; // Treat $value as a regex
930 $array[$value] = '/^' . generate_host_regex($value, '/') . '$/i';
935 // Blocklist metrics: Separate $host, to $blocked and not blocked
936 function blocklist_distiller(& $hosts, $keys = array('goodhost', 'badhost'), $asap = FALSE)
938 if (! is_array($hosts)) $hosts = array($hosts);
939 if (! is_array($keys)) $keys = array($keys);
941 $list = get_blocklist('list');
944 foreach($keys as $key){
945 foreach (get_blocklist($key) as $label => $regex) {
946 if (is_array($regex)) {
947 foreach($regex as $_label => $_regex) {
948 $group = preg_grep($_regex, $hosts);
950 $hosts = array_diff($hosts, $group);
951 $blocked[$key][$label][$_label] = $group;
952 if ($asap && $list[$key]) break;
956 $group = preg_grep($regex, $hosts);
958 $hosts = array_diff($hosts, $group);
959 $blocked[$key][$label] = $group;
960 if ($asap && $list[$key]) break;
969 function is_badhost($hosts = array(), $asap = TRUE, & $remains)
973 if (! is_array($hosts)) $hosts = array($hosts);
974 foreach(array_keys($hosts) as $key) {
975 if (! is_string($hosts[$key])) {
979 if (empty($hosts)) return $result;
981 $list = get_blocklist('list');
982 $blocked = blocklist_distiller($hosts, array_keys($list), $asap);
983 foreach($list as $key=>$type){
985 unset($blocked[$key]); // Ignore goodhost etc
994 // Default (enabled) methods and thresholds (for content insertion)
995 function check_uri_spam_method($times = 1, $t_area = 0, $rule = TRUE)
997 $times = intval($times);
998 $t_area = intval($t_area);
1002 'quantity' => 8 * $times, // Allow N URIs
1003 'non_uniqhost' => 3 * $times, // Allow N duped (and normalized) Hosts
1004 //'non_uniquri'=> 3 * $times, // Allow N duped (and normalized) URIs
1007 'area_anchor' => $t_area, // Using <a href> HTML tag
1008 'area_bbcode' => $t_area, // Using [url] or [link] BBCode
1009 //'uri_anchor' => $t_area, // URI inside <a href> HTML tag
1010 //'uri_bbcode' => $t_area, // URI inside [url] or [link] BBCode
1015 //'asap' => TRUE, // Quit or return As Soon As Possible
1016 'uniqhost' => TRUE, // Show uniq host (at block notification mail)
1017 'badhost' => TRUE, // Check badhost
1023 // Remove non-$positive values
1024 foreach (array_keys($positive) as $key) {
1025 if ($positive[$key] < 0) unset($positive[$key]);
1028 return $positive + $bool;
1031 // Simple/fast spam check
1032 function check_uri_spam($target = '', $method = array())
1034 if (! is_array($method) || empty($method)) {
1035 $method = check_uri_spam_method();
1049 'is_spam' => array(),
1050 'method' => & $method,
1051 'remains' => array(),
1054 $sum = & $progress['sum'];
1055 $is_spam = & $progress['is_spam'];
1056 $remains = & $progress['remains'];
1057 $error = & $progress['error'];
1058 $asap = isset($method['asap']);
1061 if (is_array($target)) {
1062 foreach($target as $str) {
1064 $_progress = check_uri_spam($str, $method);
1065 $_sum = & $_progress['sum'];
1066 $_is_spam = & $_progress['is_spam'];
1067 $_remains = & $_progress['remains'];
1068 $_error = & $_progress['error'];
1069 foreach (array_keys($_sum) as $key) {
1070 $sum[$key] += $_sum[$key];
1072 foreach (array_keys($_is_spam) as $key) {
1073 if (is_array($_is_spam[$key])) {
1074 // Marge keys (badhost)
1075 foreach(array_keys($_is_spam[$key]) as $_key) {
1076 if (! isset($is_spam[$key][$_key])) {
1077 $is_spam[$key][$_key] = $_is_spam[$key][$_key];
1079 $is_spam[$key][$_key] += $_is_spam[$key][$_key];
1083 $is_spam[$key] = TRUE;
1086 foreach ($_remains as $key=>$value) {
1087 foreach ($value as $_key=>$_value) {
1088 if (is_int($_key)) {
1089 $remains[$key][] = $_value;
1091 $remains[$key][$_key] = $_value;
1095 if (! empty($_error)) $error += $_error;
1096 if ($asap && $is_spam) break;
1101 // Area: There's HTML anchor tag
1102 if ((! $asap || ! $is_spam) && isset($method['area_anchor'])) {
1103 $key = 'area_anchor';
1104 $_asap = isset($method['asap']) ? array('asap' => TRUE) : array();
1105 $result = area_pickup($target, array($key => TRUE) + $_asap);
1107 $sum[$key] = $result[$key];
1108 if (isset($method[$key]) && $sum[$key] > $method[$key]) {
1109 $is_spam[$key] = TRUE;
1114 // Area: There's 'BBCode' linking tag
1115 if ((! $asap || ! $is_spam) && isset($method['area_bbcode'])) {
1116 $key = 'area_bbcode';
1117 $_asap = isset($method['asap']) ? array('asap' => TRUE) : array();
1118 $result = area_pickup($target, array($key => TRUE) + $_asap);
1120 $sum[$key] = $result[$key];
1121 if (isset($method[$key]) && $sum[$key] > $method[$key]) {
1122 $is_spam[$key] = TRUE;
1128 if ($asap && $is_spam) return $progress;
1131 $pickups = uri_pickup_normalize(spam_uri_pickup($target, $method));
1132 //$remains['uri_pickup'] = & $pickups;
1135 if (empty($pickups)) return $progress;
1137 // URI: Check quantity
1138 $sum['quantity'] += count($pickups);
1140 if ((! $asap || ! $is_spam) && isset($method['quantity']) &&
1141 $sum['quantity'] > $method['quantity']) {
1142 $is_spam['quantity'] = TRUE;
1145 // URI: used inside HTML anchor tag pair
1146 if ((! $asap || ! $is_spam) && isset($method['uri_anchor'])) {
1147 $key = 'uri_anchor';
1148 foreach($pickups as $pickup) {
1149 if (isset($pickup['area'][$key])) {
1150 $sum[$key] += $pickup['area'][$key];
1151 if(isset($method[$key]) &&
1152 $sum[$key] > $method[$key]) {
1153 $is_spam[$key] = TRUE;
1154 if ($asap && $is_spam) break;
1156 if ($asap && $is_spam) break;
1161 // URI: used inside 'BBCode' pair
1162 if ((! $asap || ! $is_spam) && isset($method['uri_bbcode'])) {
1163 $key = 'uri_bbcode';
1164 foreach($pickups as $pickup) {
1165 if (isset($pickup['area'][$key])) {
1166 $sum[$key] += $pickup['area'][$key];
1167 if(isset($method[$key]) &&
1168 $sum[$key] > $method[$key]) {
1169 $is_spam[$key] = TRUE;
1170 if ($asap && $is_spam) break;
1172 if ($asap && $is_spam) break;
1177 // URI: Uniqueness (and removing non-uniques)
1178 if ((! $asap || ! $is_spam) && isset($method['non_uniquri'])) {
1181 foreach (array_keys($pickups) as $key) {
1182 $uris[$key] = uri_pickup_implode($pickups[$key]);
1184 $count = count($uris);
1185 $uris = array_unique($uris);
1186 $sum['non_uniquri'] += $count - count($uris);
1187 if ($sum['non_uniquri'] > $method['non_uniquri']) {
1188 $is_spam['non_uniquri'] = TRUE;
1190 if (! $asap || ! $is_spam) {
1191 foreach (array_diff(array_keys($pickups),
1192 array_keys($uris)) as $remove) {
1193 unset($pickups[$remove]);
1200 if ($asap && $is_spam) return $progress;
1202 // Host: Uniqueness (uniq / non-uniq)
1204 foreach ($pickups as $pickup) $hosts[] = & $pickup['host'];
1205 $hosts = array_unique($hosts);
1206 //$remains['uniqhost'] = & $hosts;
1207 $sum['uniqhost'] += count($hosts);
1208 if ((! $asap || ! $is_spam) && isset($method['non_uniqhost'])) {
1209 $sum['non_uniqhost'] = $sum['quantity'] - $sum['uniqhost'];
1210 if ($sum['non_uniqhost'] > $method['non_uniqhost']) {
1211 $is_spam['non_uniqhost'] = TRUE;
1216 if ($asap && $is_spam) return $progress;
1219 if ((! $asap || ! $is_spam) && isset($method['badhost'])) {
1220 $__remains = array();
1221 $badhost = is_badhost($hosts, $asap, $__remains);
1224 $remains['badhost'] = array();
1225 foreach ($__remains as $value) {
1226 $remains['badhost'][$value] = TRUE;
1231 if (! empty($badhost)) {
1233 //var_dump($badhost); // BADHOST detail
1235 $sum['badhost'] += array_count_leaves($badhost);
1236 foreach(array_keys($badhost) as $keys) {
1237 $is_spam['badhost'][$keys] =
1238 array_count_leaves($badhost[$keys]);
1247 // Count leaves (A leaf = value that is not an array, or an empty array)
1248 function array_count_leaves($array = array(), $count_empty = FALSE)
1250 if (! is_array($array) || (empty($array) && $count_empty)) return 1;
1254 foreach ($array as $part) {
1255 $count += array_count_leaves($part, $count_empty);
1260 // ---------------------
1263 // TODO: Don't show unused $method!
1264 // Summarize $progress (blocked only)
1265 function summarize_spam_progress($progress = array(), $blockedonly = FALSE)
1268 $tmp = array_keys($progress['is_spam']);
1271 $method = & $progress['method'];
1272 if (isset($progress['sum'])) {
1273 foreach ($progress['sum'] as $key => $value) {
1274 if (isset($method[$key])) {
1275 $tmp[] = $key . '(' . $value . ')';
1281 return implode(', ', $tmp);
1284 // ---------------------
1287 // Common bahavior for blocking
1288 // NOTE: Call this function from various blocking feature, to disgueise the reason 'why blocked'
1289 function spam_exit($mode = '', $data = array())
1292 case '': echo("\n"); break;
1294 echo('<pre>' . "\n");
1295 echo htmlspecialchars(var_export($data, TRUE));
1296 echo('</pre>' . "\n");
1305 // ---------------------
1308 // TODO: Record them
1309 // Simple/fast spam filter ($target: 'a string' or an array())
1310 function pkwk_spamfilter($action, $page, $target = array('title' => ''), $method = array(), $exitmode = '')
1312 $progress = check_uri_spam($target, $method);
1314 if (! empty($progress['is_spam'])) {
1315 // Mail to administrator(s)
1316 pkwk_spamnotify($action, $page, $target, $progress, $method);
1319 spam_exit($exitmode, $progress);
1323 // ---------------------
1324 // PukiWiki original
1326 // Mail to administrator(s)
1327 function pkwk_spamnotify($action, $page, $target = array('title' => ''), $progress = array(), $method = array())
1329 global $notify, $notify_subject;
1331 if (! $notify) return;
1333 $asap = isset($method['asap']);
1335 $summary['ACTION'] = 'Blocked by: ' . summarize_spam_progress($progress, TRUE);
1337 $summary['METRICS'] = summarize_spam_progress($progress);
1339 if (isset($progress['is_spam']['badhost'])) {
1341 foreach($progress['is_spam']['badhost'] as $glob=>$number) {
1342 $badhost[] = $glob . '(' . $number . ')';
1344 $summary['DETAIL_BADHOST'] = implode(', ', $badhost);
1346 if (! $asap && $progress['remains']['badhost']) {
1347 $count = count($progress['remains']['badhost']);
1348 $summary['DETAIL_NEUTRAL_HOST'] = $count .
1351 '/[^, a-z0-9.-]/i', '',
1352 implode(', ', array_keys($progress['remains']['badhost']))
1356 $summary['COMMENT'] = $action;
1357 $summary['PAGE'] = '[blocked] ' . (is_pagename($page) ? $page : '');
1358 $summary['URI'] = get_script_uri() . '?' . rawurlencode($page);
1359 $summary['USER_AGENT'] = TRUE;
1360 $summary['REMOTE_ADDR'] = TRUE;
1361 pkwk_mail_notify($notify_subject, var_export($target, TRUE), $summary, TRUE);