2 // $Id: spam.php,v 1.141 2007/05/02 10:01:19 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 // Roughly strings(1) using PCRE
41 // This function is useful to:
42 // * Reduce the size of data, from removing unprintable binary data
43 // * Detect _bare_strings_ from binary data
45 // http://www.freebsd.org/cgi/man.cgi?query=strings (Man-page of GNU strings)
46 // http://www.pcre.org/pcre.txt
47 function strings($binary = '', $min_len = 4, $ignore_space = FALSE)
50 $binary = preg_replace(
52 '/(?:[^[:graph:] \t\n]|[\r])+/s',
65 $binary = preg_replace('/(?:[^[:graph:][:space:]]|[\r])+/s', "\n", $binary);
69 $min_len = min(1024, intval($min_len));
72 preg_grep('/^.{' . $min_len . ',}/S',
73 explode("\n", $binary)
82 // ---------------------
85 // Return an array of URIs in the $string
86 // [OK] http://nasty.example.org#nasty_string
87 // [OK] http://nasty.example.org:80/foo/xxx#nasty_string/bar
88 // [OK] ftp://nasty.example.org:80/dfsdfs
89 // [OK] ftp://cnn.example.com&story=breaking_news@10.0.0.1/top_story.htm (from RFC3986)
90 function uri_pickup($string = '')
92 if (! is_string($string)) return array();
94 // Not available for: IDN(ignored)
97 // scheme://userinfo@host:port/path/or/pathinfo/maybefile.and?query=string#fragment
98 // Refer RFC3986 (Regex below is not strict)
99 '#(\b[a-z][a-z0-9.+-]{1,8}):/+' . // 1: Scheme
101 '([^\s<>"\'\[\]/\#?@]*)' . // 2: Userinfo (Username)
105 '\[[0-9a-f:.]+\]' . '|' . // IPv6([colon-hex and dot]): RFC2732
106 '(?:[0-9]{1,3}\.){3}[0-9]{1,3}' . '|' . // IPv4(dot-decimal): 001.22.3.44
107 '[a-z0-9.-]+' . // hostname(FQDN) : foo.example.org
109 '(?::([0-9]*))?' . // 4: Port
110 '((?:/+[^\s<>"\'\[\]/\#]+)*/+)?' . // 5: Directory path or path-info
111 '([^\s<>"\'\[\]\#?]+)?' . // 6: File?
112 '(?:\?([^\s<>"\'\[\]\#]+))?' . // 7: Query string
113 '(?:\#([a-z0-9._~%!$&\'()*+,;=:@-]*))?' . // 8: Fragment
115 $string, $array, PREG_SET_ORDER | PREG_OFFSET_CAPTURE
119 static $parts = array(
120 1 => 'scheme', 2 => 'userinfo', 3 => 'host', 4 => 'port',
121 5 => 'path', 6 => 'file', 7 => 'query', 8 => 'fragment'
123 $default = array('');
124 foreach(array_keys($array) as $uri) {
125 $_uri = & $array[$uri];
126 array_rename_keys($_uri, $parts, TRUE, $default);
127 $offset = $_uri['scheme'][1]; // Scheme's offset = URI's offset
128 foreach(array_keys($_uri) as $part) {
129 $_uri[$part] = & $_uri[$part][0]; // Remove offsets
133 foreach(array_keys($array) as $uri) {
134 $_uri = & $array[$uri];
135 if ($_uri['scheme'] === '') {
136 unset($array[$uri]); // Considererd harmless
139 unset($_uri[0]); // Matched string itself
140 $_uri['area']['offset'] = $offset; // Area offset for area_measure()
146 // Normalize an array of URI arrays
147 // NOTE: Give me the uri_pickup() results
148 function uri_pickup_normalize(& $pickups, $destructive = TRUE)
150 if (! is_array($pickups)) return $pickups;
153 foreach (array_keys($pickups) as $key) {
154 $_key = & $pickups[$key];
155 $_key['scheme'] = isset($_key['scheme']) ? scheme_normalize($_key['scheme']) : '';
156 $_key['host'] = isset($_key['host']) ? host_normalize($_key['host']) : '';
157 $_key['port'] = isset($_key['port']) ? port_normalize($_key['port'], $_key['scheme'], FALSE) : '';
158 $_key['path'] = isset($_key['path']) ? strtolower(path_normalize($_key['path'])) : '';
159 $_key['file'] = isset($_key['file']) ? file_normalize($_key['file']) : '';
160 $_key['query'] = isset($_key['query']) ? query_normalize($_key['query']) : '';
161 $_key['fragment'] = isset($_key['fragment']) ? strtolower($_key['fragment']) : '';
164 foreach (array_keys($pickups) as $key) {
165 $_key = & $pickups[$key];
166 $_key['scheme'] = isset($_key['scheme']) ? scheme_normalize($_key['scheme']) : '';
167 $_key['host'] = isset($_key['host']) ? strtolower($_key['host']) : '';
168 $_key['port'] = isset($_key['port']) ? port_normalize($_key['port'], $_key['scheme'], FALSE) : '';
169 $_key['path'] = isset($_key['path']) ? path_normalize($_key['path']) : '';
176 // An URI array => An URI (See uri_pickup())
178 // $pickups = uri_pickup('a string include some URIs');
180 // foreach (array_keys($pickups) as $key) {
181 // $uris[$key] = uri_pickup_implode($pickups[$key]);
183 function uri_pickup_implode($uri = array())
185 if (empty($uri) || ! is_array($uri)) return NULL;
188 if (isset($uri['scheme']) && $uri['scheme'] !== '') {
189 $tmp[] = & $uri['scheme'];
192 if (isset($uri['userinfo']) && $uri['userinfo'] !== '') {
193 $tmp[] = & $uri['userinfo'];
196 if (isset($uri['host']) && $uri['host'] !== '') {
197 $tmp[] = & $uri['host'];
199 if (isset($uri['port']) && $uri['port'] !== '') {
201 $tmp[] = & $uri['port'];
203 if (isset($uri['path']) && $uri['path'] !== '') {
204 $tmp[] = & $uri['path'];
206 if (isset($uri['file']) && $uri['file'] !== '') {
207 $tmp[] = & $uri['file'];
209 if (isset($uri['query']) && $uri['query'] !== '') {
211 $tmp[] = & $uri['query'];
213 if (isset($uri['fragment']) && $uri['fragment'] !== '') {
215 $tmp[] = & $uri['fragment'];
218 return implode('', $tmp);
221 // $array['something'] => $array['wanted']
222 function array_rename_keys(& $array, $keys = array('from' => 'to'), $force = FALSE, $default = '')
224 if (! is_array($array) || ! is_array($keys)) return FALSE;
226 // Nondestructive test
228 foreach(array_keys($keys) as $from)
229 if (! isset($array[$from]))
232 foreach($keys as $from => $to) {
233 if ($from === $to) continue;
234 if (! $force || isset($array[$from])) {
235 $array[$to] = & $array[$from];
236 unset($array[$from]);
238 $array[$to] = $default;
245 // ---------------------
248 // Pickup all of markup areas
249 function area_pickup($string = '', $method = array())
252 if (empty($method)) return $area;
254 // Anchor tag pair by preg_match and preg_match_all()
256 // [OK] <a href= >Good site!</a>
257 // [OK] <a href= "#" >test</a>
258 // [OK] <a href="http://nasty.example.com">visit http://nasty.example.com/</a>
259 // [OK] <a href=\'http://nasty.example.com/\' >discount foobar</a>
260 // [NG] <a href="http://ng.example.com">visit http://ng.example.com _not_ended_
261 $regex = '#<a\b[^>]*\bhref\b[^>]*>.*?</a\b[^>]*(>)#is';
262 if (isset($method['area_anchor'])) {
264 $count = isset($method['asap']) ?
265 preg_match($regex, $string) :
266 preg_match_all($regex, $string, $areas);
267 if (! empty($count)) $area['area_anchor'] = $count;
269 if (isset($method['uri_anchor'])) {
271 preg_match_all($regex, $string, $areas, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
272 foreach(array_keys($areas) as $_area) {
273 $areas[$_area] = array(
274 $areas[$_area][0][1], // Area start (<a href>)
275 $areas[$_area][1][1], // Area end (</a>)
278 if (! empty($areas)) $area['uri_anchor'] = $areas;
281 // phpBB's "BBCode" pair by preg_match and preg_match_all()
283 // [OK] [url]http://nasty.example.com/[/url]
284 // [OK] [link]http://nasty.example.com/[/link]
285 // [OK] [url=http://nasty.example.com]visit http://nasty.example.com/[/url]
286 // [OK] [link http://nasty.example.com/]buy something[/link]
287 $regex = '#\[(url|link)\b[^\]]*\].*?\[/\1\b[^\]]*(\])#is';
288 if (isset($method['area_bbcode'])) {
290 $count = isset($method['asap']) ?
291 preg_match($regex, $string) :
292 preg_match_all($regex, $string, $areas, PREG_SET_ORDER);
293 if (! empty($count)) $area['area_bbcode'] = $count;
295 if (isset($method['uri_bbcode'])) {
297 preg_match_all($regex, $string, $areas, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
298 foreach(array_keys($areas) as $_area) {
299 $areas[$_area] = array(
300 $areas[$_area][0][1], // Area start ([url])
301 $areas[$_area][2][1], // Area end ([/url])
304 if (! empty($areas)) $area['uri_bbcode'] = $areas;
307 // Various Wiki syntax
308 // [text_or_uri>text_or_uri]
309 // [text_or_uri:text_or_uri]
310 // [text_or_uri|text_or_uri]
311 // [text_or_uri->text_or_uri]
312 // [text_or_uri text_or_uri] // MediaWiki
313 // MediaWiki: [http://nasty.example.com/ visit http://nasty.example.com/]
318 // If in doubt, it's a little doubtful
319 // if (Area => inside <= Area) $brief += -1
320 function area_measure($areas, & $array, $belief = -1, $a_key = 'area', $o_key = 'offset')
322 if (! is_array($areas) || ! is_array($array)) return;
324 $areas_keys = array_keys($areas);
325 foreach(array_keys($array) as $u_index) {
326 $offset = isset($array[$u_index][$o_key]) ?
327 intval($array[$u_index][$o_key]) : 0;
328 foreach($areas_keys as $a_index) {
329 if (isset($array[$u_index][$a_key])) {
330 $offset_s = intval($areas[$a_index][0]);
331 $offset_e = intval($areas[$a_index][1]);
332 // [Area => inside <= Area]
333 if ($offset_s < $offset && $offset < $offset_e) {
334 $array[$u_index][$a_key] += $belief;
341 // ---------------------
344 // Domain exposure callback (See spam_uri_pickup_preprocess())
345 // http://victim.example.org/?foo+site:nasty.example.com+bar
346 // => http://nasty.example.com/?refer=victim.example.org
347 // NOTE: 'refer=' is not so good for (at this time).
348 // Consider about using IP address of the victim, try to avoid that.
349 function _preg_replace_callback_domain_exposure($matches = array())
353 // Preserve the victim URI as a complicity or ...
354 if (isset($matches[5])) {
356 $matches[1] . '://' . // scheme
357 $matches[2] . '/' . // victim.example.org
358 $matches[3]; // The rest of all (before victim)
362 if (isset($matches[4])) {
364 $matches[1] . '://' . // scheme
365 $matches[4] . // nasty.example.com
366 '/?refer=' . strtolower($matches[2]) . // victim.example.org
373 // Preprocess: rawurldecode() and adding space(s) and something
374 // to detect/count some URIs _if possible_
375 // NOTE: It's maybe danger to var_dump(result). [e.g. 'javascript:']
376 // [OK] http://victim.example.org/?site:nasty.example.org
377 // [OK] http://victim.example.org/nasty.example.org
378 // [OK] http://victim.example.org/go?http%3A%2F%2Fnasty.example.org
379 // [OK] http://victim.example.org/http://nasty.example.org
380 function spam_uri_pickup_preprocess($string = '')
382 if (! is_string($string)) return '';
384 $string = rawurldecode($string);
386 // Domain exposure (simple)
387 // http://victim.example.org/nasty.example.org/path#frag
388 // => http://nasty.example.org/?refer=victim.example.org and original
389 $string = preg_replace(
392 'ime\.nu' . '|' . // 2ch.net
393 'ime\.st' . '|' . // 2ch.net
394 'link\.toolbot\.com' . '|' .
397 '/([a-z0-9.%_-]+\.[a-z0-9.%_-]+)#i', // nasty.example.org
398 'http://$2/?refer=$1 $0', // Preserve $0 or remove?
402 // Domain exposure (See _preg_replace_callback_domain_exposure())
403 $string = preg_replace_callback(
407 // Something Google: http://www.google.com/supported_domains
408 '(?:[a-z0-9.]+\.)?google\.[a-z]{2,3}(?:\.[a-z]{2})?' .
411 '(?:[a-z0-9.]+\.)?altavista.com' .
415 '([a-z0-9?=&.%_/\'\\\+-]+)' . // path/?query=foo+bar+
416 '\bsite:([a-z0-9.%_-]+\.[a-z0-9.%_-]+)' . // site:nasty.example.com
417 //'()' . // Preserve or remove?
420 '_preg_replace_callback_domain_exposure',
424 // URI exposure (uriuri => uri uri)
425 $string = preg_replace(
427 '#(?<! )(?:https?|ftp):/#i',
428 // '#[a-z][a-z0-9.+-]{1,8}://#i',
429 // '#[a-z][a-z0-9.+-]{1,8}://#i'
438 // Main function of spam-uri pickup,
439 // A wrapper function of uri_pickup()
440 function spam_uri_pickup($string = '', $method = array())
442 if (! is_array($method) || empty($method)) {
443 $method = check_uri_spam_method();
446 $string = spam_uri_pickup_preprocess($string);
448 $array = uri_pickup($string);
450 // Area elevation of URIs, for '(especially external)link' intension
451 if (! empty($array)) {
453 if (isset($method['uri_anchor'])) $_method['uri_anchor'] = & $method['uri_anchor'];
454 if (isset($method['uri_bbcode'])) $_method['uri_bbcode'] = & $method['uri_bbcode'];
455 $areas = area_pickup($string, $_method, TRUE);
456 if (! empty($areas)) {
457 $area_shadow = array();
458 foreach (array_keys($array) as $key) {
459 $area_shadow[$key] = & $array[$key]['area'];
460 foreach (array_keys($_method) as $_key) {
461 $area_shadow[$key][$_key] = 0;
464 foreach (array_keys($_method) as $_key) {
465 if (isset($areas[$_key])) {
466 area_measure($areas[$_key], $area_shadow, 1, $_key);
472 // Remove 'offset's for area_measure()
473 foreach(array_keys($array) as $key)
474 unset($array[$key]['area']['offset']);
480 // ---------------------
483 // Scheme normalization: Renaming the schemes
484 // snntp://example.org => nntps://example.org
485 // NOTE: Keep the static lists simple. See also port_normalize().
486 function scheme_normalize($scheme = '', $abbrevs_harmfull = TRUE)
488 // Abbreviations they have no intention of link
489 static $abbrevs = array(
494 // Aliases => normalized ones
495 static $aliases = array(
505 if (! is_string($scheme)) return '';
507 $scheme = strtolower($scheme);
508 if (isset($abbrevs[$scheme])) {
509 $scheme = $abbrevs_harmfull ? $abbrevs[$scheme] : '';
511 if (isset($aliases[$scheme])) {
512 $scheme = $aliases[$scheme];
518 // Hostname normlization (Destructive)
519 // www.foo => www.foo ('foo' seems TLD)
520 // www.foo.bar => foo.bar
521 // www.10.20 => www.10.20 (Invalid hostname)
523 // 'www' is mostly used as traditional hostname of WWW server.
524 // 'www.foo.bar' may be identical with 'foo.bar'.
525 function host_normalize($host = '')
527 if (! is_string($host)) return '';
529 $host = strtolower($host);
531 if (preg_match('/^www\.(.+\.[a-z]+)$/', $host, $matches)) {
538 // Port normalization: Suppress the (redundant) default port
539 // HTTP://example.org:80/ => http://example.org/
540 // HTTP://example.org:8080/ => http://example.org:8080/
541 // HTTPS://example.org:443/ => https://example.org/
542 function port_normalize($port, $scheme, $scheme_normalize = FALSE)
544 // Schemes that users _maybe_ want to add protocol-handlers
545 // to their web browsers. (and attackers _maybe_ want to use ...)
546 // Reference: http://www.iana.org/assignments/port-numbers
547 static $array = array(
548 // scheme => default port
574 // intval() converts '0-1' to '0', so preg_match() rejects these invalid ones
575 if (! is_numeric($port) || $port < 0 || preg_match('/[^0-9]/i', $port))
578 $port = intval($port);
579 if ($scheme_normalize) $scheme = scheme_normalize($scheme);
580 if (isset($array[$scheme]) && $port == $array[$scheme])
581 $port = ''; // Ignore the defaults
586 // Path normalization
587 // http://example.org => http://example.org/
588 // http://example.org#hoge => http://example.org/#hoge
589 // http://example.org/path/a/b/./c////./d => http://example.org/path/a/b/c/d
590 // http://example.org/path/../../a/../back => http://example.org/back
591 function path_normalize($path = '', $divider = '/', $add_root = TRUE)
593 if (! is_string($divider)) return is_string($path) ? $path : '';
596 $first_div = & $divider;
600 if (! is_string($path) || $path == '') return $first_div;
602 if (strpos($path, $divider, strlen($path) - strlen($divider)) === FALSE) {
605 $last_div = & $divider;
608 $array = explode($divider, $path);
610 // Remove paddings ('//' and '/./')
611 foreach(array_keys($array) as $key) {
612 if ($array[$key] == '' || $array[$key] == '.') {
617 // Remove back-tracks ('/../')
619 foreach($array as $value) {
620 if ($value == '..') {
623 array_push($tmp, $value);
631 return $first_div . implode($divider, $array) . $last_div;
635 // DirectoryIndex normalize (Destructive and rough)
636 // TODO: sample.en.ja.html.gz => sample.html
637 function file_normalize($file = 'index.html.en')
639 static $simple_defaults = array(
640 'default.htm' => TRUE,
641 'default.html' => TRUE,
642 'default.asp' => TRUE,
643 'default.aspx' => TRUE,
644 'index' => TRUE, // Some system can omit the suffix
647 static $content_suffix = array(
648 // index.xxx, sample.xxx
663 static $language_suffix = array(
664 // Reference: Apache 2.0.59 'AddLanguage' default
693 // Reference: Apache 2.0.59 default 'index.html' variants
699 static $charset_suffix = array(
700 // Reference: Apache 2.0.59 'AddCharset' default
701 'iso8859-1' => TRUE, // ISO-8859-1
702 'latin1' => TRUE, // ISO-8859-1
703 'iso8859-2' => TRUE, // ISO-8859-2
704 'latin2' => TRUE, // ISO-8859-2
705 'cen' => TRUE, // ISO-8859-2
706 'iso8859-3' => TRUE, // ISO-8859-3
707 'latin3' => TRUE, // ISO-8859-3
708 'iso8859-4' => TRUE, // ISO-8859-4
709 'latin4' => TRUE, // ISO-8859-4
710 'iso8859-5' => TRUE, // ISO-8859-5
711 'latin5' => TRUE, // ISO-8859-5
712 'cyr' => TRUE, // ISO-8859-5
713 'iso-ru' => TRUE, // ISO-8859-5
714 'iso8859-6' => TRUE, // ISO-8859-6
715 'latin6' => TRUE, // ISO-8859-6
716 'arb' => TRUE, // ISO-8859-6
717 'iso8859-7' => TRUE, // ISO-8859-7
718 'latin7' => TRUE, // ISO-8859-7
719 'grk' => TRUE, // ISO-8859-7
720 'iso8859-8' => TRUE, // ISO-8859-8
721 'latin8' => TRUE, // ISO-8859-8
722 'heb' => TRUE, // ISO-8859-8
723 'iso8859-9' => TRUE, // ISO-8859-9
724 'latin9' => TRUE, // ISO-8859-9
725 'trk' => TRUE, // ISO-8859-9
726 'iso2022-jp'=> TRUE, // ISO-2022-JP
727 'jis' => TRUE, // ISO-2022-JP
728 'iso2022-kr'=> TRUE, // ISO-2022-KR
729 'kis' => TRUE, // ISO-2022-KR
730 'iso2022-cn'=> TRUE, // ISO-2022-CN
731 'cis' => TRUE, // ISO-2022-CN
733 'cp-1251' => TRUE, // ru, WINDOWS-1251
734 'win-1251' => TRUE, // ru, WINDOWS-1251
735 'cp866' => TRUE, // ru
736 'koi8-r' => TRUE, // ru, KOI8-r
737 'koi8-ru' => TRUE, // ru, KOI8-r
738 'koi8-uk' => TRUE, // ru, KOI8-ru
739 'ua' => TRUE, // ru, KOI8-ru
740 'ucs2' => TRUE, // ru, ISO-10646-UCS-2
741 'ucs4' => TRUE, // ru, ISO-10646-UCS-4
744 // Reference: Apache 2.0.59 default 'index.html' variants
749 // May uncompress by web browsers on the fly
750 // Must be at the last of the filename
751 // Reference: Apache 2.0.59 'AddEncoding'
752 static $encoding_suffix = array(
757 if (! is_string($file)) return '';
758 $_file = strtolower($file);
759 if (isset($simple_defaults[$_file])) return '';
762 // Roughly removing language/character-set/encoding suffixes
764 // * Apache 2 document about 'Content-negotiaton', 'mod_mime' and 'mod_negotiation'
765 // http://httpd.apache.org/docs/2.0/content-negotiation.html
766 // http://httpd.apache.org/docs/2.0/mod/mod_mime.html
767 // http://httpd.apache.org/docs/2.0/mod/mod_negotiation.html
768 // * http://www.iana.org/assignments/character-sets
769 // * RFC3066: Tags for the Identification of Languages
770 // http://www.ietf.org/rfc/rfc3066.txt
771 // * ISO 639: codes of 'language names'
772 $suffixes = explode('.', $_file);
773 $body = array_shift($suffixes);
775 // Remove the last .gz/.z
776 $last_key = end(array_keys($suffixes));
777 if (isset($encoding_suffix[$suffixes[$last_key]])) {
778 unset($suffixes[$last_key]);
781 // Cut language and charset suffixes
782 foreach($suffixes as $key => $value){
783 if (isset($language_suffix[$value]) || isset($charset_suffix[$value])) {
784 unset($suffixes[$key]);
787 if (empty($suffixes)) return $body;
790 $count = count($suffixes);
792 $current = current($suffixes);
793 if ($body == 'index' && $count == 1 && isset($content_suffix[$current])) return '';
798 // Sort query-strings if possible (Destructive and rough)
799 // [OK] &&&&f=d&b&d&c&a=0dd => a=0dd&b&c&d&f=d
800 // [OK] nothing==&eg=dummy&eg=padding&eg=foobar => eg=foobar
801 function query_normalize($string = '', $equal = TRUE, $equal_cutempty = TRUE, $stortolower = TRUE)
803 if (! is_string($string)) return '';
804 if ($stortolower) $string = strtolower($string);
806 $array = explode('&', $string);
808 // Remove '&' paddings
809 foreach(array_keys($array) as $key) {
810 if ($array[$key] == '') {
815 // Consider '='-sepalated input and paddings
817 $equals = $not_equals = array();
818 foreach ($array as $part) {
819 if (strpos($part, '=') === FALSE) {
820 $not_equals[] = $part;
822 list($key, $value) = explode('=', $part, 2);
823 $value = ltrim($value, '=');
824 if (! $equal_cutempty || $value != '') {
825 $equals[$key] = $value;
830 $array = & $not_equals;
831 foreach ($equals as $key => $value) {
832 $array[] = $key . '=' . $value;
838 return implode('&', $array);
841 // ---------------------
842 // Part One : Checker
844 // Rough implementation of globbing
846 // USAGE: $regex = '/^' . generate_glob_regex('*.txt', '/') . '$/i';
848 function generate_glob_regex($string = '', $divider = '/')
850 static $from = array(
853 // 22 => '[', // Maybe cause regex compilation error (e.g. '[]')
869 if (! is_string($string)) return '';
871 $string = str_replace($from, $mid, $string); // Hide
872 $string = preg_quote($string, $divider);
873 $string = str_replace($mid, $to, $string); // Unhide
878 // Rough hostname checker
880 // TODO: Strict digit, 0x, CIDR, IPv6
881 function is_ip($string = '')
883 if (preg_match('/^' .
884 '(?:[0-9]{1,3}\.){3}[0-9]{1,3}' . '|' .
885 '(?:[0-9]{1,3}\.){1,3}' . '$/',
887 return 4; // Seems IPv4(dot-decimal)
889 return 0; // Seems not IP
893 // Generate host (FQDN, IPv4, ...) regex
894 // 'localhost' : Matches with 'localhost' only
895 // 'example.org' : Matches with 'example.org' only (See host_normalize() about 'www')
896 // '.example.org' : Matches with ALL FQDN ended with '.example.org'
897 // '*.example.org' : Almost the same of '.example.org' except 'www.example.org'
898 // '10.20.30.40' : Matches with IPv4 address '10.20.30.40' only
899 // [TODO] '192.' : Matches with all IPv4 hosts started with '192.'
900 // TODO: IPv4, CIDR?, IPv6
901 function generate_host_regex($string = '', $divider = '/')
903 if (! is_string($string)) return '';
905 if (mb_strpos($string, '.') === FALSE)
906 return generate_glob_regex($string, $divider);
909 if (is_ip($string)) {
911 return generate_glob_regex($string, $divider);
914 $part = explode('.', $string, 2);
915 if ($part[0] == '') {
916 $part[0] = '(?:.*\.)?'; // And all related FQDN
917 } else if ($part[0] == '*') {
918 $part[0] = '.*\.'; // All subdomains/hosts only
920 return generate_glob_regex($string, $divider);
922 $part[1] = generate_glob_regex($part[1], $divider);
923 return implode('', $part);
927 function get_blocklist($list = '')
931 if (! isset($regexs)) {
933 if (file_exists(SPAM_INI_FILE)) {
934 $blocklist = array();
935 include(SPAM_INI_FILE);
936 // $blocklist['badhost'] = array(
937 // '*.blogspot.com', // Blog services's subdomains (only)
938 // 'IANA-examples' => '#^(?:.*\.)?example\.(?:com|net|org)$#',
940 if (isset($blocklist['list'])) {
941 $regexs['list'] = & $blocklist['list'];
944 $blocklist['list'] = array(
949 foreach(array_keys($blocklist['list']) as $_list) {
950 if (! isset($blocklist[$_list])) continue;
951 foreach ($blocklist[$_list] as $key => $value) {
952 if (is_array($value)) {
953 $regexs[$_list][$key] = array();
954 foreach($value as $_key => $_value) {
955 get_blocklist_add($regexs[$_list][$key], $_key, $_value);
958 get_blocklist_add($regexs[$_list], $key, $value);
961 unset($blocklist[$_list]);
967 return $regexs; // ALL
968 } else if (isset($regexs[$list])) {
969 return $regexs[$list];
975 // Subroutine of get_blocklist()
976 function get_blocklist_add(& $array, $key = 0, $value = '*.example.org')
978 if (is_string($key)) {
979 $array[$key] = & $value; // Treat $value as a regex
981 $array[$value] = '/^' . generate_host_regex($value, '/') . '$/i';
985 // Blocklist metrics: Separate $host, to $blocked and not blocked
986 function blocklist_distiller(& $hosts, $keys = array('goodhost', 'badhost'), $asap = FALSE)
988 if (! is_array($hosts)) $hosts = array($hosts);
989 if (! is_array($keys)) $keys = array($keys);
991 $list = get_blocklist('list');
994 foreach($keys as $key){
995 foreach (get_blocklist($key) as $label => $regex) {
996 if (is_array($regex)) {
997 foreach($regex as $_label => $_regex) {
998 $group = preg_grep($_regex, $hosts);
1000 $hosts = array_diff($hosts, $group);
1001 $blocked[$key][$label][$_label] = $group;
1002 if ($asap && $list[$key]) break;
1006 $group = preg_grep($regex, $hosts);
1008 $hosts = array_diff($hosts, $group);
1009 $blocked[$key][$label] = $group;
1010 if ($asap && $list[$key]) break;
1019 // Simple example for badhost (not used now)
1020 function is_badhost($hosts = array(), $asap = TRUE, $bool = TRUE)
1022 $list = get_blocklist('list');
1023 $blocked = blocklist_distiller($hosts, array_keys($list), $asap);
1024 foreach($list as $key=>$type){
1025 if (! $type) unset($blocked[$key]); // Ignore goodhost etc
1028 return $bool ? ! empty($blocked) : $blocked;
1032 // Default (enabled) methods and thresholds (for content insertion)
1033 function check_uri_spam_method($times = 1, $t_area = 0, $rule = TRUE)
1035 $times = intval($times);
1036 $t_area = intval($t_area);
1040 'quantity' => 8 * $times, // Allow N URIs
1041 'non_uniqhost' => 3 * $times, // Allow N duped (and normalized) Hosts
1042 //'non_uniquri'=> 3 * $times, // Allow N duped (and normalized) URIs
1045 'area_anchor' => $t_area, // Using <a href> HTML tag
1046 'area_bbcode' => $t_area, // Using [url] or [link] BBCode
1047 //'uri_anchor' => $t_area, // URI inside <a href> HTML tag
1048 //'uri_bbcode' => $t_area, // URI inside [url] or [link] BBCode
1053 //'asap' => TRUE, // Quit or return As Soon As Possible
1054 'uniqhost' => TRUE, // Show uniq host (at block notification mail)
1055 'badhost' => TRUE, // Check badhost
1061 // Remove non-$positive values
1062 foreach (array_keys($positive) as $key) {
1063 if ($positive[$key] < 0) unset($positive[$key]);
1066 return $positive + $bool;
1069 // Simple/fast spam check
1070 function check_uri_spam($target = '', $method = array())
1072 if (! is_array($method) || empty($method)) {
1073 $method = check_uri_spam_method();
1087 'is_spam' => array(),
1088 'method' => & $method,
1089 'remains' => array(),
1092 $sum = & $progress['sum'];
1093 $is_spam = & $progress['is_spam'];
1094 $remains = & $progress['remains'];
1095 $error = & $progress['error'];
1096 $asap = isset($method['asap']);
1099 if (is_array($target)) {
1100 foreach($target as $str) {
1102 $_progress = check_uri_spam($str, $method);
1103 $_sum = & $_progress['sum'];
1104 $_is_spam = & $_progress['is_spam'];
1105 $_remains = & $_progress['remains'];
1106 $_error = & $_progress['error'];
1107 foreach (array_keys($_sum) as $key) {
1108 $sum[$key] += $_sum[$key];
1110 foreach (array_keys($_is_spam) as $key) {
1111 if (is_array($_is_spam[$key])) {
1112 // Marge keys (badhost)
1113 foreach(array_keys($_is_spam[$key]) as $_key) {
1114 if (! isset($is_spam[$key][$_key])) {
1115 $is_spam[$key][$_key] = $_is_spam[$key][$_key];
1117 $is_spam[$key][$_key] += $_is_spam[$key][$_key];
1121 $is_spam[$key] = TRUE;
1124 foreach ($_remains as $key=>$value) {
1125 foreach ($value as $_key=>$_value) {
1126 if (is_int($_key)) {
1127 $remains[$key][] = $_value;
1129 $remains[$key][$_key] = $_value;
1133 if (! empty($_error)) $error += $_error;
1134 if ($asap && $is_spam) break;
1139 // Area: There's HTML anchor tag
1140 if ((! $asap || ! $is_spam) && isset($method['area_anchor'])) {
1141 $key = 'area_anchor';
1142 $_asap = isset($method['asap']) ? array('asap' => TRUE) : array();
1143 $result = area_pickup($target, array($key => TRUE) + $_asap);
1145 $sum[$key] = $result[$key];
1146 if (isset($method[$key]) && $sum[$key] > $method[$key]) {
1147 $is_spam[$key] = TRUE;
1152 // Area: There's 'BBCode' linking tag
1153 if ((! $asap || ! $is_spam) && isset($method['area_bbcode'])) {
1154 $key = 'area_bbcode';
1155 $_asap = isset($method['asap']) ? array('asap' => TRUE) : array();
1156 $result = area_pickup($target, array($key => TRUE) + $_asap);
1158 $sum[$key] = $result[$key];
1159 if (isset($method[$key]) && $sum[$key] > $method[$key]) {
1160 $is_spam[$key] = TRUE;
1166 if ($asap && $is_spam) return $progress;
1169 $pickups = uri_pickup_normalize(spam_uri_pickup($target, $method));
1170 //$remains['uri_pickup'] = & $pickups;
1173 if (empty($pickups)) return $progress;
1175 // URI: Check quantity
1176 $sum['quantity'] += count($pickups);
1178 if ((! $asap || ! $is_spam) && isset($method['quantity']) &&
1179 $sum['quantity'] > $method['quantity']) {
1180 $is_spam['quantity'] = TRUE;
1183 // URI: used inside HTML anchor tag pair
1184 if ((! $asap || ! $is_spam) && isset($method['uri_anchor'])) {
1185 $key = 'uri_anchor';
1186 foreach($pickups as $pickup) {
1187 if (isset($pickup['area'][$key])) {
1188 $sum[$key] += $pickup['area'][$key];
1189 if(isset($method[$key]) &&
1190 $sum[$key] > $method[$key]) {
1191 $is_spam[$key] = TRUE;
1192 if ($asap && $is_spam) break;
1194 if ($asap && $is_spam) break;
1199 // URI: used inside 'BBCode' pair
1200 if ((! $asap || ! $is_spam) && isset($method['uri_bbcode'])) {
1201 $key = 'uri_bbcode';
1202 foreach($pickups as $pickup) {
1203 if (isset($pickup['area'][$key])) {
1204 $sum[$key] += $pickup['area'][$key];
1205 if(isset($method[$key]) &&
1206 $sum[$key] > $method[$key]) {
1207 $is_spam[$key] = TRUE;
1208 if ($asap && $is_spam) break;
1210 if ($asap && $is_spam) break;
1215 // URI: Uniqueness (and removing non-uniques)
1216 if ((! $asap || ! $is_spam) && isset($method['non_uniquri'])) {
1219 foreach (array_keys($pickups) as $key) {
1220 $uris[$key] = uri_pickup_implode($pickups[$key]);
1222 $count = count($uris);
1223 $uris = array_unique($uris);
1224 $sum['non_uniquri'] += $count - count($uris);
1225 if ($sum['non_uniquri'] > $method['non_uniquri']) {
1226 $is_spam['non_uniquri'] = TRUE;
1228 if (! $asap || ! $is_spam) {
1229 foreach (array_diff(array_keys($pickups),
1230 array_keys($uris)) as $remove) {
1231 unset($pickups[$remove]);
1238 if ($asap && $is_spam) return $progress;
1240 // Host: Uniqueness (uniq / non-uniq)
1242 foreach ($pickups as $pickup) $hosts[] = & $pickup['host'];
1243 $hosts = array_unique($hosts);
1244 //$remains['uniqhost'] = & $hosts;
1245 $sum['uniqhost'] += count($hosts);
1246 if ((! $asap || ! $is_spam) && isset($method['non_uniqhost'])) {
1247 $sum['non_uniqhost'] = $sum['quantity'] - $sum['uniqhost'];
1248 if ($sum['non_uniqhost'] > $method['non_uniqhost']) {
1249 $is_spam['non_uniqhost'] = TRUE;
1254 if ($asap && $is_spam) return $progress;
1256 // URI: Bad host (Separate good/bad hosts from $hosts)
1257 if ((! $asap || ! $is_spam) && isset($method['badhost'])) {
1260 $list = get_blocklist('list');
1261 $blocked = blocklist_distiller($hosts, array_keys($list), $asap);
1262 foreach($list as $key=>$type){
1263 if (! $type) unset($blocked[$key]); // Ignore goodhost etc
1267 if (! $asap && $hosts) {
1268 $remains['badhost'] = array();
1269 foreach ($hosts as $value) {
1270 $remains['badhost'][$value] = TRUE;
1274 if (! empty($blocked)) {
1276 //var_dump($blocked); // BADHOST detail
1278 $sum['badhost'] += array_count_leaves($blocked);
1279 foreach(array_keys($blocked) as $keys) {
1280 $is_spam['badhost'][$keys] =
1281 array_count_leaves($blocked[$keys]);
1289 // Count leaves (A leaf = value that is not an array, or an empty array)
1290 function array_count_leaves($array = array(), $count_empty = FALSE)
1292 if (! is_array($array) || (empty($array) && $count_empty)) return 1;
1296 foreach ($array as $part) {
1297 $count += array_count_leaves($part, $count_empty);
1303 function array_merge_leaves($array1 = array(), $array2 = array())
1305 return array_merge_recursive($array1, $array2);
1308 // ---------------------
1311 // TODO: Don't show unused $method!
1312 // Summarize $progress (blocked only)
1313 function summarize_spam_progress($progress = array(), $blockedonly = FALSE)
1316 $tmp = array_keys($progress['is_spam']);
1319 $method = & $progress['method'];
1320 if (isset($progress['sum'])) {
1321 foreach ($progress['sum'] as $key => $value) {
1322 if (isset($method[$key])) {
1323 $tmp[] = $key . '(' . $value . ')';
1329 return implode(', ', $tmp);
1332 function summarize_detail_badhost($is_spam_badhost = array())
1335 foreach($is_spam_badhost as $glob=>$number) {
1336 $badhost[] = $glob . '(' . $number . ')';
1338 return implode(', ', $badhost);
1342 function summarize_detail_newtral($remains_badhost = array())
1344 return count($remains_badhost) .
1345 ' (' . implode(', ', array_keys($remains_badhost)) . ')';
1349 // ---------------------
1352 // Common bahavior for blocking
1353 // NOTE: Call this function from various blocking feature, to disgueise the reason 'why blocked'
1354 function spam_exit($mode = '', $data = array())
1357 case '': echo("\n"); break;
1359 echo('<pre>' . "\n");
1360 echo htmlspecialchars(var_export($data, TRUE));
1361 echo('</pre>' . "\n");
1370 // ---------------------
1373 // TODO: Record them
1374 // Simple/fast spam filter ($target: 'a string' or an array())
1375 function pkwk_spamfilter($action, $page, $target = array('title' => ''), $method = array(), $exitmode = '')
1377 $progress = check_uri_spam($target, $method);
1379 if (! empty($progress['is_spam'])) {
1380 // Mail to administrator(s)
1381 pkwk_spamnotify($action, $page, $target, $progress, $method);
1384 spam_exit($exitmode, $progress);
1388 // ---------------------
1389 // PukiWiki original
1391 // Mail to administrator(s)
1392 function pkwk_spamnotify($action, $page, $target = array('title' => ''), $progress = array(), $method = array())
1394 global $notify, $notify_subject;
1396 if (! $notify) return;
1398 $asap = isset($method['asap']);
1400 $summary['ACTION'] = 'Blocked by: ' . summarize_spam_progress($progress, TRUE);
1402 $summary['METRICS'] = summarize_spam_progress($progress);
1404 if (isset($progress['is_spam']['badhost'])) {
1405 $summary['DETAIL_BADHOST'] = summarize_detail_badhost($progress['is_spam']['badhost']);
1407 if (! $asap && $progress['remains']['badhost']) {
1408 $summary['DETAIL_NEUTRAL_HOST'] = summarize_detail_newtral($progress['remains']['badhost']);
1410 $summary['COMMENT'] = $action;
1411 $summary['PAGE'] = '[blocked] ' . (is_pagename($page) ? $page : '');
1412 $summary['URI'] = get_script_uri() . '?' . rawurlencode($page);
1413 $summary['USER_AGENT'] = TRUE;
1414 $summary['REMOTE_ADDR'] = TRUE;
1415 pkwk_mail_notify($notify_subject, var_export($target, TRUE), $summary, TRUE);