2 // $Id: spam.php,v 1.153 2007/05/05 08:02:39 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 // Renumber all numeric keys from 0
62 function array_renumber_numeric_keys(& $array)
64 if (! is_array($array)) return $array;
68 foreach($array as $key => $value){
69 if (is_array($value)) array_renumber_numeric_keys($array[$key]); // Recurse
70 if (is_numeric($key)) $tmp[$key] = ++$count;
72 array_rename_keys($array, $tmp);
77 // Roughly strings(1) using PCRE
78 // This function is useful to:
79 // * Reduce the size of data, from removing unprintable binary data
80 // * Detect _bare_strings_ from binary data
82 // http://www.freebsd.org/cgi/man.cgi?query=strings (Man-page of GNU strings)
83 // http://www.pcre.org/pcre.txt
84 function strings($binary = '', $min_len = 4, $ignore_space = FALSE)
87 $binary = preg_replace(
89 '/(?:[^[:graph:] \t\n]|[\r])+/s',
102 $binary = preg_replace('/(?:[^[:graph:][:space:]]|[\r])+/s', "\n", $binary);
106 $min_len = min(1024, intval($min_len));
109 preg_grep('/^.{' . $min_len . ',}/S',
110 explode("\n", $binary)
119 // ---------------------
122 // Return an array of URIs in the $string
123 // [OK] http://nasty.example.org#nasty_string
124 // [OK] http://nasty.example.org:80/foo/xxx#nasty_string/bar
125 // [OK] ftp://nasty.example.org:80/dfsdfs
126 // [OK] ftp://cnn.example.com&story=breaking_news@10.0.0.1/top_story.htm (from RFC3986)
127 function uri_pickup($string = '')
129 if (! is_string($string)) return array();
131 // Not available for: IDN(ignored)
134 // scheme://userinfo@host:port/path/or/pathinfo/maybefile.and?query=string#fragment
135 // Refer RFC3986 (Regex below is not strict)
136 '#(\b[a-z][a-z0-9.+-]{1,8}):/+' . // 1: Scheme
138 '([^\s<>"\'\[\]/\#?@]*)' . // 2: Userinfo (Username)
142 '\[[0-9a-f:.]+\]' . '|' . // IPv6([colon-hex and dot]): RFC2732
143 '(?:[0-9]{1,3}\.){3}[0-9]{1,3}' . '|' . // IPv4(dot-decimal): 001.22.3.44
144 '[a-z0-9.-]+' . // hostname(FQDN) : foo.example.org
146 '(?::([0-9]*))?' . // 4: Port
147 '((?:/+[^\s<>"\'\[\]/\#]+)*/+)?' . // 5: Directory path or path-info
148 '([^\s<>"\'\[\]\#?]+)?' . // 6: File?
149 '(?:\?([^\s<>"\'\[\]\#]+))?' . // 7: Query string
150 '(?:\#([a-z0-9._~%!$&\'()*+,;=:@-]*))?' . // 8: Fragment
152 $string, $array, PREG_SET_ORDER | PREG_OFFSET_CAPTURE
156 static $parts = array(
157 1 => 'scheme', 2 => 'userinfo', 3 => 'host', 4 => 'port',
158 5 => 'path', 6 => 'file', 7 => 'query', 8 => 'fragment'
160 $default = array('');
161 foreach(array_keys($array) as $uri) {
162 $_uri = & $array[$uri];
163 array_rename_keys($_uri, $parts, TRUE, $default);
164 $offset = $_uri['scheme'][1]; // Scheme's offset = URI's offset
165 foreach(array_keys($_uri) as $part) {
166 $_uri[$part] = & $_uri[$part][0]; // Remove offsets
170 foreach(array_keys($array) as $uri) {
171 $_uri = & $array[$uri];
172 if ($_uri['scheme'] === '') {
173 unset($array[$uri]); // Considererd harmless
176 unset($_uri[0]); // Matched string itself
177 $_uri['area']['offset'] = $offset; // Area offset for area_measure()
183 // Normalize an array of URI arrays
184 // NOTE: Give me the uri_pickup() results
185 function uri_pickup_normalize(& $pickups, $destructive = TRUE)
187 if (! is_array($pickups)) return $pickups;
190 foreach (array_keys($pickups) as $key) {
191 $_key = & $pickups[$key];
192 $_key['scheme'] = isset($_key['scheme']) ? scheme_normalize($_key['scheme']) : '';
193 $_key['host'] = isset($_key['host']) ? host_normalize($_key['host']) : '';
194 $_key['port'] = isset($_key['port']) ? port_normalize($_key['port'], $_key['scheme'], FALSE) : '';
195 $_key['path'] = isset($_key['path']) ? strtolower(path_normalize($_key['path'])) : '';
196 $_key['file'] = isset($_key['file']) ? file_normalize($_key['file']) : '';
197 $_key['query'] = isset($_key['query']) ? query_normalize($_key['query']) : '';
198 $_key['fragment'] = isset($_key['fragment']) ? strtolower($_key['fragment']) : '';
201 foreach (array_keys($pickups) as $key) {
202 $_key = & $pickups[$key];
203 $_key['scheme'] = isset($_key['scheme']) ? scheme_normalize($_key['scheme']) : '';
204 $_key['host'] = isset($_key['host']) ? strtolower($_key['host']) : '';
205 $_key['port'] = isset($_key['port']) ? port_normalize($_key['port'], $_key['scheme'], FALSE) : '';
206 $_key['path'] = isset($_key['path']) ? path_normalize($_key['path']) : '';
213 // An URI array => An URI (See uri_pickup())
215 // $pickups = uri_pickup('a string include some URIs');
217 // foreach (array_keys($pickups) as $key) {
218 // $uris[$key] = uri_pickup_implode($pickups[$key]);
220 function uri_pickup_implode($uri = array())
222 if (empty($uri) || ! is_array($uri)) return NULL;
225 if (isset($uri['scheme']) && $uri['scheme'] !== '') {
226 $tmp[] = & $uri['scheme'];
229 if (isset($uri['userinfo']) && $uri['userinfo'] !== '') {
230 $tmp[] = & $uri['userinfo'];
233 if (isset($uri['host']) && $uri['host'] !== '') {
234 $tmp[] = & $uri['host'];
236 if (isset($uri['port']) && $uri['port'] !== '') {
238 $tmp[] = & $uri['port'];
240 if (isset($uri['path']) && $uri['path'] !== '') {
241 $tmp[] = & $uri['path'];
243 if (isset($uri['file']) && $uri['file'] !== '') {
244 $tmp[] = & $uri['file'];
246 if (isset($uri['query']) && $uri['query'] !== '') {
248 $tmp[] = & $uri['query'];
250 if (isset($uri['fragment']) && $uri['fragment'] !== '') {
252 $tmp[] = & $uri['fragment'];
255 return implode('', $tmp);
258 // $array['something'] => $array['wanted']
259 function array_rename_keys(& $array, $keys = array('from' => 'to'), $force = FALSE, $default = '')
261 if (! is_array($array) || ! is_array($keys)) return FALSE;
263 // Nondestructive test
265 foreach(array_keys($keys) as $from)
266 if (! isset($array[$from]))
269 foreach($keys as $from => $to) {
270 if ($from === $to) continue;
271 if (! $force || isset($array[$from])) {
272 $array[$to] = & $array[$from];
273 unset($array[$from]);
275 $array[$to] = $default;
282 // ---------------------
285 // Pickup all of markup areas
286 function area_pickup($string = '', $method = array())
289 if (empty($method)) return $area;
291 // Anchor tag pair by preg_match and preg_match_all()
293 // [OK] <a href= >Good site!</a>
294 // [OK] <a href= "#" >test</a>
295 // [OK] <a href="http://nasty.example.com">visit http://nasty.example.com/</a>
296 // [OK] <a href=\'http://nasty.example.com/\' >discount foobar</a>
297 // [NG] <a href="http://ng.example.com">visit http://ng.example.com _not_ended_
298 $regex = '#<a\b[^>]*\bhref\b[^>]*>.*?</a\b[^>]*(>)#is';
299 if (isset($method['area_anchor'])) {
301 $count = isset($method['asap']) ?
302 preg_match($regex, $string) :
303 preg_match_all($regex, $string, $areas);
304 if (! empty($count)) $area['area_anchor'] = $count;
306 if (isset($method['uri_anchor'])) {
308 preg_match_all($regex, $string, $areas, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
309 foreach(array_keys($areas) as $_area) {
310 $areas[$_area] = array(
311 $areas[$_area][0][1], // Area start (<a href>)
312 $areas[$_area][1][1], // Area end (</a>)
315 if (! empty($areas)) $area['uri_anchor'] = $areas;
318 // phpBB's "BBCode" pair by preg_match and preg_match_all()
320 // [OK] [url]http://nasty.example.com/[/url]
321 // [OK] [link]http://nasty.example.com/[/link]
322 // [OK] [url=http://nasty.example.com]visit http://nasty.example.com/[/url]
323 // [OK] [link http://nasty.example.com/]buy something[/link]
324 $regex = '#\[(url|link)\b[^\]]*\].*?\[/\1\b[^\]]*(\])#is';
325 if (isset($method['area_bbcode'])) {
327 $count = isset($method['asap']) ?
328 preg_match($regex, $string) :
329 preg_match_all($regex, $string, $areas, PREG_SET_ORDER);
330 if (! empty($count)) $area['area_bbcode'] = $count;
332 if (isset($method['uri_bbcode'])) {
334 preg_match_all($regex, $string, $areas, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
335 foreach(array_keys($areas) as $_area) {
336 $areas[$_area] = array(
337 $areas[$_area][0][1], // Area start ([url])
338 $areas[$_area][2][1], // Area end ([/url])
341 if (! empty($areas)) $area['uri_bbcode'] = $areas;
344 // Various Wiki syntax
345 // [text_or_uri>text_or_uri]
346 // [text_or_uri:text_or_uri]
347 // [text_or_uri|text_or_uri]
348 // [text_or_uri->text_or_uri]
349 // [text_or_uri text_or_uri] // MediaWiki
350 // MediaWiki: [http://nasty.example.com/ visit http://nasty.example.com/]
355 // If in doubt, it's a little doubtful
356 // if (Area => inside <= Area) $brief += -1
357 function area_measure($areas, & $array, $belief = -1, $a_key = 'area', $o_key = 'offset')
359 if (! is_array($areas) || ! is_array($array)) return;
361 $areas_keys = array_keys($areas);
362 foreach(array_keys($array) as $u_index) {
363 $offset = isset($array[$u_index][$o_key]) ?
364 intval($array[$u_index][$o_key]) : 0;
365 foreach($areas_keys as $a_index) {
366 if (isset($array[$u_index][$a_key])) {
367 $offset_s = intval($areas[$a_index][0]);
368 $offset_e = intval($areas[$a_index][1]);
369 // [Area => inside <= Area]
370 if ($offset_s < $offset && $offset < $offset_e) {
371 $array[$u_index][$a_key] += $belief;
378 // ---------------------
381 // Domain exposure callback (See spam_uri_pickup_preprocess())
382 // http://victim.example.org/?foo+site:nasty.example.com+bar
383 // => http://nasty.example.com/?refer=victim.example.org
384 // NOTE: 'refer=' is not so good for (at this time).
385 // Consider about using IP address of the victim, try to avoid that.
386 function _preg_replace_callback_domain_exposure($matches = array())
390 // Preserve the victim URI as a complicity or ...
391 if (isset($matches[5])) {
393 $matches[1] . '://' . // scheme
394 $matches[2] . '/' . // victim.example.org
395 $matches[3]; // The rest of all (before victim)
399 if (isset($matches[4])) {
401 $matches[1] . '://' . // scheme
402 $matches[4] . // nasty.example.com
403 '/?refer=' . strtolower($matches[2]) . // victim.example.org
410 // Preprocess: rawurldecode() and adding space(s) and something
411 // to detect/count some URIs _if possible_
412 // NOTE: It's maybe danger to var_dump(result). [e.g. 'javascript:']
413 // [OK] http://victim.example.org/?site:nasty.example.org
414 // [OK] http://victim.example.org/nasty.example.org
415 // [OK] http://victim.example.org/go?http%3A%2F%2Fnasty.example.org
416 // [OK] http://victim.example.org/http://nasty.example.org
417 function spam_uri_pickup_preprocess($string = '')
419 if (! is_string($string)) return '';
421 $string = rawurldecode($string);
423 // Domain exposure (simple)
424 // http://victim.example.org/nasty.example.org/path#frag
425 // => http://nasty.example.org/?refer=victim.example.org and original
426 $string = preg_replace(
429 'ime\.nu' . '|' . // 2ch.net
430 'ime\.st' . '|' . // 2ch.net
431 'link\.toolbot\.com' . '|' .
434 '/([a-z0-9.%_-]+\.[a-z0-9.%_-]+)#i', // nasty.example.org
435 'http://$2/?refer=$1 $0', // Preserve $0 or remove?
439 // Domain exposure (See _preg_replace_callback_domain_exposure())
440 $string = preg_replace_callback(
444 // Something Google: http://www.google.com/supported_domains
445 '(?:[a-z0-9.]+\.)?google\.[a-z]{2,3}(?:\.[a-z]{2})?' .
448 '(?:[a-z0-9.]+\.)?altavista.com' .
452 '([a-z0-9?=&.%_/\'\\\+-]+)' . // path/?query=foo+bar+
453 '\bsite:([a-z0-9.%_-]+\.[a-z0-9.%_-]+)' . // site:nasty.example.com
454 //'()' . // Preserve or remove?
457 '_preg_replace_callback_domain_exposure',
461 // URI exposure (uriuri => uri uri)
462 $string = preg_replace(
464 '#(?<! )(?:https?|ftp):/#i',
465 // '#[a-z][a-z0-9.+-]{1,8}://#i',
466 // '#[a-z][a-z0-9.+-]{1,8}://#i'
475 // Main function of spam-uri pickup,
476 // A wrapper function of uri_pickup()
477 function spam_uri_pickup($string = '', $method = array())
479 if (! is_array($method) || empty($method)) {
480 $method = check_uri_spam_method();
483 $string = spam_uri_pickup_preprocess($string);
485 $array = uri_pickup($string);
487 // Area elevation of URIs, for '(especially external)link' intension
488 if (! empty($array)) {
490 if (isset($method['uri_anchor'])) $_method['uri_anchor'] = & $method['uri_anchor'];
491 if (isset($method['uri_bbcode'])) $_method['uri_bbcode'] = & $method['uri_bbcode'];
492 $areas = area_pickup($string, $_method, TRUE);
493 if (! empty($areas)) {
494 $area_shadow = array();
495 foreach (array_keys($array) as $key) {
496 $area_shadow[$key] = & $array[$key]['area'];
497 foreach (array_keys($_method) as $_key) {
498 $area_shadow[$key][$_key] = 0;
501 foreach (array_keys($_method) as $_key) {
502 if (isset($areas[$_key])) {
503 area_measure($areas[$_key], $area_shadow, 1, $_key);
509 // Remove 'offset's for area_measure()
510 foreach(array_keys($array) as $key)
511 unset($array[$key]['area']['offset']);
517 // ---------------------
520 // Scheme normalization: Renaming the schemes
521 // snntp://example.org => nntps://example.org
522 // NOTE: Keep the static lists simple. See also port_normalize().
523 function scheme_normalize($scheme = '', $abbrevs_harmfull = TRUE)
525 // Abbreviations they have no intention of link
526 static $abbrevs = array(
531 // Aliases => normalized ones
532 static $aliases = array(
542 if (! is_string($scheme)) return '';
544 $scheme = strtolower($scheme);
545 if (isset($abbrevs[$scheme])) {
546 $scheme = $abbrevs_harmfull ? $abbrevs[$scheme] : '';
548 if (isset($aliases[$scheme])) {
549 $scheme = $aliases[$scheme];
555 // Hostname normlization (Destructive)
556 // www.foo => www.foo ('foo' seems TLD)
557 // www.foo.bar => foo.bar
558 // www.10.20 => www.10.20 (Invalid hostname)
560 // 'www' is mostly used as traditional hostname of WWW server.
561 // 'www.foo.bar' may be identical with 'foo.bar'.
562 function host_normalize($host = '')
564 if (! is_string($host)) return '';
566 $host = strtolower($host);
568 if (preg_match('/^www\.(.+\.[a-z]+)$/', $host, $matches)) {
575 // Port normalization: Suppress the (redundant) default port
576 // HTTP://example.org:80/ => http://example.org/
577 // HTTP://example.org:8080/ => http://example.org:8080/
578 // HTTPS://example.org:443/ => https://example.org/
579 function port_normalize($port, $scheme, $scheme_normalize = FALSE)
581 // Schemes that users _maybe_ want to add protocol-handlers
582 // to their web browsers. (and attackers _maybe_ want to use ...)
583 // Reference: http://www.iana.org/assignments/port-numbers
584 static $array = array(
585 // scheme => default port
611 // intval() converts '0-1' to '0', so preg_match() rejects these invalid ones
612 if (! is_numeric($port) || $port < 0 || preg_match('/[^0-9]/i', $port))
615 $port = intval($port);
616 if ($scheme_normalize) $scheme = scheme_normalize($scheme);
617 if (isset($array[$scheme]) && $port == $array[$scheme])
618 $port = ''; // Ignore the defaults
623 // Path normalization
624 // http://example.org => http://example.org/
625 // http://example.org#hoge => http://example.org/#hoge
626 // http://example.org/path/a/b/./c////./d => http://example.org/path/a/b/c/d
627 // http://example.org/path/../../a/../back => http://example.org/back
628 function path_normalize($path = '', $divider = '/', $add_root = TRUE)
630 if (! is_string($divider)) return is_string($path) ? $path : '';
633 $first_div = & $divider;
637 if (! is_string($path) || $path == '') return $first_div;
639 if (strpos($path, $divider, strlen($path) - strlen($divider)) === FALSE) {
642 $last_div = & $divider;
645 $array = explode($divider, $path);
647 // Remove paddings ('//' and '/./')
648 foreach(array_keys($array) as $key) {
649 if ($array[$key] == '' || $array[$key] == '.') {
654 // Remove back-tracks ('/../')
656 foreach($array as $value) {
657 if ($value == '..') {
660 array_push($tmp, $value);
668 return $first_div . implode($divider, $array) . $last_div;
672 // DirectoryIndex normalize (Destructive and rough)
673 // TODO: sample.en.ja.html.gz => sample.html
674 function file_normalize($file = 'index.html.en')
676 static $simple_defaults = array(
677 'default.htm' => TRUE,
678 'default.html' => TRUE,
679 'default.asp' => TRUE,
680 'default.aspx' => TRUE,
681 'index' => TRUE, // Some system can omit the suffix
684 static $content_suffix = array(
685 // index.xxx, sample.xxx
700 static $language_suffix = array(
701 // Reference: Apache 2.0.59 'AddLanguage' default
730 // Reference: Apache 2.0.59 default 'index.html' variants
736 static $charset_suffix = array(
737 // Reference: Apache 2.0.59 'AddCharset' default
738 'iso8859-1' => TRUE, // ISO-8859-1
739 'latin1' => TRUE, // ISO-8859-1
740 'iso8859-2' => TRUE, // ISO-8859-2
741 'latin2' => TRUE, // ISO-8859-2
742 'cen' => TRUE, // ISO-8859-2
743 'iso8859-3' => TRUE, // ISO-8859-3
744 'latin3' => TRUE, // ISO-8859-3
745 'iso8859-4' => TRUE, // ISO-8859-4
746 'latin4' => TRUE, // ISO-8859-4
747 'iso8859-5' => TRUE, // ISO-8859-5
748 'latin5' => TRUE, // ISO-8859-5
749 'cyr' => TRUE, // ISO-8859-5
750 'iso-ru' => TRUE, // ISO-8859-5
751 'iso8859-6' => TRUE, // ISO-8859-6
752 'latin6' => TRUE, // ISO-8859-6
753 'arb' => TRUE, // ISO-8859-6
754 'iso8859-7' => TRUE, // ISO-8859-7
755 'latin7' => TRUE, // ISO-8859-7
756 'grk' => TRUE, // ISO-8859-7
757 'iso8859-8' => TRUE, // ISO-8859-8
758 'latin8' => TRUE, // ISO-8859-8
759 'heb' => TRUE, // ISO-8859-8
760 'iso8859-9' => TRUE, // ISO-8859-9
761 'latin9' => TRUE, // ISO-8859-9
762 'trk' => TRUE, // ISO-8859-9
763 'iso2022-jp'=> TRUE, // ISO-2022-JP
764 'jis' => TRUE, // ISO-2022-JP
765 'iso2022-kr'=> TRUE, // ISO-2022-KR
766 'kis' => TRUE, // ISO-2022-KR
767 'iso2022-cn'=> TRUE, // ISO-2022-CN
768 'cis' => TRUE, // ISO-2022-CN
770 'cp-1251' => TRUE, // ru, WINDOWS-1251
771 'win-1251' => TRUE, // ru, WINDOWS-1251
772 'cp866' => TRUE, // ru
773 'koi8-r' => TRUE, // ru, KOI8-r
774 'koi8-ru' => TRUE, // ru, KOI8-r
775 'koi8-uk' => TRUE, // ru, KOI8-ru
776 'ua' => TRUE, // ru, KOI8-ru
777 'ucs2' => TRUE, // ru, ISO-10646-UCS-2
778 'ucs4' => TRUE, // ru, ISO-10646-UCS-4
781 // Reference: Apache 2.0.59 default 'index.html' variants
786 // May uncompress by web browsers on the fly
787 // Must be at the last of the filename
788 // Reference: Apache 2.0.59 'AddEncoding'
789 static $encoding_suffix = array(
794 if (! is_string($file)) return '';
795 $_file = strtolower($file);
796 if (isset($simple_defaults[$_file])) return '';
799 // Roughly removing language/character-set/encoding suffixes
801 // * Apache 2 document about 'Content-negotiaton', 'mod_mime' and 'mod_negotiation'
802 // http://httpd.apache.org/docs/2.0/content-negotiation.html
803 // http://httpd.apache.org/docs/2.0/mod/mod_mime.html
804 // http://httpd.apache.org/docs/2.0/mod/mod_negotiation.html
805 // * http://www.iana.org/assignments/character-sets
806 // * RFC3066: Tags for the Identification of Languages
807 // http://www.ietf.org/rfc/rfc3066.txt
808 // * ISO 639: codes of 'language names'
809 $suffixes = explode('.', $_file);
810 $body = array_shift($suffixes);
812 // Remove the last .gz/.z
813 $last_key = end(array_keys($suffixes));
814 if (isset($encoding_suffix[$suffixes[$last_key]])) {
815 unset($suffixes[$last_key]);
818 // Cut language and charset suffixes
819 foreach($suffixes as $key => $value){
820 if (isset($language_suffix[$value]) || isset($charset_suffix[$value])) {
821 unset($suffixes[$key]);
824 if (empty($suffixes)) return $body;
827 $count = count($suffixes);
829 $current = current($suffixes);
830 if ($body == 'index' && $count == 1 && isset($content_suffix[$current])) return '';
835 // Sort query-strings if possible (Destructive and rough)
836 // [OK] &&&&f=d&b&d&c&a=0dd => a=0dd&b&c&d&f=d
837 // [OK] nothing==&eg=dummy&eg=padding&eg=foobar => eg=foobar
838 function query_normalize($string = '', $equal = TRUE, $equal_cutempty = TRUE, $stortolower = TRUE)
840 if (! is_string($string)) return '';
841 if ($stortolower) $string = strtolower($string);
843 $array = explode('&', $string);
845 // Remove '&' paddings
846 foreach(array_keys($array) as $key) {
847 if ($array[$key] == '') {
852 // Consider '='-sepalated input and paddings
854 $equals = $not_equals = array();
855 foreach ($array as $part) {
856 if (strpos($part, '=') === FALSE) {
857 $not_equals[] = $part;
859 list($key, $value) = explode('=', $part, 2);
860 $value = ltrim($value, '=');
861 if (! $equal_cutempty || $value != '') {
862 $equals[$key] = $value;
867 $array = & $not_equals;
868 foreach ($equals as $key => $value) {
869 $array[] = $key . '=' . $value;
875 return implode('&', $array);
878 // ---------------------
879 // Part One : Checker
881 // Rough implementation of globbing
883 // USAGE: $regex = '/^' . generate_glob_regex('*.txt', '/') . '$/i';
885 function generate_glob_regex($string = '', $divider = '/')
887 static $from = array(
890 // 22 => '[', // Maybe cause regex compilation error (e.g. '[]')
906 if (! is_string($string)) return '';
908 $string = str_replace($from, $mid, $string); // Hide
909 $string = preg_quote($string, $divider);
910 $string = str_replace($mid, $to, $string); // Unhide
915 // Rough hostname checker
917 // TODO: Strict digit, 0x, CIDR, IPv6
918 function is_ip($string = '')
920 if (preg_match('/^' .
921 '(?:[0-9]{1,3}\.){3}[0-9]{1,3}' . '|' .
922 '(?:[0-9]{1,3}\.){1,3}' . '$/',
924 return 4; // Seems IPv4(dot-decimal)
926 return 0; // Seems not IP
930 // Generate host (FQDN, IPv4, ...) regex
931 // 'localhost' : Matches with 'localhost' only
932 // 'example.org' : Matches with 'example.org' only (See host_normalize() about 'www')
933 // '.example.org' : Matches with ALL FQDN ended with '.example.org'
934 // '*.example.org' : Almost the same of '.example.org' except 'www.example.org'
935 // '10.20.30.40' : Matches with IPv4 address '10.20.30.40' only
936 // [TODO] '192.' : Matches with all IPv4 hosts started with '192.'
937 // TODO: IPv4, CIDR?, IPv6
938 function generate_host_regex($string = '', $divider = '/')
940 if (! is_string($string)) return '';
942 if (mb_strpos($string, '.') === FALSE)
943 return generate_glob_regex($string, $divider);
946 if (is_ip($string)) {
948 return generate_glob_regex($string, $divider);
951 $part = explode('.', $string, 2);
952 if ($part[0] == '') {
953 $part[0] = '(?:.*\.)?'; // And all related FQDN
954 } else if ($part[0] == '*') {
955 $part[0] = '.*\.'; // All subdomains/hosts only
957 return generate_glob_regex($string, $divider);
959 $part[1] = generate_glob_regex($part[1], $divider);
960 return implode('', $part);
964 function get_blocklist($list = '')
968 if (! isset($regexs)) {
970 if (file_exists(SPAM_INI_FILE)) {
971 $blocklist = array();
972 include(SPAM_INI_FILE);
973 // $blocklist['badhost'] = array(
974 // '*.blogspot.com', // Blog services's subdomains (only)
975 // 'IANA-examples' => '#^(?:.*\.)?example\.(?:com|net|org)$#',
977 if (isset($blocklist['list'])) {
978 $regexs['list'] = & $blocklist['list'];
981 $blocklist['list'] = array(
986 foreach(array_keys($blocklist['list']) as $_list) {
987 if (! isset($blocklist[$_list])) continue;
988 foreach ($blocklist[$_list] as $key => $value) {
989 if (is_array($value)) {
990 $regexs[$_list][$key] = array();
991 foreach($value as $_key => $_value) {
992 get_blocklist_add($regexs[$_list][$key], $_key, $_value);
995 get_blocklist_add($regexs[$_list], $key, $value);
998 unset($blocklist[$_list]);
1004 return $regexs; // ALL
1005 } else if (isset($regexs[$list])) {
1006 return $regexs[$list];
1012 // Subroutine of get_blocklist()
1013 function get_blocklist_add(& $array, $key = 0, $value = '*.example.org')
1015 if (is_string($key)) {
1016 $array[$key] = & $value; // Treat $value as a regex
1018 $array[$value] = '/^' . generate_host_regex($value, '/') . '$/i';
1022 // Blocklist metrics: Separate $host, to $blocked and not blocked
1023 function blocklist_distiller(& $hosts, $keys = array('goodhost', 'badhost'), $asap = FALSE)
1025 if (! is_array($hosts)) $hosts = array($hosts);
1026 if (! is_array($keys)) $keys = array($keys);
1028 $list = get_blocklist('list');
1031 foreach($keys as $key){
1032 foreach (get_blocklist($key) as $label => $regex) {
1033 if (is_array($regex)) {
1034 foreach($regex as $_label => $_regex) {
1035 $group = preg_grep($_regex, $hosts);
1037 $hosts = array_diff($hosts, $group);
1038 $blocked[$key][$label][$_label] = $group;
1039 if ($asap && $list[$key]) break;
1043 $group = preg_grep($regex, $hosts);
1045 $hosts = array_diff($hosts, $group);
1046 $blocked[$key][$label] = $group;
1047 if ($asap && $list[$key]) break;
1056 // Simple example for badhost (not used now)
1057 function is_badhost($hosts = array(), $asap = TRUE, $bool = TRUE)
1059 $list = get_blocklist('list');
1060 $blocked = blocklist_distiller($hosts, array_keys($list), $asap);
1061 foreach($list as $key=>$type){
1062 if (! $type) unset($blocked[$key]); // Ignore goodhost etc
1065 return $bool ? ! empty($blocked) : $blocked;
1069 // Default (enabled) methods and thresholds (for content insertion)
1070 function check_uri_spam_method($times = 1, $t_area = 0, $rule = TRUE)
1072 $times = intval($times);
1073 $t_area = intval($t_area);
1077 'quantity' => 8 * $times, // Allow N URIs
1078 'non_uniqhost' => 3 * $times, // Allow N duped (and normalized) Hosts
1079 //'non_uniquri'=> 3 * $times, // Allow N duped (and normalized) URIs
1082 'area_anchor' => $t_area, // Using <a href> HTML tag
1083 'area_bbcode' => $t_area, // Using [url] or [link] BBCode
1084 //'uri_anchor' => $t_area, // URI inside <a href> HTML tag
1085 //'uri_bbcode' => $t_area, // URI inside [url] or [link] BBCode
1090 //'asap' => TRUE, // Quit or return As Soon As Possible
1091 'uniqhost' => TRUE, // Show uniq host (at block notification mail)
1092 'badhost' => TRUE, // Check badhost
1098 // Remove non-$positive values
1099 foreach (array_keys($positive) as $key) {
1100 if ($positive[$key] < 0) unset($positive[$key]);
1103 return $positive + $bool;
1106 // Simple/fast spam check
1107 function check_uri_spam($target = '', $method = array())
1112 // Theme to do => Dummy, optional value, or optional array()
1114 //'uniqhost' => TRUE,
1115 //'non_uniqhost'=> 3,
1116 //'non_uniquri' => 3,
1117 //'badhost' => TRUE,
1118 //'area_anchor' => 0,
1119 //'area_bbcode' => 0,
1120 //'uri_anchor' => 0,
1121 //'uri_bbcode' => 0,
1124 // Theme => Volume found (int)
1127 // Flag. If someting defined here,
1128 // one or more spam will be included
1133 //'category' => array(
1138 // Hosts not blocked
1143 $sum = & $progress['sum'];
1144 $is_spam = & $progress['is_spam'];
1145 $progress['method'] = & $method; // Argument
1146 $blocked = & $progress['blocked'];
1147 $hosts = & $progress['hosts'];
1148 $asap = isset($method['asap']);
1151 if (! is_array($method) || empty($method)) {
1152 $method = check_uri_spam_method();
1154 foreach(array_keys($method) as $key) {
1155 if (! isset($sum[$key])) $sum[$key] = 0;
1158 if (is_array($target)) {
1159 foreach($target as $str) {
1160 if (! is_string($str)) continue;
1162 $_progress = check_uri_spam($str, $method); // Recurse
1165 $_sum = & $_progress['sum'];
1166 foreach (array_keys($_sum) as $key) {
1167 if (! isset($sum[$key])) {
1168 $sum[$key] = & $_sum[$key];
1170 $sum[$key] += $_sum[$key];
1175 $_is_spam = & $_progress['is_spam'];
1176 foreach (array_keys($_is_spam) as $key) {
1177 $is_spam[$key] = TRUE;
1180 if ($asap && $is_spam) break;
1183 $blocked = array_merge_leaves($blocked, $_progress['blocked'], FALSE, FALSE);
1184 $hosts = array_merge_leaves($hosts, $_progress['hosts'], FALSE, FALSE);
1188 $blocked = array_unique_recursive($blocked);
1189 $hosts = array_unique_recursive($hosts);
1191 // Renumber numeric keys
1192 array_renumber_numeric_keys($blocked);
1193 array_renumber_numeric_keys($hosts);
1195 // Recount $sum['badhost']
1196 $sum['badhost'] = array_count_leaves($blocked);
1201 // Area: There's HTML anchor tag
1202 if ((! $asap || ! $is_spam) && isset($method['area_anchor'])) {
1203 $key = 'area_anchor';
1204 $_asap = isset($method['asap']) ? array('asap' => TRUE) : array();
1205 $result = area_pickup($target, array($key => TRUE) + $_asap);
1207 $sum[$key] = $result[$key];
1208 if (isset($method[$key]) && $sum[$key] > $method[$key]) {
1209 $is_spam[$key] = TRUE;
1214 // Area: There's 'BBCode' linking tag
1215 if ((! $asap || ! $is_spam) && isset($method['area_bbcode'])) {
1216 $key = 'area_bbcode';
1217 $_asap = isset($method['asap']) ? array('asap' => TRUE) : array();
1218 $result = area_pickup($target, array($key => TRUE) + $_asap);
1220 $sum[$key] = $result[$key];
1221 if (isset($method[$key]) && $sum[$key] > $method[$key]) {
1222 $is_spam[$key] = TRUE;
1228 if ($asap && $is_spam) return $progress;
1231 $pickups = uri_pickup_normalize(spam_uri_pickup($target, $method));
1234 if (empty($pickups)) return $progress;
1236 // URI: Check quantity
1237 $sum['quantity'] += count($pickups);
1239 if ((! $asap || ! $is_spam) && isset($method['quantity']) &&
1240 $sum['quantity'] > $method['quantity']) {
1241 $is_spam['quantity'] = TRUE;
1244 // URI: used inside HTML anchor tag pair
1245 if ((! $asap || ! $is_spam) && isset($method['uri_anchor'])) {
1246 $key = 'uri_anchor';
1247 foreach($pickups as $pickup) {
1248 if (isset($pickup['area'][$key])) {
1249 $sum[$key] += $pickup['area'][$key];
1250 if(isset($method[$key]) &&
1251 $sum[$key] > $method[$key]) {
1252 $is_spam[$key] = TRUE;
1253 if ($asap && $is_spam) break;
1255 if ($asap && $is_spam) break;
1260 // URI: used inside 'BBCode' pair
1261 if ((! $asap || ! $is_spam) && isset($method['uri_bbcode'])) {
1262 $key = 'uri_bbcode';
1263 foreach($pickups as $pickup) {
1264 if (isset($pickup['area'][$key])) {
1265 $sum[$key] += $pickup['area'][$key];
1266 if(isset($method[$key]) &&
1267 $sum[$key] > $method[$key]) {
1268 $is_spam[$key] = TRUE;
1269 if ($asap && $is_spam) break;
1271 if ($asap && $is_spam) break;
1276 // URI: Uniqueness (and removing non-uniques)
1277 if ((! $asap || ! $is_spam) && isset($method['non_uniquri'])) {
1280 foreach (array_keys($pickups) as $key) {
1281 $uris[$key] = uri_pickup_implode($pickups[$key]);
1283 $count = count($uris);
1284 $uris = array_unique($uris);
1285 $sum['non_uniquri'] += $count - count($uris);
1286 if ($sum['non_uniquri'] > $method['non_uniquri']) {
1287 $is_spam['non_uniquri'] = TRUE;
1289 if (! $asap || ! $is_spam) {
1290 foreach (array_diff(array_keys($pickups),
1291 array_keys($uris)) as $remove) {
1292 unset($pickups[$remove]);
1299 if ($asap && $is_spam) return $progress;
1301 // Host: Uniqueness (uniq / non-uniq)
1302 foreach ($pickups as $pickup) $hosts[] = & $pickup['host'];
1303 $hosts = array_unique($hosts);
1304 $sum['uniqhost'] += count($hosts);
1305 if ((! $asap || ! $is_spam) && isset($method['non_uniqhost'])) {
1306 $sum['non_uniqhost'] = $sum['quantity'] - $sum['uniqhost'];
1307 if ($sum['non_uniqhost'] > $method['non_uniqhost']) {
1308 $is_spam['non_uniqhost'] = TRUE;
1313 if ($asap && $is_spam) return $progress;
1315 // URI: Bad host (Separate good/bad hosts from $hosts)
1316 if ((! $asap || ! $is_spam) && isset($method['badhost'])) {
1319 $list = get_blocklist('list');
1320 $blocked = blocklist_distiller($hosts, array_keys($list), $asap);
1321 foreach($list as $key=>$type){
1322 if (! $type) unset($blocked[$key]); // Ignore goodhost etc
1326 if (! empty($blocked)) $is_spam['badhost'] = TRUE;
1332 // Count leaves (A leaf = value that is not an array, or an empty array)
1333 function array_count_leaves($array = array(), $count_empty = FALSE)
1335 if (! is_array($array) || (empty($array) && $count_empty)) return 1;
1339 foreach ($array as $part) {
1340 $count += array_count_leaves($part, $count_empty);
1345 // Merge two leaves' value
1346 function array_merge_leaves(& $array1, & $array2, $unique_values = TRUE, $renumber_numeric = TRUE)
1348 $array = array_merge_recursive($array1, $array2);
1350 // Redundant values (and keys) are vanished
1351 if ($unique_values) $array = array_unique_recursive($array);
1353 // All NUMERIC keys are always renumbered from 0
1354 if ($renumber_numeric) array_renumber_numeric_keys($array);
1360 // ---------------------
1363 // TODO: Don't show unused $method!
1364 // Summarize $progress (blocked only)
1365 function summarize_spam_progress($progress = array(), $blockedonly = FALSE)
1368 $tmp = array_keys($progress['is_spam']);
1371 $method = & $progress['method'];
1372 if (isset($progress['sum'])) {
1373 foreach ($progress['sum'] as $key => $value) {
1374 if (isset($method[$key]) && $value) {
1375 $tmp[] = $key . '(' . $value . ')';
1381 return implode(', ', $tmp);
1384 // Very roughly, shrink the lines of var_export()
1385 // NOTE: If the same data exists, it must be corrupted.
1386 function var_export_shrink($expression, $return = FALSE)
1388 $result =preg_replace(
1389 // Remove a newline and spaces
1390 '# => \n *array \(#', ' => array (',
1391 var_export($expression, TRUE)
1402 function summarize_detail_badhost($progress = array())
1404 if (! isset($progress['is_spam']['badhost'])) return '';
1406 return var_export_shrink($progress['blocked'], TRUE);
1409 // Reverse $string with specified delimiter
1410 function delimiter_reverse($string = 'foo.bar.example.com', $from_delim = '.', $to_delim = '.')
1412 if (! is_string($string) || ! is_string($from_delim) || ! is_string($to_delim))
1415 // com.example.bar.foo
1416 return implode($to_delim, array_reverse(explode($from_delim, $string)));
1419 function summarize_detail_newtral($progress = array())
1421 if (! isset($progress['hosts']) ||
1422 ! is_array($progress['hosts']) ||
1423 empty($progress['hosts'])) return '';
1427 foreach($progress['hosts'] as $value) {
1428 $tmp[delimiter_reverse($value)] = $value;
1432 return count($tmp) . ' (' .implode(', ', $tmp) . ')';
1436 // ---------------------
1439 // Common bahavior for blocking
1440 // NOTE: Call this function from various blocking feature, to disgueise the reason 'why blocked'
1441 function spam_exit($mode = '', $data = array())
1444 case '': echo("\n"); break;
1446 echo('<pre>' . "\n");
1447 echo htmlspecialchars(var_export($data, TRUE));
1448 echo('</pre>' . "\n");
1457 // ---------------------
1460 // TODO: Record them
1461 // Simple/fast spam filter ($target: 'a string' or an array())
1462 function pkwk_spamfilter($action, $page, $target = array('title' => ''), $method = array(), $exitmode = '')
1464 $progress = check_uri_spam($target, $method);
1466 if (! empty($progress['is_spam'])) {
1467 // Mail to administrator(s)
1468 pkwk_spamnotify($action, $page, $target, $progress, $method);
1471 spam_exit($exitmode, $progress);
1475 // ---------------------
1476 // PukiWiki original
1478 // Mail to administrator(s)
1479 function pkwk_spamnotify($action, $page, $target = array('title' => ''), $progress = array(), $method = array())
1481 global $notify, $notify_subject;
1483 if (! $notify) return;
1485 $asap = isset($method['asap']);
1487 $summary['ACTION'] = 'Blocked by: ' . summarize_spam_progress($progress, TRUE);
1489 $summary['METRICS'] = summarize_spam_progress($progress);
1492 $tmp = summarize_detail_badhost($progress);
1493 if ($tmp != '') $summary['DETAIL_BADHOST'] = $tmp;
1495 $tmp = summarize_detail_newtral($progress);
1496 if (! $asap && $tmp != '') $summary['DETAIL_NEUTRAL_HOST'] = $tmp;
1498 $summary['COMMENT'] = $action;
1499 $summary['PAGE'] = '[blocked] ' . (is_pagename($page) ? $page : '');
1500 $summary['URI'] = get_script_uri() . '?' . rawurlencode($page);
1501 $summary['USER_AGENT'] = TRUE;
1502 $summary['REMOTE_ADDR'] = TRUE;
1503 pkwk_mail_notify($notify_subject, var_export($target, TRUE), $summary, TRUE);