2 // $Id: spam.php,v 1.148 2007/05/05 04:59:31 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 // Remove redundant values from array()
41 function array_unique_recursive($array = array())
43 if (! is_array($array)) return $array;
46 foreach($array as $key => $value){
47 if (is_array($value)) {
48 $array[$key] = array_unique_recursive($value);
50 if (isset($tmp[$value])) {
61 // Roughly strings(1) using PCRE
62 // This function is useful to:
63 // * Reduce the size of data, from removing unprintable binary data
64 // * Detect _bare_strings_ from binary data
66 // http://www.freebsd.org/cgi/man.cgi?query=strings (Man-page of GNU strings)
67 // http://www.pcre.org/pcre.txt
68 function strings($binary = '', $min_len = 4, $ignore_space = FALSE)
71 $binary = preg_replace(
73 '/(?:[^[:graph:] \t\n]|[\r])+/s',
86 $binary = preg_replace('/(?:[^[:graph:][:space:]]|[\r])+/s', "\n", $binary);
90 $min_len = min(1024, intval($min_len));
93 preg_grep('/^.{' . $min_len . ',}/S',
94 explode("\n", $binary)
103 // ---------------------
106 // Return an array of URIs in the $string
107 // [OK] http://nasty.example.org#nasty_string
108 // [OK] http://nasty.example.org:80/foo/xxx#nasty_string/bar
109 // [OK] ftp://nasty.example.org:80/dfsdfs
110 // [OK] ftp://cnn.example.com&story=breaking_news@10.0.0.1/top_story.htm (from RFC3986)
111 function uri_pickup($string = '')
113 if (! is_string($string)) return array();
115 // Not available for: IDN(ignored)
118 // scheme://userinfo@host:port/path/or/pathinfo/maybefile.and?query=string#fragment
119 // Refer RFC3986 (Regex below is not strict)
120 '#(\b[a-z][a-z0-9.+-]{1,8}):/+' . // 1: Scheme
122 '([^\s<>"\'\[\]/\#?@]*)' . // 2: Userinfo (Username)
126 '\[[0-9a-f:.]+\]' . '|' . // IPv6([colon-hex and dot]): RFC2732
127 '(?:[0-9]{1,3}\.){3}[0-9]{1,3}' . '|' . // IPv4(dot-decimal): 001.22.3.44
128 '[a-z0-9.-]+' . // hostname(FQDN) : foo.example.org
130 '(?::([0-9]*))?' . // 4: Port
131 '((?:/+[^\s<>"\'\[\]/\#]+)*/+)?' . // 5: Directory path or path-info
132 '([^\s<>"\'\[\]\#?]+)?' . // 6: File?
133 '(?:\?([^\s<>"\'\[\]\#]+))?' . // 7: Query string
134 '(?:\#([a-z0-9._~%!$&\'()*+,;=:@-]*))?' . // 8: Fragment
136 $string, $array, PREG_SET_ORDER | PREG_OFFSET_CAPTURE
140 static $parts = array(
141 1 => 'scheme', 2 => 'userinfo', 3 => 'host', 4 => 'port',
142 5 => 'path', 6 => 'file', 7 => 'query', 8 => 'fragment'
144 $default = array('');
145 foreach(array_keys($array) as $uri) {
146 $_uri = & $array[$uri];
147 array_rename_keys($_uri, $parts, TRUE, $default);
148 $offset = $_uri['scheme'][1]; // Scheme's offset = URI's offset
149 foreach(array_keys($_uri) as $part) {
150 $_uri[$part] = & $_uri[$part][0]; // Remove offsets
154 foreach(array_keys($array) as $uri) {
155 $_uri = & $array[$uri];
156 if ($_uri['scheme'] === '') {
157 unset($array[$uri]); // Considererd harmless
160 unset($_uri[0]); // Matched string itself
161 $_uri['area']['offset'] = $offset; // Area offset for area_measure()
167 // Normalize an array of URI arrays
168 // NOTE: Give me the uri_pickup() results
169 function uri_pickup_normalize(& $pickups, $destructive = TRUE)
171 if (! is_array($pickups)) return $pickups;
174 foreach (array_keys($pickups) as $key) {
175 $_key = & $pickups[$key];
176 $_key['scheme'] = isset($_key['scheme']) ? scheme_normalize($_key['scheme']) : '';
177 $_key['host'] = isset($_key['host']) ? host_normalize($_key['host']) : '';
178 $_key['port'] = isset($_key['port']) ? port_normalize($_key['port'], $_key['scheme'], FALSE) : '';
179 $_key['path'] = isset($_key['path']) ? strtolower(path_normalize($_key['path'])) : '';
180 $_key['file'] = isset($_key['file']) ? file_normalize($_key['file']) : '';
181 $_key['query'] = isset($_key['query']) ? query_normalize($_key['query']) : '';
182 $_key['fragment'] = isset($_key['fragment']) ? strtolower($_key['fragment']) : '';
185 foreach (array_keys($pickups) as $key) {
186 $_key = & $pickups[$key];
187 $_key['scheme'] = isset($_key['scheme']) ? scheme_normalize($_key['scheme']) : '';
188 $_key['host'] = isset($_key['host']) ? strtolower($_key['host']) : '';
189 $_key['port'] = isset($_key['port']) ? port_normalize($_key['port'], $_key['scheme'], FALSE) : '';
190 $_key['path'] = isset($_key['path']) ? path_normalize($_key['path']) : '';
197 // An URI array => An URI (See uri_pickup())
199 // $pickups = uri_pickup('a string include some URIs');
201 // foreach (array_keys($pickups) as $key) {
202 // $uris[$key] = uri_pickup_implode($pickups[$key]);
204 function uri_pickup_implode($uri = array())
206 if (empty($uri) || ! is_array($uri)) return NULL;
209 if (isset($uri['scheme']) && $uri['scheme'] !== '') {
210 $tmp[] = & $uri['scheme'];
213 if (isset($uri['userinfo']) && $uri['userinfo'] !== '') {
214 $tmp[] = & $uri['userinfo'];
217 if (isset($uri['host']) && $uri['host'] !== '') {
218 $tmp[] = & $uri['host'];
220 if (isset($uri['port']) && $uri['port'] !== '') {
222 $tmp[] = & $uri['port'];
224 if (isset($uri['path']) && $uri['path'] !== '') {
225 $tmp[] = & $uri['path'];
227 if (isset($uri['file']) && $uri['file'] !== '') {
228 $tmp[] = & $uri['file'];
230 if (isset($uri['query']) && $uri['query'] !== '') {
232 $tmp[] = & $uri['query'];
234 if (isset($uri['fragment']) && $uri['fragment'] !== '') {
236 $tmp[] = & $uri['fragment'];
239 return implode('', $tmp);
242 // $array['something'] => $array['wanted']
243 function array_rename_keys(& $array, $keys = array('from' => 'to'), $force = FALSE, $default = '')
245 if (! is_array($array) || ! is_array($keys)) return FALSE;
247 // Nondestructive test
249 foreach(array_keys($keys) as $from)
250 if (! isset($array[$from]))
253 foreach($keys as $from => $to) {
254 if ($from === $to) continue;
255 if (! $force || isset($array[$from])) {
256 $array[$to] = & $array[$from];
257 unset($array[$from]);
259 $array[$to] = $default;
266 // ---------------------
269 // Pickup all of markup areas
270 function area_pickup($string = '', $method = array())
273 if (empty($method)) return $area;
275 // Anchor tag pair by preg_match and preg_match_all()
277 // [OK] <a href= >Good site!</a>
278 // [OK] <a href= "#" >test</a>
279 // [OK] <a href="http://nasty.example.com">visit http://nasty.example.com/</a>
280 // [OK] <a href=\'http://nasty.example.com/\' >discount foobar</a>
281 // [NG] <a href="http://ng.example.com">visit http://ng.example.com _not_ended_
282 $regex = '#<a\b[^>]*\bhref\b[^>]*>.*?</a\b[^>]*(>)#is';
283 if (isset($method['area_anchor'])) {
285 $count = isset($method['asap']) ?
286 preg_match($regex, $string) :
287 preg_match_all($regex, $string, $areas);
288 if (! empty($count)) $area['area_anchor'] = $count;
290 if (isset($method['uri_anchor'])) {
292 preg_match_all($regex, $string, $areas, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
293 foreach(array_keys($areas) as $_area) {
294 $areas[$_area] = array(
295 $areas[$_area][0][1], // Area start (<a href>)
296 $areas[$_area][1][1], // Area end (</a>)
299 if (! empty($areas)) $area['uri_anchor'] = $areas;
302 // phpBB's "BBCode" pair by preg_match and preg_match_all()
304 // [OK] [url]http://nasty.example.com/[/url]
305 // [OK] [link]http://nasty.example.com/[/link]
306 // [OK] [url=http://nasty.example.com]visit http://nasty.example.com/[/url]
307 // [OK] [link http://nasty.example.com/]buy something[/link]
308 $regex = '#\[(url|link)\b[^\]]*\].*?\[/\1\b[^\]]*(\])#is';
309 if (isset($method['area_bbcode'])) {
311 $count = isset($method['asap']) ?
312 preg_match($regex, $string) :
313 preg_match_all($regex, $string, $areas, PREG_SET_ORDER);
314 if (! empty($count)) $area['area_bbcode'] = $count;
316 if (isset($method['uri_bbcode'])) {
318 preg_match_all($regex, $string, $areas, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
319 foreach(array_keys($areas) as $_area) {
320 $areas[$_area] = array(
321 $areas[$_area][0][1], // Area start ([url])
322 $areas[$_area][2][1], // Area end ([/url])
325 if (! empty($areas)) $area['uri_bbcode'] = $areas;
328 // Various Wiki syntax
329 // [text_or_uri>text_or_uri]
330 // [text_or_uri:text_or_uri]
331 // [text_or_uri|text_or_uri]
332 // [text_or_uri->text_or_uri]
333 // [text_or_uri text_or_uri] // MediaWiki
334 // MediaWiki: [http://nasty.example.com/ visit http://nasty.example.com/]
339 // If in doubt, it's a little doubtful
340 // if (Area => inside <= Area) $brief += -1
341 function area_measure($areas, & $array, $belief = -1, $a_key = 'area', $o_key = 'offset')
343 if (! is_array($areas) || ! is_array($array)) return;
345 $areas_keys = array_keys($areas);
346 foreach(array_keys($array) as $u_index) {
347 $offset = isset($array[$u_index][$o_key]) ?
348 intval($array[$u_index][$o_key]) : 0;
349 foreach($areas_keys as $a_index) {
350 if (isset($array[$u_index][$a_key])) {
351 $offset_s = intval($areas[$a_index][0]);
352 $offset_e = intval($areas[$a_index][1]);
353 // [Area => inside <= Area]
354 if ($offset_s < $offset && $offset < $offset_e) {
355 $array[$u_index][$a_key] += $belief;
362 // ---------------------
365 // Domain exposure callback (See spam_uri_pickup_preprocess())
366 // http://victim.example.org/?foo+site:nasty.example.com+bar
367 // => http://nasty.example.com/?refer=victim.example.org
368 // NOTE: 'refer=' is not so good for (at this time).
369 // Consider about using IP address of the victim, try to avoid that.
370 function _preg_replace_callback_domain_exposure($matches = array())
374 // Preserve the victim URI as a complicity or ...
375 if (isset($matches[5])) {
377 $matches[1] . '://' . // scheme
378 $matches[2] . '/' . // victim.example.org
379 $matches[3]; // The rest of all (before victim)
383 if (isset($matches[4])) {
385 $matches[1] . '://' . // scheme
386 $matches[4] . // nasty.example.com
387 '/?refer=' . strtolower($matches[2]) . // victim.example.org
394 // Preprocess: rawurldecode() and adding space(s) and something
395 // to detect/count some URIs _if possible_
396 // NOTE: It's maybe danger to var_dump(result). [e.g. 'javascript:']
397 // [OK] http://victim.example.org/?site:nasty.example.org
398 // [OK] http://victim.example.org/nasty.example.org
399 // [OK] http://victim.example.org/go?http%3A%2F%2Fnasty.example.org
400 // [OK] http://victim.example.org/http://nasty.example.org
401 function spam_uri_pickup_preprocess($string = '')
403 if (! is_string($string)) return '';
405 $string = rawurldecode($string);
407 // Domain exposure (simple)
408 // http://victim.example.org/nasty.example.org/path#frag
409 // => http://nasty.example.org/?refer=victim.example.org and original
410 $string = preg_replace(
413 'ime\.nu' . '|' . // 2ch.net
414 'ime\.st' . '|' . // 2ch.net
415 'link\.toolbot\.com' . '|' .
418 '/([a-z0-9.%_-]+\.[a-z0-9.%_-]+)#i', // nasty.example.org
419 'http://$2/?refer=$1 $0', // Preserve $0 or remove?
423 // Domain exposure (See _preg_replace_callback_domain_exposure())
424 $string = preg_replace_callback(
428 // Something Google: http://www.google.com/supported_domains
429 '(?:[a-z0-9.]+\.)?google\.[a-z]{2,3}(?:\.[a-z]{2})?' .
432 '(?:[a-z0-9.]+\.)?altavista.com' .
436 '([a-z0-9?=&.%_/\'\\\+-]+)' . // path/?query=foo+bar+
437 '\bsite:([a-z0-9.%_-]+\.[a-z0-9.%_-]+)' . // site:nasty.example.com
438 //'()' . // Preserve or remove?
441 '_preg_replace_callback_domain_exposure',
445 // URI exposure (uriuri => uri uri)
446 $string = preg_replace(
448 '#(?<! )(?:https?|ftp):/#i',
449 // '#[a-z][a-z0-9.+-]{1,8}://#i',
450 // '#[a-z][a-z0-9.+-]{1,8}://#i'
459 // Main function of spam-uri pickup,
460 // A wrapper function of uri_pickup()
461 function spam_uri_pickup($string = '', $method = array())
463 if (! is_array($method) || empty($method)) {
464 $method = check_uri_spam_method();
467 $string = spam_uri_pickup_preprocess($string);
469 $array = uri_pickup($string);
471 // Area elevation of URIs, for '(especially external)link' intension
472 if (! empty($array)) {
474 if (isset($method['uri_anchor'])) $_method['uri_anchor'] = & $method['uri_anchor'];
475 if (isset($method['uri_bbcode'])) $_method['uri_bbcode'] = & $method['uri_bbcode'];
476 $areas = area_pickup($string, $_method, TRUE);
477 if (! empty($areas)) {
478 $area_shadow = array();
479 foreach (array_keys($array) as $key) {
480 $area_shadow[$key] = & $array[$key]['area'];
481 foreach (array_keys($_method) as $_key) {
482 $area_shadow[$key][$_key] = 0;
485 foreach (array_keys($_method) as $_key) {
486 if (isset($areas[$_key])) {
487 area_measure($areas[$_key], $area_shadow, 1, $_key);
493 // Remove 'offset's for area_measure()
494 foreach(array_keys($array) as $key)
495 unset($array[$key]['area']['offset']);
501 // ---------------------
504 // Scheme normalization: Renaming the schemes
505 // snntp://example.org => nntps://example.org
506 // NOTE: Keep the static lists simple. See also port_normalize().
507 function scheme_normalize($scheme = '', $abbrevs_harmfull = TRUE)
509 // Abbreviations they have no intention of link
510 static $abbrevs = array(
515 // Aliases => normalized ones
516 static $aliases = array(
526 if (! is_string($scheme)) return '';
528 $scheme = strtolower($scheme);
529 if (isset($abbrevs[$scheme])) {
530 $scheme = $abbrevs_harmfull ? $abbrevs[$scheme] : '';
532 if (isset($aliases[$scheme])) {
533 $scheme = $aliases[$scheme];
539 // Hostname normlization (Destructive)
540 // www.foo => www.foo ('foo' seems TLD)
541 // www.foo.bar => foo.bar
542 // www.10.20 => www.10.20 (Invalid hostname)
544 // 'www' is mostly used as traditional hostname of WWW server.
545 // 'www.foo.bar' may be identical with 'foo.bar'.
546 function host_normalize($host = '')
548 if (! is_string($host)) return '';
550 $host = strtolower($host);
552 if (preg_match('/^www\.(.+\.[a-z]+)$/', $host, $matches)) {
559 // Port normalization: Suppress the (redundant) default port
560 // HTTP://example.org:80/ => http://example.org/
561 // HTTP://example.org:8080/ => http://example.org:8080/
562 // HTTPS://example.org:443/ => https://example.org/
563 function port_normalize($port, $scheme, $scheme_normalize = FALSE)
565 // Schemes that users _maybe_ want to add protocol-handlers
566 // to their web browsers. (and attackers _maybe_ want to use ...)
567 // Reference: http://www.iana.org/assignments/port-numbers
568 static $array = array(
569 // scheme => default port
595 // intval() converts '0-1' to '0', so preg_match() rejects these invalid ones
596 if (! is_numeric($port) || $port < 0 || preg_match('/[^0-9]/i', $port))
599 $port = intval($port);
600 if ($scheme_normalize) $scheme = scheme_normalize($scheme);
601 if (isset($array[$scheme]) && $port == $array[$scheme])
602 $port = ''; // Ignore the defaults
607 // Path normalization
608 // http://example.org => http://example.org/
609 // http://example.org#hoge => http://example.org/#hoge
610 // http://example.org/path/a/b/./c////./d => http://example.org/path/a/b/c/d
611 // http://example.org/path/../../a/../back => http://example.org/back
612 function path_normalize($path = '', $divider = '/', $add_root = TRUE)
614 if (! is_string($divider)) return is_string($path) ? $path : '';
617 $first_div = & $divider;
621 if (! is_string($path) || $path == '') return $first_div;
623 if (strpos($path, $divider, strlen($path) - strlen($divider)) === FALSE) {
626 $last_div = & $divider;
629 $array = explode($divider, $path);
631 // Remove paddings ('//' and '/./')
632 foreach(array_keys($array) as $key) {
633 if ($array[$key] == '' || $array[$key] == '.') {
638 // Remove back-tracks ('/../')
640 foreach($array as $value) {
641 if ($value == '..') {
644 array_push($tmp, $value);
652 return $first_div . implode($divider, $array) . $last_div;
656 // DirectoryIndex normalize (Destructive and rough)
657 // TODO: sample.en.ja.html.gz => sample.html
658 function file_normalize($file = 'index.html.en')
660 static $simple_defaults = array(
661 'default.htm' => TRUE,
662 'default.html' => TRUE,
663 'default.asp' => TRUE,
664 'default.aspx' => TRUE,
665 'index' => TRUE, // Some system can omit the suffix
668 static $content_suffix = array(
669 // index.xxx, sample.xxx
684 static $language_suffix = array(
685 // Reference: Apache 2.0.59 'AddLanguage' default
714 // Reference: Apache 2.0.59 default 'index.html' variants
720 static $charset_suffix = array(
721 // Reference: Apache 2.0.59 'AddCharset' default
722 'iso8859-1' => TRUE, // ISO-8859-1
723 'latin1' => TRUE, // ISO-8859-1
724 'iso8859-2' => TRUE, // ISO-8859-2
725 'latin2' => TRUE, // ISO-8859-2
726 'cen' => TRUE, // ISO-8859-2
727 'iso8859-3' => TRUE, // ISO-8859-3
728 'latin3' => TRUE, // ISO-8859-3
729 'iso8859-4' => TRUE, // ISO-8859-4
730 'latin4' => TRUE, // ISO-8859-4
731 'iso8859-5' => TRUE, // ISO-8859-5
732 'latin5' => TRUE, // ISO-8859-5
733 'cyr' => TRUE, // ISO-8859-5
734 'iso-ru' => TRUE, // ISO-8859-5
735 'iso8859-6' => TRUE, // ISO-8859-6
736 'latin6' => TRUE, // ISO-8859-6
737 'arb' => TRUE, // ISO-8859-6
738 'iso8859-7' => TRUE, // ISO-8859-7
739 'latin7' => TRUE, // ISO-8859-7
740 'grk' => TRUE, // ISO-8859-7
741 'iso8859-8' => TRUE, // ISO-8859-8
742 'latin8' => TRUE, // ISO-8859-8
743 'heb' => TRUE, // ISO-8859-8
744 'iso8859-9' => TRUE, // ISO-8859-9
745 'latin9' => TRUE, // ISO-8859-9
746 'trk' => TRUE, // ISO-8859-9
747 'iso2022-jp'=> TRUE, // ISO-2022-JP
748 'jis' => TRUE, // ISO-2022-JP
749 'iso2022-kr'=> TRUE, // ISO-2022-KR
750 'kis' => TRUE, // ISO-2022-KR
751 'iso2022-cn'=> TRUE, // ISO-2022-CN
752 'cis' => TRUE, // ISO-2022-CN
754 'cp-1251' => TRUE, // ru, WINDOWS-1251
755 'win-1251' => TRUE, // ru, WINDOWS-1251
756 'cp866' => TRUE, // ru
757 'koi8-r' => TRUE, // ru, KOI8-r
758 'koi8-ru' => TRUE, // ru, KOI8-r
759 'koi8-uk' => TRUE, // ru, KOI8-ru
760 'ua' => TRUE, // ru, KOI8-ru
761 'ucs2' => TRUE, // ru, ISO-10646-UCS-2
762 'ucs4' => TRUE, // ru, ISO-10646-UCS-4
765 // Reference: Apache 2.0.59 default 'index.html' variants
770 // May uncompress by web browsers on the fly
771 // Must be at the last of the filename
772 // Reference: Apache 2.0.59 'AddEncoding'
773 static $encoding_suffix = array(
778 if (! is_string($file)) return '';
779 $_file = strtolower($file);
780 if (isset($simple_defaults[$_file])) return '';
783 // Roughly removing language/character-set/encoding suffixes
785 // * Apache 2 document about 'Content-negotiaton', 'mod_mime' and 'mod_negotiation'
786 // http://httpd.apache.org/docs/2.0/content-negotiation.html
787 // http://httpd.apache.org/docs/2.0/mod/mod_mime.html
788 // http://httpd.apache.org/docs/2.0/mod/mod_negotiation.html
789 // * http://www.iana.org/assignments/character-sets
790 // * RFC3066: Tags for the Identification of Languages
791 // http://www.ietf.org/rfc/rfc3066.txt
792 // * ISO 639: codes of 'language names'
793 $suffixes = explode('.', $_file);
794 $body = array_shift($suffixes);
796 // Remove the last .gz/.z
797 $last_key = end(array_keys($suffixes));
798 if (isset($encoding_suffix[$suffixes[$last_key]])) {
799 unset($suffixes[$last_key]);
802 // Cut language and charset suffixes
803 foreach($suffixes as $key => $value){
804 if (isset($language_suffix[$value]) || isset($charset_suffix[$value])) {
805 unset($suffixes[$key]);
808 if (empty($suffixes)) return $body;
811 $count = count($suffixes);
813 $current = current($suffixes);
814 if ($body == 'index' && $count == 1 && isset($content_suffix[$current])) return '';
819 // Sort query-strings if possible (Destructive and rough)
820 // [OK] &&&&f=d&b&d&c&a=0dd => a=0dd&b&c&d&f=d
821 // [OK] nothing==&eg=dummy&eg=padding&eg=foobar => eg=foobar
822 function query_normalize($string = '', $equal = TRUE, $equal_cutempty = TRUE, $stortolower = TRUE)
824 if (! is_string($string)) return '';
825 if ($stortolower) $string = strtolower($string);
827 $array = explode('&', $string);
829 // Remove '&' paddings
830 foreach(array_keys($array) as $key) {
831 if ($array[$key] == '') {
836 // Consider '='-sepalated input and paddings
838 $equals = $not_equals = array();
839 foreach ($array as $part) {
840 if (strpos($part, '=') === FALSE) {
841 $not_equals[] = $part;
843 list($key, $value) = explode('=', $part, 2);
844 $value = ltrim($value, '=');
845 if (! $equal_cutempty || $value != '') {
846 $equals[$key] = $value;
851 $array = & $not_equals;
852 foreach ($equals as $key => $value) {
853 $array[] = $key . '=' . $value;
859 return implode('&', $array);
862 // ---------------------
863 // Part One : Checker
865 // Rough implementation of globbing
867 // USAGE: $regex = '/^' . generate_glob_regex('*.txt', '/') . '$/i';
869 function generate_glob_regex($string = '', $divider = '/')
871 static $from = array(
874 // 22 => '[', // Maybe cause regex compilation error (e.g. '[]')
890 if (! is_string($string)) return '';
892 $string = str_replace($from, $mid, $string); // Hide
893 $string = preg_quote($string, $divider);
894 $string = str_replace($mid, $to, $string); // Unhide
899 // Rough hostname checker
901 // TODO: Strict digit, 0x, CIDR, IPv6
902 function is_ip($string = '')
904 if (preg_match('/^' .
905 '(?:[0-9]{1,3}\.){3}[0-9]{1,3}' . '|' .
906 '(?:[0-9]{1,3}\.){1,3}' . '$/',
908 return 4; // Seems IPv4(dot-decimal)
910 return 0; // Seems not IP
914 // Generate host (FQDN, IPv4, ...) regex
915 // 'localhost' : Matches with 'localhost' only
916 // 'example.org' : Matches with 'example.org' only (See host_normalize() about 'www')
917 // '.example.org' : Matches with ALL FQDN ended with '.example.org'
918 // '*.example.org' : Almost the same of '.example.org' except 'www.example.org'
919 // '10.20.30.40' : Matches with IPv4 address '10.20.30.40' only
920 // [TODO] '192.' : Matches with all IPv4 hosts started with '192.'
921 // TODO: IPv4, CIDR?, IPv6
922 function generate_host_regex($string = '', $divider = '/')
924 if (! is_string($string)) return '';
926 if (mb_strpos($string, '.') === FALSE)
927 return generate_glob_regex($string, $divider);
930 if (is_ip($string)) {
932 return generate_glob_regex($string, $divider);
935 $part = explode('.', $string, 2);
936 if ($part[0] == '') {
937 $part[0] = '(?:.*\.)?'; // And all related FQDN
938 } else if ($part[0] == '*') {
939 $part[0] = '.*\.'; // All subdomains/hosts only
941 return generate_glob_regex($string, $divider);
943 $part[1] = generate_glob_regex($part[1], $divider);
944 return implode('', $part);
948 function get_blocklist($list = '')
952 if (! isset($regexs)) {
954 if (file_exists(SPAM_INI_FILE)) {
955 $blocklist = array();
956 include(SPAM_INI_FILE);
957 // $blocklist['badhost'] = array(
958 // '*.blogspot.com', // Blog services's subdomains (only)
959 // 'IANA-examples' => '#^(?:.*\.)?example\.(?:com|net|org)$#',
961 if (isset($blocklist['list'])) {
962 $regexs['list'] = & $blocklist['list'];
965 $blocklist['list'] = array(
970 foreach(array_keys($blocklist['list']) as $_list) {
971 if (! isset($blocklist[$_list])) continue;
972 foreach ($blocklist[$_list] as $key => $value) {
973 if (is_array($value)) {
974 $regexs[$_list][$key] = array();
975 foreach($value as $_key => $_value) {
976 get_blocklist_add($regexs[$_list][$key], $_key, $_value);
979 get_blocklist_add($regexs[$_list], $key, $value);
982 unset($blocklist[$_list]);
988 return $regexs; // ALL
989 } else if (isset($regexs[$list])) {
990 return $regexs[$list];
996 // Subroutine of get_blocklist()
997 function get_blocklist_add(& $array, $key = 0, $value = '*.example.org')
999 if (is_string($key)) {
1000 $array[$key] = & $value; // Treat $value as a regex
1002 $array[$value] = '/^' . generate_host_regex($value, '/') . '$/i';
1006 // Blocklist metrics: Separate $host, to $blocked and not blocked
1007 function blocklist_distiller(& $hosts, $keys = array('goodhost', 'badhost'), $asap = FALSE)
1009 if (! is_array($hosts)) $hosts = array($hosts);
1010 if (! is_array($keys)) $keys = array($keys);
1012 $list = get_blocklist('list');
1015 foreach($keys as $key){
1016 foreach (get_blocklist($key) as $label => $regex) {
1017 if (is_array($regex)) {
1018 foreach($regex as $_label => $_regex) {
1019 $group = preg_grep($_regex, $hosts);
1021 $hosts = array_diff($hosts, $group);
1022 $blocked[$key][$label][$_label] = $group;
1023 if ($asap && $list[$key]) break;
1027 $group = preg_grep($regex, $hosts);
1029 $hosts = array_diff($hosts, $group);
1030 $blocked[$key][$label] = $group;
1031 if ($asap && $list[$key]) break;
1040 // Simple example for badhost (not used now)
1041 function is_badhost($hosts = array(), $asap = TRUE, $bool = TRUE)
1043 $list = get_blocklist('list');
1044 $blocked = blocklist_distiller($hosts, array_keys($list), $asap);
1045 foreach($list as $key=>$type){
1046 if (! $type) unset($blocked[$key]); // Ignore goodhost etc
1049 return $bool ? ! empty($blocked) : $blocked;
1053 // Default (enabled) methods and thresholds (for content insertion)
1054 function check_uri_spam_method($times = 1, $t_area = 0, $rule = TRUE)
1056 $times = intval($times);
1057 $t_area = intval($t_area);
1061 'quantity' => 8 * $times, // Allow N URIs
1062 'non_uniqhost' => 3 * $times, // Allow N duped (and normalized) Hosts
1063 //'non_uniquri'=> 3 * $times, // Allow N duped (and normalized) URIs
1066 'area_anchor' => $t_area, // Using <a href> HTML tag
1067 'area_bbcode' => $t_area, // Using [url] or [link] BBCode
1068 //'uri_anchor' => $t_area, // URI inside <a href> HTML tag
1069 //'uri_bbcode' => $t_area, // URI inside [url] or [link] BBCode
1074 //'asap' => TRUE, // Quit or return As Soon As Possible
1075 'uniqhost' => TRUE, // Show uniq host (at block notification mail)
1076 'badhost' => TRUE, // Check badhost
1082 // Remove non-$positive values
1083 foreach (array_keys($positive) as $key) {
1084 if ($positive[$key] < 0) unset($positive[$key]);
1087 return $positive + $bool;
1090 // Simple/fast spam check
1091 function check_uri_spam($target = '', $method = array())
1096 // Theme to do => Dummy, optional value, or optional array()
1098 //'uniqhost' => TRUE,
1099 //'non_uniqhost'=> 3,
1100 //'non_uniquri' => 3,
1101 //'badhost' => TRUE,
1102 //'area_anchor' => 0,
1103 //'area_bbcode' => 0,
1104 //'uri_anchor' => 0,
1105 //'uri_bbcode' => 0,
1108 // Theme => Volume found (int)
1111 // Flag. If someting defined here,
1112 // one or more spam will be included
1117 //'category' => array(
1122 // Hosts not blocked
1127 $sum = & $progress['sum'];
1128 $is_spam = & $progress['is_spam'];
1129 $progress['method'] = & $method; // Argument
1130 $blocked = & $progress['blocked'];
1131 $hosts = & $progress['hosts'];
1132 $asap = isset($method['asap']);
1135 if (! is_array($method) || empty($method)) {
1136 $method = check_uri_spam_method();
1138 foreach(array_keys($method) as $key) {
1139 if (! isset($sum[$key])) $sum[$key] = 0;
1142 if (is_array($target)) {
1143 foreach($target as $str) {
1144 if (! is_string($str)) continue;
1146 $_progress = check_uri_spam($str, $method); // Recurse
1149 $_sum = & $_progress['sum'];
1150 foreach (array_keys($_sum) as $key) {
1151 if (! isset($sum[$key])) {
1152 $sum[$key] = & $_sum[$key];
1154 $sum[$key] += $_sum[$key];
1159 $_is_spam = & $_progress['is_spam'];
1160 foreach (array_keys($_is_spam) as $key) {
1161 $is_spam[$key] = TRUE;
1164 if ($asap && $is_spam) break;
1167 $blocked = array_merge_leaves($blocked, $_progress['blocked']);
1170 $hosts = array_merge_leaves($hosts, $_progress['hosts']);
1173 // Recount $sum['badhost']
1174 $sum['badhost'] = array_count_leaves($blocked);
1179 // Area: There's HTML anchor tag
1180 if ((! $asap || ! $is_spam) && isset($method['area_anchor'])) {
1181 $key = 'area_anchor';
1182 $_asap = isset($method['asap']) ? array('asap' => TRUE) : array();
1183 $result = area_pickup($target, array($key => TRUE) + $_asap);
1185 $sum[$key] = $result[$key];
1186 if (isset($method[$key]) && $sum[$key] > $method[$key]) {
1187 $is_spam[$key] = TRUE;
1192 // Area: There's 'BBCode' linking tag
1193 if ((! $asap || ! $is_spam) && isset($method['area_bbcode'])) {
1194 $key = 'area_bbcode';
1195 $_asap = isset($method['asap']) ? array('asap' => TRUE) : array();
1196 $result = area_pickup($target, array($key => TRUE) + $_asap);
1198 $sum[$key] = $result[$key];
1199 if (isset($method[$key]) && $sum[$key] > $method[$key]) {
1200 $is_spam[$key] = TRUE;
1206 if ($asap && $is_spam) return $progress;
1209 $pickups = uri_pickup_normalize(spam_uri_pickup($target, $method));
1212 if (empty($pickups)) return $progress;
1214 // URI: Check quantity
1215 $sum['quantity'] += count($pickups);
1217 if ((! $asap || ! $is_spam) && isset($method['quantity']) &&
1218 $sum['quantity'] > $method['quantity']) {
1219 $is_spam['quantity'] = TRUE;
1222 // URI: used inside HTML anchor tag pair
1223 if ((! $asap || ! $is_spam) && isset($method['uri_anchor'])) {
1224 $key = 'uri_anchor';
1225 foreach($pickups as $pickup) {
1226 if (isset($pickup['area'][$key])) {
1227 $sum[$key] += $pickup['area'][$key];
1228 if(isset($method[$key]) &&
1229 $sum[$key] > $method[$key]) {
1230 $is_spam[$key] = TRUE;
1231 if ($asap && $is_spam) break;
1233 if ($asap && $is_spam) break;
1238 // URI: used inside 'BBCode' pair
1239 if ((! $asap || ! $is_spam) && isset($method['uri_bbcode'])) {
1240 $key = 'uri_bbcode';
1241 foreach($pickups as $pickup) {
1242 if (isset($pickup['area'][$key])) {
1243 $sum[$key] += $pickup['area'][$key];
1244 if(isset($method[$key]) &&
1245 $sum[$key] > $method[$key]) {
1246 $is_spam[$key] = TRUE;
1247 if ($asap && $is_spam) break;
1249 if ($asap && $is_spam) break;
1254 // URI: Uniqueness (and removing non-uniques)
1255 if ((! $asap || ! $is_spam) && isset($method['non_uniquri'])) {
1258 foreach (array_keys($pickups) as $key) {
1259 $uris[$key] = uri_pickup_implode($pickups[$key]);
1261 $count = count($uris);
1262 $uris = array_unique($uris);
1263 $sum['non_uniquri'] += $count - count($uris);
1264 if ($sum['non_uniquri'] > $method['non_uniquri']) {
1265 $is_spam['non_uniquri'] = TRUE;
1267 if (! $asap || ! $is_spam) {
1268 foreach (array_diff(array_keys($pickups),
1269 array_keys($uris)) as $remove) {
1270 unset($pickups[$remove]);
1277 if ($asap && $is_spam) return $progress;
1279 // Host: Uniqueness (uniq / non-uniq)
1280 foreach ($pickups as $pickup) $hosts[] = & $pickup['host'];
1281 $hosts = array_unique($hosts);
1282 $sum['uniqhost'] += count($hosts);
1283 if ((! $asap || ! $is_spam) && isset($method['non_uniqhost'])) {
1284 $sum['non_uniqhost'] = $sum['quantity'] - $sum['uniqhost'];
1285 if ($sum['non_uniqhost'] > $method['non_uniqhost']) {
1286 $is_spam['non_uniqhost'] = TRUE;
1291 if ($asap && $is_spam) return $progress;
1293 // URI: Bad host (Separate good/bad hosts from $hosts)
1294 if ((! $asap || ! $is_spam) && isset($method['badhost'])) {
1297 $list = get_blocklist('list');
1298 $blocked = blocklist_distiller($hosts, array_keys($list), $asap);
1299 foreach($list as $key=>$type){
1300 if (! $type) unset($blocked[$key]); // Ignore goodhost etc
1304 if (! empty($blocked)) $is_spam['badhost'] = TRUE;
1310 // Count leaves (A leaf = value that is not an array, or an empty array)
1311 function array_count_leaves($array = array(), $count_empty = FALSE)
1313 if (! is_array($array) || (empty($array) && $count_empty)) return 1;
1317 foreach ($array as $part) {
1318 $count += array_count_leaves($part, $count_empty);
1323 // Merge two leaves' value
1324 function array_merge_leaves(& $array1, & $array2, $unique_values = TRUE)
1326 // All NUMERIC keys are always renumbered from 0
1327 $array = array_merge_recursive($array1, $array2);
1329 // Redundant values (and keys) are vanished
1330 if ($unique_values) $array = array_unique_recursive($array);
1336 // ---------------------
1339 // TODO: Don't show unused $method!
1340 // Summarize $progress (blocked only)
1341 function summarize_spam_progress($progress = array(), $blockedonly = FALSE)
1344 $tmp = array_keys($progress['is_spam']);
1347 $method = & $progress['method'];
1348 if (isset($progress['sum'])) {
1349 foreach ($progress['sum'] as $key => $value) {
1350 if (isset($method[$key]) && $value) {
1351 $tmp[] = $key . '(' . $value . ')';
1357 return implode(', ', $tmp);
1360 function summarize_detail_badhost($progress = array())
1362 if (! isset($progress['is_spam']['badhost'])) return '';
1364 return var_export($progress['blocked'], TRUE);
1367 function summarize_detail_newtral($progress = array())
1369 if (empty($progress['hosts'])) return '';
1371 return var_export($progress['hosts'], TRUE);
1375 // ---------------------
1378 // Common bahavior for blocking
1379 // NOTE: Call this function from various blocking feature, to disgueise the reason 'why blocked'
1380 function spam_exit($mode = '', $data = array())
1383 case '': echo("\n"); break;
1385 echo('<pre>' . "\n");
1386 echo htmlspecialchars(var_export($data, TRUE));
1387 echo('</pre>' . "\n");
1396 // ---------------------
1399 // TODO: Record them
1400 // Simple/fast spam filter ($target: 'a string' or an array())
1401 function pkwk_spamfilter($action, $page, $target = array('title' => ''), $method = array(), $exitmode = '')
1403 $progress = check_uri_spam($target, $method);
1405 if (! empty($progress['is_spam'])) {
1406 // Mail to administrator(s)
1407 pkwk_spamnotify($action, $page, $target, $progress, $method);
1410 spam_exit($exitmode, $progress);
1414 // ---------------------
1415 // PukiWiki original
1417 // Mail to administrator(s)
1418 function pkwk_spamnotify($action, $page, $target = array('title' => ''), $progress = array(), $method = array())
1420 global $notify, $notify_subject;
1422 if (! $notify) return;
1424 $asap = isset($method['asap']);
1426 $summary['ACTION'] = 'Blocked by: ' . summarize_spam_progress($progress, TRUE);
1428 $summary['METRICS'] = summarize_spam_progress($progress);
1431 $tmp = summarize_detail_badhost($progress);
1432 if ($tmp != '') $summary['DETAIL_BADHOST'] = $tmp;
1434 $tmp = summarize_detail_newtral($progress);
1435 if (! $asap && $tmp != '') $summary['DETAIL_NEUTRAL_HOST'] = $tmp;
1437 $summary['COMMENT'] = $action;
1438 $summary['PAGE'] = '[blocked] ' . (is_pagename($page) ? $page : '');
1439 $summary['URI'] = get_script_uri() . '?' . rawurlencode($page);
1440 $summary['USER_AGENT'] = TRUE;
1441 $summary['REMOTE_ADDR'] = TRUE;
1442 pkwk_mail_notify($notify_subject, var_export($target, TRUE), $summary, TRUE);