2 // $Id: spam.php,v 1.161 2007/05/13 04:50:09 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));
42 // Very roughly, shrink the lines of var_export()
43 // NOTE: If the same data exists, it must be corrupted.
44 function var_export_shrink($expression, $return = FALSE, $ignore_numeric_keys = FALSE)
46 $result =preg_replace(
47 // Remove a newline and spaces
48 '# => \n *array \(#', ' => array (',
49 var_export($expression, TRUE)
52 if ($ignore_numeric_keys) {
53 $result =preg_replace(
54 // Remove numeric keys
55 '#^( *)[0-9]+ => #m', '$1',
68 // Remove redundant values from array()
69 function array_unique_recursive($array = array())
71 if (! is_array($array)) return $array;
74 foreach($array as $key => $value){
75 if (is_array($value)) {
76 $array[$key] = array_unique_recursive($value);
78 if (isset($tmp[$value])) {
89 // Renumber all numeric keys from 0
90 function array_renumber_numeric_keys(& $array)
92 if (! is_array($array)) return $array;
96 foreach($array as $key => $value){
97 if (is_array($value)) array_renumber_numeric_keys($array[$key]); // Recurse
98 if (is_numeric($key)) $tmp[$key] = ++$count;
100 array_rename_keys($array, $tmp);
105 // Roughly strings(1) using PCRE
106 // This function is useful to:
107 // * Reduce the size of data, from removing unprintable binary data
108 // * Detect _bare_strings_ from binary data
110 // http://www.freebsd.org/cgi/man.cgi?query=strings (Man-page of GNU strings)
111 // http://www.pcre.org/pcre.txt
112 function strings($binary = '', $min_len = 4, $ignore_space = FALSE)
115 $binary = preg_replace(
117 '/(?:[^[:graph:] \t\n]|[\r])+/s',
130 $binary = preg_replace('/(?:[^[:graph:][:space:]]|[\r])+/s', "\n", $binary);
134 $min_len = min(1024, intval($min_len));
137 preg_grep('/^.{' . $min_len . ',}/S',
138 explode("\n", $binary)
146 // Reverse $string with specified delimiter
147 function delimiter_reverse($string = 'foo.bar.example.com', $from_delim = '.', $to_delim = '.')
149 if (! is_string($string) || ! is_string($from_delim) || ! is_string($to_delim))
152 // com.example.bar.foo
153 return implode($to_delim, array_reverse(explode($from_delim, $string)));
157 // ---------------------
160 // Return an array of URIs in the $string
161 // [OK] http://nasty.example.org#nasty_string
162 // [OK] http://nasty.example.org:80/foo/xxx#nasty_string/bar
163 // [OK] ftp://nasty.example.org:80/dfsdfs
164 // [OK] ftp://cnn.example.com&story=breaking_news@10.0.0.1/top_story.htm (from RFC3986)
165 function uri_pickup($string = '')
167 if (! is_string($string)) return array();
169 // Not available for: IDN(ignored)
172 // scheme://userinfo@host:port/path/or/pathinfo/maybefile.and?query=string#fragment
173 // Refer RFC3986 (Regex below is not strict)
174 '#(\b[a-z][a-z0-9.+-]{1,8}):/+' . // 1: Scheme
176 '([^\s<>"\'\[\]/\#?@]*)' . // 2: Userinfo (Username)
180 '\[[0-9a-f:.]+\]' . '|' . // IPv6([colon-hex and dot]): RFC2732
181 '(?:[0-9]{1,3}\.){3}[0-9]{1,3}' . '|' . // IPv4(dot-decimal): 001.22.3.44
182 '[a-z0-9][a-z0-9.-]+[a-z0-9]' . // hostname(FQDN) : foo.example.org
184 '(?::([0-9]*))?' . // 4: Port
185 '((?:/+[^\s<>"\'\[\]/\#]+)*/+)?' . // 5: Directory path or path-info
186 '([^\s<>"\'\[\]\#?]+)?' . // 6: File?
187 '(?:\?([^\s<>"\'\[\]\#]+))?' . // 7: Query string
188 '(?:\#([a-z0-9._~%!$&\'()*+,;=:@-]*))?' . // 8: Fragment
190 $string, $array, PREG_SET_ORDER | PREG_OFFSET_CAPTURE
194 static $parts = array(
195 1 => 'scheme', 2 => 'userinfo', 3 => 'host', 4 => 'port',
196 5 => 'path', 6 => 'file', 7 => 'query', 8 => 'fragment'
198 $default = array('');
199 foreach(array_keys($array) as $uri) {
200 $_uri = & $array[$uri];
201 array_rename_keys($_uri, $parts, TRUE, $default);
202 $offset = $_uri['scheme'][1]; // Scheme's offset = URI's offset
203 foreach(array_keys($_uri) as $part) {
204 $_uri[$part] = & $_uri[$part][0]; // Remove offsets
208 foreach(array_keys($array) as $uri) {
209 $_uri = & $array[$uri];
210 if ($_uri['scheme'] === '') {
211 unset($array[$uri]); // Considererd harmless
214 unset($_uri[0]); // Matched string itself
215 $_uri['area']['offset'] = $offset; // Area offset for area_measure()
221 // Normalize an array of URI arrays
222 // NOTE: Give me the uri_pickup() results
223 function uri_pickup_normalize(& $pickups, $destructive = TRUE)
225 if (! is_array($pickups)) return $pickups;
228 foreach (array_keys($pickups) as $key) {
229 $_key = & $pickups[$key];
230 $_key['scheme'] = isset($_key['scheme']) ? scheme_normalize($_key['scheme']) : '';
231 $_key['host'] = isset($_key['host']) ? host_normalize($_key['host']) : '';
232 $_key['port'] = isset($_key['port']) ? port_normalize($_key['port'], $_key['scheme'], FALSE) : '';
233 $_key['path'] = isset($_key['path']) ? strtolower(path_normalize($_key['path'])) : '';
234 $_key['file'] = isset($_key['file']) ? file_normalize($_key['file']) : '';
235 $_key['query'] = isset($_key['query']) ? query_normalize($_key['query']) : '';
236 $_key['fragment'] = isset($_key['fragment']) ? strtolower($_key['fragment']) : '';
239 foreach (array_keys($pickups) as $key) {
240 $_key = & $pickups[$key];
241 $_key['scheme'] = isset($_key['scheme']) ? scheme_normalize($_key['scheme']) : '';
242 $_key['host'] = isset($_key['host']) ? strtolower($_key['host']) : '';
243 $_key['port'] = isset($_key['port']) ? port_normalize($_key['port'], $_key['scheme'], FALSE) : '';
244 $_key['path'] = isset($_key['path']) ? path_normalize($_key['path']) : '';
251 // An URI array => An URI (See uri_pickup())
253 // $pickups = uri_pickup('a string include some URIs');
255 // foreach (array_keys($pickups) as $key) {
256 // $uris[$key] = uri_pickup_implode($pickups[$key]);
258 function uri_pickup_implode($uri = array())
260 if (empty($uri) || ! is_array($uri)) return NULL;
263 if (isset($uri['scheme']) && $uri['scheme'] !== '') {
264 $tmp[] = & $uri['scheme'];
267 if (isset($uri['userinfo']) && $uri['userinfo'] !== '') {
268 $tmp[] = & $uri['userinfo'];
271 if (isset($uri['host']) && $uri['host'] !== '') {
272 $tmp[] = & $uri['host'];
274 if (isset($uri['port']) && $uri['port'] !== '') {
276 $tmp[] = & $uri['port'];
278 if (isset($uri['path']) && $uri['path'] !== '') {
279 $tmp[] = & $uri['path'];
281 if (isset($uri['file']) && $uri['file'] !== '') {
282 $tmp[] = & $uri['file'];
284 if (isset($uri['query']) && $uri['query'] !== '') {
286 $tmp[] = & $uri['query'];
288 if (isset($uri['fragment']) && $uri['fragment'] !== '') {
290 $tmp[] = & $uri['fragment'];
293 return implode('', $tmp);
296 // $array['something'] => $array['wanted']
297 function array_rename_keys(& $array, $keys = array('from' => 'to'), $force = FALSE, $default = '')
299 if (! is_array($array) || ! is_array($keys)) return FALSE;
301 // Nondestructive test
303 foreach(array_keys($keys) as $from)
304 if (! isset($array[$from]))
307 foreach($keys as $from => $to) {
308 if ($from === $to) continue;
309 if (! $force || isset($array[$from])) {
310 $array[$to] = & $array[$from];
311 unset($array[$from]);
313 $array[$to] = $default;
320 // ---------------------
323 // Pickup all of markup areas
324 function area_pickup($string = '', $method = array())
327 if (empty($method)) return $area;
329 // Anchor tag pair by preg_match and preg_match_all()
331 // [OK] <a href= >Good site!</a>
332 // [OK] <a href= "#" >test</a>
333 // [OK] <a href="http://nasty.example.com">visit http://nasty.example.com/</a>
334 // [OK] <a href=\'http://nasty.example.com/\' >discount foobar</a>
335 // [NG] <a href="http://ng.example.com">visit http://ng.example.com _not_ended_
336 $regex = '#<a\b[^>]*\bhref\b[^>]*>.*?</a\b[^>]*(>)#is';
337 if (isset($method['area_anchor'])) {
339 $count = isset($method['asap']) ?
340 preg_match($regex, $string) :
341 preg_match_all($regex, $string, $areas);
342 if (! empty($count)) $area['area_anchor'] = $count;
344 if (isset($method['uri_anchor'])) {
346 preg_match_all($regex, $string, $areas, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
347 foreach(array_keys($areas) as $_area) {
348 $areas[$_area] = array(
349 $areas[$_area][0][1], // Area start (<a href>)
350 $areas[$_area][1][1], // Area end (</a>)
353 if (! empty($areas)) $area['uri_anchor'] = $areas;
356 // phpBB's "BBCode" pair by preg_match and preg_match_all()
358 // [OK] [url]http://nasty.example.com/[/url]
359 // [OK] [link]http://nasty.example.com/[/link]
360 // [OK] [url=http://nasty.example.com]visit http://nasty.example.com/[/url]
361 // [OK] [link http://nasty.example.com/]buy something[/link]
362 $regex = '#\[(url|link)\b[^\]]*\].*?\[/\1\b[^\]]*(\])#is';
363 if (isset($method['area_bbcode'])) {
365 $count = isset($method['asap']) ?
366 preg_match($regex, $string) :
367 preg_match_all($regex, $string, $areas, PREG_SET_ORDER);
368 if (! empty($count)) $area['area_bbcode'] = $count;
370 if (isset($method['uri_bbcode'])) {
372 preg_match_all($regex, $string, $areas, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
373 foreach(array_keys($areas) as $_area) {
374 $areas[$_area] = array(
375 $areas[$_area][0][1], // Area start ([url])
376 $areas[$_area][2][1], // Area end ([/url])
379 if (! empty($areas)) $area['uri_bbcode'] = $areas;
382 // Various Wiki syntax
383 // [text_or_uri>text_or_uri]
384 // [text_or_uri:text_or_uri]
385 // [text_or_uri|text_or_uri]
386 // [text_or_uri->text_or_uri]
387 // [text_or_uri text_or_uri] // MediaWiki
388 // MediaWiki: [http://nasty.example.com/ visit http://nasty.example.com/]
393 // If in doubt, it's a little doubtful
394 // if (Area => inside <= Area) $brief += -1
395 function area_measure($areas, & $array, $belief = -1, $a_key = 'area', $o_key = 'offset')
397 if (! is_array($areas) || ! is_array($array)) return;
399 $areas_keys = array_keys($areas);
400 foreach(array_keys($array) as $u_index) {
401 $offset = isset($array[$u_index][$o_key]) ?
402 intval($array[$u_index][$o_key]) : 0;
403 foreach($areas_keys as $a_index) {
404 if (isset($array[$u_index][$a_key])) {
405 $offset_s = intval($areas[$a_index][0]);
406 $offset_e = intval($areas[$a_index][1]);
407 // [Area => inside <= Area]
408 if ($offset_s < $offset && $offset < $offset_e) {
409 $array[$u_index][$a_key] += $belief;
416 // ---------------------
419 // Domain exposure callback (See spam_uri_pickup_preprocess())
420 // http://victim.example.org/?foo+site:nasty.example.com+bar
421 // => http://nasty.example.com/?refer=victim.example.org
422 // NOTE: 'refer=' is not so good for (at this time).
423 // Consider about using IP address of the victim, try to avoid that.
424 function _preg_replace_callback_domain_exposure($matches = array())
428 // Preserve the victim URI as a complicity or ...
429 if (isset($matches[5])) {
431 $matches[1] . '://' . // scheme
432 $matches[2] . '/' . // victim.example.org
433 $matches[3]; // The rest of all (before victim)
437 if (isset($matches[4])) {
439 $matches[1] . '://' . // scheme
440 $matches[4] . // nasty.example.com
441 '/?refer=' . strtolower($matches[2]) . // victim.example.org
448 // Preprocess: rawurldecode() and adding space(s) and something
449 // to detect/count some URIs _if possible_
450 // NOTE: It's maybe danger to var_dump(result). [e.g. 'javascript:']
451 // [OK] http://victim.example.org/?site:nasty.example.org
452 // [OK] http://victim.example.org/nasty.example.org
453 // [OK] http://victim.example.org/go?http%3A%2F%2Fnasty.example.org
454 // [OK] http://victim.example.org/http://nasty.example.org
455 function spam_uri_pickup_preprocess($string = '')
457 if (! is_string($string)) return '';
459 $string = rawurldecode($string);
461 // Domain exposure (simple)
462 // http://victim.example.org/nasty.example.org/path#frag
463 // => http://nasty.example.org/?refer=victim.example.org and original
464 $string = preg_replace(
467 'ime\.nu' . '|' . // 2ch.net
468 'ime\.st' . '|' . // 2ch.net
469 'link\.toolbot\.com' . '|' .
472 '/([a-z0-9.%_-]+\.[a-z0-9.%_-]+)#i', // nasty.example.org
473 'http://$2/?refer=$1 $0', // Preserve $0 or remove?
477 // Domain exposure (gate-big5)
478 // http://victim.example.org/gate/big5/nasty.example.org/path
479 // => http://nasty.example.org/?refer=victim.example.org and original
480 $string = preg_replace(
483 'big5.51job.com' . '|' .
484 'big5.china.com' . '|' .
485 'big5.xinhuanet.com' . '|' .
488 '/([a-z0-9.%_-]+\.[a-z0-9.%_-]+)' .
489 '#i', // nasty.example.org
490 'http://$2/?refer=$1 $0', // Preserve $0 or remove?
494 // Domain exposure (See _preg_replace_callback_domain_exposure())
495 $string = preg_replace_callback(
499 // Something Google: http://www.google.com/supported_domains
500 '(?:[a-z0-9.]+\.)?google\.[a-z]{2,3}(?:\.[a-z]{2})?' .
503 '(?:[a-z0-9.]+\.)?altavista.com' .
507 '([a-z0-9?=&.%_/\'\\\+-]+)' . // path/?query=foo+bar+
508 '\bsite:([a-z0-9.%_-]+\.[a-z0-9.%_-]+)' . // site:nasty.example.com
509 //'()' . // Preserve or remove?
512 '_preg_replace_callback_domain_exposure',
516 // URI exposure (uriuri => uri uri)
517 $string = preg_replace(
519 '#(?<! )(?:https?|ftp):/#i',
520 // '#[a-z][a-z0-9.+-]{1,8}://#i',
521 // '#[a-z][a-z0-9.+-]{1,8}://#i'
530 // Main function of spam-uri pickup,
531 // A wrapper function of uri_pickup()
532 function spam_uri_pickup($string = '', $method = array())
534 if (! is_array($method) || empty($method)) {
535 $method = check_uri_spam_method();
538 $string = spam_uri_pickup_preprocess($string);
540 $array = uri_pickup($string);
542 // Area elevation of URIs, for '(especially external)link' intension
543 if (! empty($array)) {
545 if (isset($method['uri_anchor'])) $_method['uri_anchor'] = & $method['uri_anchor'];
546 if (isset($method['uri_bbcode'])) $_method['uri_bbcode'] = & $method['uri_bbcode'];
547 $areas = area_pickup($string, $_method, TRUE);
548 if (! empty($areas)) {
549 $area_shadow = array();
550 foreach (array_keys($array) as $key) {
551 $area_shadow[$key] = & $array[$key]['area'];
552 foreach (array_keys($_method) as $_key) {
553 $area_shadow[$key][$_key] = 0;
556 foreach (array_keys($_method) as $_key) {
557 if (isset($areas[$_key])) {
558 area_measure($areas[$_key], $area_shadow, 1, $_key);
564 // Remove 'offset's for area_measure()
565 foreach(array_keys($array) as $key)
566 unset($array[$key]['area']['offset']);
572 // ---------------------
575 // Scheme normalization: Renaming the schemes
576 // snntp://example.org => nntps://example.org
577 // NOTE: Keep the static lists simple. See also port_normalize().
578 function scheme_normalize($scheme = '', $abbrevs_harmfull = TRUE)
580 // Abbreviations they have no intention of link
581 static $abbrevs = array(
586 // Aliases => normalized ones
587 static $aliases = array(
597 if (! is_string($scheme)) return '';
599 $scheme = strtolower($scheme);
600 if (isset($abbrevs[$scheme])) {
601 $scheme = $abbrevs_harmfull ? $abbrevs[$scheme] : '';
603 if (isset($aliases[$scheme])) {
604 $scheme = $aliases[$scheme];
610 // Hostname normlization (Destructive)
611 // www.foo => www.foo ('foo' seems TLD)
612 // www.foo.bar => foo.bar
613 // www.10.20 => www.10.20 (Invalid hostname)
615 // 'www' is mostly used as traditional hostname of WWW server.
616 // 'www.foo.bar' may be identical with 'foo.bar'.
617 function host_normalize($host = '')
619 if (! is_string($host)) return '';
621 $host = strtolower($host);
623 if (preg_match('/^www\.(.+\.[a-z]+)$/', $host, $matches)) {
630 // Port normalization: Suppress the (redundant) default port
631 // HTTP://example.org:80/ => http://example.org/
632 // HTTP://example.org:8080/ => http://example.org:8080/
633 // HTTPS://example.org:443/ => https://example.org/
634 function port_normalize($port, $scheme, $scheme_normalize = FALSE)
636 // Schemes that users _maybe_ want to add protocol-handlers
637 // to their web browsers. (and attackers _maybe_ want to use ...)
638 // Reference: http://www.iana.org/assignments/port-numbers
639 static $array = array(
640 // scheme => default port
666 // intval() converts '0-1' to '0', so preg_match() rejects these invalid ones
667 if (! is_numeric($port) || $port < 0 || preg_match('/[^0-9]/i', $port))
670 $port = intval($port);
671 if ($scheme_normalize) $scheme = scheme_normalize($scheme);
672 if (isset($array[$scheme]) && $port == $array[$scheme])
673 $port = ''; // Ignore the defaults
678 // Path normalization
679 // http://example.org => http://example.org/
680 // http://example.org#hoge => http://example.org/#hoge
681 // http://example.org/path/a/b/./c////./d => http://example.org/path/a/b/c/d
682 // http://example.org/path/../../a/../back => http://example.org/back
683 function path_normalize($path = '', $divider = '/', $add_root = TRUE)
685 if (! is_string($divider)) return is_string($path) ? $path : '';
688 $first_div = & $divider;
692 if (! is_string($path) || $path == '') return $first_div;
694 if (strpos($path, $divider, strlen($path) - strlen($divider)) === FALSE) {
697 $last_div = & $divider;
700 $array = explode($divider, $path);
702 // Remove paddings ('//' and '/./')
703 foreach(array_keys($array) as $key) {
704 if ($array[$key] == '' || $array[$key] == '.') {
709 // Remove back-tracks ('/../')
711 foreach($array as $value) {
712 if ($value == '..') {
715 array_push($tmp, $value);
723 return $first_div . implode($divider, $array) . $last_div;
727 // DirectoryIndex normalize (Destructive and rough)
728 // TODO: sample.en.ja.html.gz => sample.html
729 function file_normalize($file = 'index.html.en')
731 static $simple_defaults = array(
732 'default.htm' => TRUE,
733 'default.html' => TRUE,
734 'default.asp' => TRUE,
735 'default.aspx' => TRUE,
736 'index' => TRUE, // Some system can omit the suffix
739 static $content_suffix = array(
740 // index.xxx, sample.xxx
755 static $language_suffix = array(
756 // Reference: Apache 2.0.59 'AddLanguage' default
785 // Reference: Apache 2.0.59 default 'index.html' variants
791 static $charset_suffix = array(
792 // Reference: Apache 2.0.59 'AddCharset' default
793 'iso8859-1' => TRUE, // ISO-8859-1
794 'latin1' => TRUE, // ISO-8859-1
795 'iso8859-2' => TRUE, // ISO-8859-2
796 'latin2' => TRUE, // ISO-8859-2
797 'cen' => TRUE, // ISO-8859-2
798 'iso8859-3' => TRUE, // ISO-8859-3
799 'latin3' => TRUE, // ISO-8859-3
800 'iso8859-4' => TRUE, // ISO-8859-4
801 'latin4' => TRUE, // ISO-8859-4
802 'iso8859-5' => TRUE, // ISO-8859-5
803 'latin5' => TRUE, // ISO-8859-5
804 'cyr' => TRUE, // ISO-8859-5
805 'iso-ru' => TRUE, // ISO-8859-5
806 'iso8859-6' => TRUE, // ISO-8859-6
807 'latin6' => TRUE, // ISO-8859-6
808 'arb' => TRUE, // ISO-8859-6
809 'iso8859-7' => TRUE, // ISO-8859-7
810 'latin7' => TRUE, // ISO-8859-7
811 'grk' => TRUE, // ISO-8859-7
812 'iso8859-8' => TRUE, // ISO-8859-8
813 'latin8' => TRUE, // ISO-8859-8
814 'heb' => TRUE, // ISO-8859-8
815 'iso8859-9' => TRUE, // ISO-8859-9
816 'latin9' => TRUE, // ISO-8859-9
817 'trk' => TRUE, // ISO-8859-9
818 'iso2022-jp'=> TRUE, // ISO-2022-JP
819 'jis' => TRUE, // ISO-2022-JP
820 'iso2022-kr'=> TRUE, // ISO-2022-KR
821 'kis' => TRUE, // ISO-2022-KR
822 'iso2022-cn'=> TRUE, // ISO-2022-CN
823 'cis' => TRUE, // ISO-2022-CN
825 'cp-1251' => TRUE, // ru, WINDOWS-1251
826 'win-1251' => TRUE, // ru, WINDOWS-1251
827 'cp866' => TRUE, // ru
828 'koi8-r' => TRUE, // ru, KOI8-r
829 'koi8-ru' => TRUE, // ru, KOI8-r
830 'koi8-uk' => TRUE, // ru, KOI8-ru
831 'ua' => TRUE, // ru, KOI8-ru
832 'ucs2' => TRUE, // ru, ISO-10646-UCS-2
833 'ucs4' => TRUE, // ru, ISO-10646-UCS-4
836 // Reference: Apache 2.0.59 default 'index.html' variants
841 // May uncompress by web browsers on the fly
842 // Must be at the last of the filename
843 // Reference: Apache 2.0.59 'AddEncoding'
844 static $encoding_suffix = array(
849 if (! is_string($file)) return '';
850 $_file = strtolower($file);
851 if (isset($simple_defaults[$_file])) return '';
854 // Roughly removing language/character-set/encoding suffixes
856 // * Apache 2 document about 'Content-negotiaton', 'mod_mime' and 'mod_negotiation'
857 // http://httpd.apache.org/docs/2.0/content-negotiation.html
858 // http://httpd.apache.org/docs/2.0/mod/mod_mime.html
859 // http://httpd.apache.org/docs/2.0/mod/mod_negotiation.html
860 // * http://www.iana.org/assignments/character-sets
861 // * RFC3066: Tags for the Identification of Languages
862 // http://www.ietf.org/rfc/rfc3066.txt
863 // * ISO 639: codes of 'language names'
864 $suffixes = explode('.', $_file);
865 $body = array_shift($suffixes);
867 // Remove the last .gz/.z
868 $last_key = end(array_keys($suffixes));
869 if (isset($encoding_suffix[$suffixes[$last_key]])) {
870 unset($suffixes[$last_key]);
873 // Cut language and charset suffixes
874 foreach($suffixes as $key => $value){
875 if (isset($language_suffix[$value]) || isset($charset_suffix[$value])) {
876 unset($suffixes[$key]);
879 if (empty($suffixes)) return $body;
882 $count = count($suffixes);
884 $current = current($suffixes);
885 if ($body == 'index' && $count == 1 && isset($content_suffix[$current])) return '';
890 // Sort query-strings if possible (Destructive and rough)
891 // [OK] &&&&f=d&b&d&c&a=0dd => a=0dd&b&c&d&f=d
892 // [OK] nothing==&eg=dummy&eg=padding&eg=foobar => eg=foobar
893 function query_normalize($string = '', $equal = TRUE, $equal_cutempty = TRUE, $stortolower = TRUE)
895 if (! is_string($string)) return '';
896 if ($stortolower) $string = strtolower($string);
898 $array = explode('&', $string);
900 // Remove '&' paddings
901 foreach(array_keys($array) as $key) {
902 if ($array[$key] == '') {
907 // Consider '='-sepalated input and paddings
909 $equals = $not_equals = array();
910 foreach ($array as $part) {
911 if (strpos($part, '=') === FALSE) {
912 $not_equals[] = $part;
914 list($key, $value) = explode('=', $part, 2);
915 $value = ltrim($value, '=');
916 if (! $equal_cutempty || $value != '') {
917 $equals[$key] = $value;
922 $array = & $not_equals;
923 foreach ($equals as $key => $value) {
924 $array[] = $key . '=' . $value;
930 return implode('&', $array);
933 // ---------------------
934 // Part One : Checker
936 // Rough implementation of globbing
938 // USAGE: $regex = '/^' . generate_glob_regex('*.txt', '/') . '$/i';
940 function generate_glob_regex($string = '', $divider = '/')
942 static $from = array(
945 // 22 => '[', // Maybe cause regex compilation error (e.g. '[]')
961 if (! is_string($string)) return '';
963 $string = str_replace($from, $mid, $string); // Hide
964 $string = preg_quote($string, $divider);
965 $string = str_replace($mid, $to, $string); // Unhide
970 // Rough hostname checker
972 // TODO: Strict digit, 0x, CIDR, IPv6
973 function is_ip($string = '')
975 if (preg_match('/^' .
976 '(?:[0-9]{1,3}\.){3}[0-9]{1,3}' . '|' .
977 '(?:[0-9]{1,3}\.){1,3}' . '$/',
979 return 4; // Seems IPv4(dot-decimal)
981 return 0; // Seems not IP
985 // Generate host (FQDN, IPv4, ...) regex
986 // 'localhost' : Matches with 'localhost' only
987 // 'example.org' : Matches with 'example.org' only (See host_normalize() about 'www')
988 // '.example.org' : Matches with ALL FQDN ended with '.example.org'
989 // '*.example.org' : Almost the same of '.example.org' except 'www.example.org'
990 // '10.20.30.40' : Matches with IPv4 address '10.20.30.40' only
991 // [TODO] '192.' : Matches with all IPv4 hosts started with '192.'
992 // TODO: IPv4, CIDR?, IPv6
993 function generate_host_regex($string = '', $divider = '/')
995 if (! is_string($string)) return '';
997 if (mb_strpos($string, '.') === FALSE)
998 return generate_glob_regex($string, $divider);
1001 if (is_ip($string)) {
1003 return generate_glob_regex($string, $divider);
1005 // FQDN or something
1006 $part = explode('.', $string, 2);
1007 if ($part[0] == '') {
1008 $part[0] = '(?:.*\.)?'; // And all related FQDN
1009 } else if ($part[0] == '*') {
1010 $part[0] = '.*\.'; // All subdomains/hosts only
1012 return generate_glob_regex($string, $divider);
1014 $part[1] = generate_glob_regex($part[1], $divider);
1015 return implode('', $part);
1019 function get_blocklist($list = '')
1023 if (! isset($regexs)) {
1025 if (file_exists(SPAM_INI_FILE)) {
1026 $blocklist = array();
1027 include(SPAM_INI_FILE);
1028 // $blocklist['badhost'] = array(
1029 // '*.blogspot.com', // Blog services's subdomains (only)
1030 // 'IANA-examples' => '#^(?:.*\.)?example\.(?:com|net|org)$#',
1032 if (isset($blocklist['list'])) {
1033 $regexs['list'] = & $blocklist['list'];
1036 $blocklist['list'] = array(
1037 'goodhost' => FALSE,
1041 foreach(array_keys($blocklist['list']) as $_list) {
1042 if (! isset($blocklist[$_list])) continue;
1043 foreach ($blocklist[$_list] as $key => $value) {
1044 if (is_array($value)) {
1045 $regexs[$_list][$key] = array();
1046 foreach($value as $_key => $_value) {
1047 get_blocklist_add($regexs[$_list][$key], $_key, $_value);
1050 get_blocklist_add($regexs[$_list], $key, $value);
1053 unset($blocklist[$_list]);
1059 return $regexs; // ALL
1060 } else if (isset($regexs[$list])) {
1061 return $regexs[$list];
1067 // Subroutine of get_blocklist()
1068 function get_blocklist_add(& $array, $key = 0, $value = '*.example.org')
1070 if (is_string($key)) {
1071 $array[$key] = & $value; // Treat $value as a regex
1073 $array[$value] = '/^' . generate_host_regex($value, '/') . '$/i';
1077 // Blocklist metrics: Separate $host, to $blocked and not blocked
1078 function blocklist_distiller(& $hosts, $keys = array('goodhost', 'badhost'), $asap = FALSE)
1080 if (! is_array($hosts)) $hosts = array($hosts);
1081 if (! is_array($keys)) $keys = array($keys);
1083 $list = get_blocklist('list');
1086 foreach($keys as $key){
1087 foreach (get_blocklist($key) as $label => $regex) {
1088 if (is_array($regex)) {
1089 foreach($regex as $_label => $_regex) {
1090 $group = preg_grep($_regex, $hosts);
1092 $hosts = array_diff($hosts, $group);
1093 $blocked[$key][$label][$_label] = $group;
1094 if ($asap && $list[$key]) break;
1098 $group = preg_grep($regex, $hosts);
1100 $hosts = array_diff($hosts, $group);
1101 $blocked[$key][$label] = $group;
1102 if ($asap && $list[$key]) break;
1111 // Default (enabled) methods and thresholds (for content insertion)
1112 function check_uri_spam_method($times = 1, $t_area = 0, $rule = TRUE)
1114 $times = intval($times);
1115 $t_area = intval($t_area);
1119 'quantity' => 8 * $times, // Allow N URIs
1120 'non_uniqhost' => 3 * $times, // Allow N duped (and normalized) Hosts
1121 //'non_uniquri'=> 3 * $times, // Allow N duped (and normalized) URIs
1124 'area_anchor' => $t_area, // Using <a href> HTML tag
1125 'area_bbcode' => $t_area, // Using [url] or [link] BBCode
1126 //'uri_anchor' => $t_area, // URI inside <a href> HTML tag
1127 //'uri_bbcode' => $t_area, // URI inside [url] or [link] BBCode
1132 //'asap' => TRUE, // Quit or return As Soon As Possible
1133 'uniqhost' => TRUE, // Show uniq host (at block notification mail)
1134 'badhost' => TRUE, // Check badhost
1140 // Remove non-$positive values
1141 foreach (array_keys($positive) as $key) {
1142 if ($positive[$key] < 0) unset($positive[$key]);
1145 return $positive + $bool;
1148 // Simple/fast spam check
1149 function check_uri_spam($target = '', $method = array())
1154 // Theme to do => Dummy, optional value, or optional array()
1156 //'uniqhost' => TRUE,
1157 //'non_uniqhost'=> 3,
1158 //'non_uniquri' => 3,
1159 //'badhost' => TRUE,
1160 //'area_anchor' => 0,
1161 //'area_bbcode' => 0,
1162 //'uri_anchor' => 0,
1163 //'uri_bbcode' => 0,
1166 // Theme => Volume found (int)
1169 // Flag. If someting defined here,
1170 // one or more spam will be included
1175 //'category' => array(
1180 // Hosts not blocked
1185 $sum = & $progress['sum'];
1186 $is_spam = & $progress['is_spam'];
1187 $progress['method'] = & $method; // Argument
1188 $blocked = & $progress['blocked'];
1189 $hosts = & $progress['hosts'];
1190 $asap = isset($method['asap']);
1193 if (! is_array($method) || empty($method)) {
1194 $method = check_uri_spam_method();
1196 foreach(array_keys($method) as $key) {
1197 if (! isset($sum[$key])) $sum[$key] = 0;
1200 if (is_array($target)) {
1201 foreach($target as $str) {
1202 if (! is_string($str)) continue;
1204 $_progress = check_uri_spam($str, $method); // Recurse
1207 $_sum = & $_progress['sum'];
1208 foreach (array_keys($_sum) as $key) {
1209 if (! isset($sum[$key])) {
1210 $sum[$key] = & $_sum[$key];
1212 $sum[$key] += $_sum[$key];
1217 $_is_spam = & $_progress['is_spam'];
1218 foreach (array_keys($_is_spam) as $key) {
1219 $is_spam[$key] = TRUE;
1222 if ($asap && $is_spam) break;
1225 $blocked = array_merge_recursive($blocked, $_progress['blocked']);
1226 $hosts = array_merge_recursive($hosts, $_progress['hosts']);
1230 $blocked = array_unique_recursive($blocked);
1231 $hosts = array_unique_recursive($hosts);
1233 // Recount $sum['badhost']
1234 $sum['badhost'] = array_count_leaves($blocked);
1239 // Area: There's HTML anchor tag
1240 if ((! $asap || ! $is_spam) && isset($method['area_anchor'])) {
1241 $key = 'area_anchor';
1242 $_asap = isset($method['asap']) ? array('asap' => TRUE) : array();
1243 $result = area_pickup($target, array($key => TRUE) + $_asap);
1245 $sum[$key] = $result[$key];
1246 if (isset($method[$key]) && $sum[$key] > $method[$key]) {
1247 $is_spam[$key] = TRUE;
1252 // Area: There's 'BBCode' linking tag
1253 if ((! $asap || ! $is_spam) && isset($method['area_bbcode'])) {
1254 $key = 'area_bbcode';
1255 $_asap = isset($method['asap']) ? array('asap' => TRUE) : array();
1256 $result = area_pickup($target, array($key => TRUE) + $_asap);
1258 $sum[$key] = $result[$key];
1259 if (isset($method[$key]) && $sum[$key] > $method[$key]) {
1260 $is_spam[$key] = TRUE;
1266 if ($asap && $is_spam) return $progress;
1269 $pickups = uri_pickup_normalize(spam_uri_pickup($target, $method));
1272 if (empty($pickups)) return $progress;
1274 // URI: Check quantity
1275 $sum['quantity'] += count($pickups);
1277 if ((! $asap || ! $is_spam) && isset($method['quantity']) &&
1278 $sum['quantity'] > $method['quantity']) {
1279 $is_spam['quantity'] = TRUE;
1282 // URI: used inside HTML anchor tag pair
1283 if ((! $asap || ! $is_spam) && isset($method['uri_anchor'])) {
1284 $key = 'uri_anchor';
1285 foreach($pickups as $pickup) {
1286 if (isset($pickup['area'][$key])) {
1287 $sum[$key] += $pickup['area'][$key];
1288 if(isset($method[$key]) &&
1289 $sum[$key] > $method[$key]) {
1290 $is_spam[$key] = TRUE;
1291 if ($asap && $is_spam) break;
1293 if ($asap && $is_spam) break;
1298 // URI: used inside 'BBCode' pair
1299 if ((! $asap || ! $is_spam) && isset($method['uri_bbcode'])) {
1300 $key = 'uri_bbcode';
1301 foreach($pickups as $pickup) {
1302 if (isset($pickup['area'][$key])) {
1303 $sum[$key] += $pickup['area'][$key];
1304 if(isset($method[$key]) &&
1305 $sum[$key] > $method[$key]) {
1306 $is_spam[$key] = TRUE;
1307 if ($asap && $is_spam) break;
1309 if ($asap && $is_spam) break;
1314 // URI: Uniqueness (and removing non-uniques)
1315 if ((! $asap || ! $is_spam) && isset($method['non_uniquri'])) {
1318 foreach (array_keys($pickups) as $key) {
1319 $uris[$key] = uri_pickup_implode($pickups[$key]);
1321 $count = count($uris);
1322 $uris = array_unique($uris);
1323 $sum['non_uniquri'] += $count - count($uris);
1324 if ($sum['non_uniquri'] > $method['non_uniquri']) {
1325 $is_spam['non_uniquri'] = TRUE;
1327 if (! $asap || ! $is_spam) {
1328 foreach (array_diff(array_keys($pickups),
1329 array_keys($uris)) as $remove) {
1330 unset($pickups[$remove]);
1337 if ($asap && $is_spam) return $progress;
1339 // Host: Uniqueness (uniq / non-uniq)
1340 foreach ($pickups as $pickup) $hosts[] = & $pickup['host'];
1341 $hosts = array_unique($hosts);
1342 $sum['uniqhost'] += count($hosts);
1343 if ((! $asap || ! $is_spam) && isset($method['non_uniqhost'])) {
1344 $sum['non_uniqhost'] = $sum['quantity'] - $sum['uniqhost'];
1345 if ($sum['non_uniqhost'] > $method['non_uniqhost']) {
1346 $is_spam['non_uniqhost'] = TRUE;
1351 if ($asap && $is_spam) return $progress;
1353 // URI: Bad host (Separate good/bad hosts from $hosts)
1354 if ((! $asap || ! $is_spam) && isset($method['badhost'])) {
1357 $list = get_blocklist('list');
1358 $blocked = blocklist_distiller($hosts, array_keys($list), $asap);
1359 foreach($list as $key=>$type){
1360 if (! $type) unset($blocked[$key]); // Ignore goodhost etc
1364 if (! empty($blocked)) $is_spam['badhost'] = TRUE;
1370 // Count leaves (A leaf = value that is not an array, or an empty array)
1371 function array_count_leaves($array = array(), $count_empty = FALSE)
1373 if (! is_array($array) || (empty($array) && $count_empty)) return 1;
1377 foreach ($array as $part) {
1378 $count += array_count_leaves($part, $count_empty);
1383 // An array-leaves to a flat array
1384 function array_flat_leaves($array, $unique = TRUE)
1386 if (! is_array($array)) return $array;
1389 foreach(array_keys($array) as $key) {
1390 if (is_array($array[$key])) {
1392 foreach(array_flat_leaves($array[$key]) as $_value) {
1396 $tmp[] = & $array[$key];
1400 return $unique ? array_values(array_unique($tmp)) : $tmp;
1403 // An array() to an array leaf
1404 function array_leaf($array = array('A', 'B', 'C.D'), $stem = FALSE, $edge = array())
1408 foreach($array as $arg) {
1409 if (! is_string($arg) && ! is_int($arg)) continue;
1410 $tmp[$arg] = array();
1412 $tmp = & $tmp[$arg];
1415 $parent[key($parent)] = & $edge;
1417 $parent = key($parent);
1420 return $leaf; // array('A' => array('B' => 'C.D'))
1424 // ---------------------
1427 // Summarize $progress (blocked only)
1428 function summarize_spam_progress($progress = array(), $blockedonly = FALSE)
1431 $tmp = array_keys($progress['is_spam']);
1434 $method = & $progress['method'];
1435 if (isset($progress['sum'])) {
1436 foreach ($progress['sum'] as $key => $value) {
1437 if (isset($method[$key]) && $value) {
1438 $tmp[] = $key . '(' . $value . ')';
1444 return implode(', ', $tmp);
1447 function summarize_detail_badhost($progress = array())
1449 if (! isset($progress['blocked']) || empty($progress['blocked'])) return '';
1453 foreach($progress['blocked'] as $list => $lvalue) {
1454 foreach($lvalue as $group => $gvalue) {
1455 $flat = implode(', ', array_flat_leaves($gvalue));
1456 if ($flat == $group) {
1457 $blocked[$list][] = $flat;
1459 $blocked[$list][$group] = $flat;
1465 // From: 'A-1' => array('ie.to')
1466 // To: 'A-1' => 'ie.to'
1467 foreach($blocked as $list => $lvalue) {
1468 if (is_array($lvalue) &&
1469 count($lvalue) == 1 &&
1470 is_numeric(key($lvalue))) {
1471 $blocked[$list] = current($lvalue);
1475 return var_export_shrink($blocked, TRUE, TRUE);
1478 function summarize_detail_newtral($progress = array())
1480 if (! isset($progress['hosts']) ||
1481 ! is_array($progress['hosts']) ||
1482 empty($progress['hosts'])) return '';
1488 foreach($progress['hosts'] as $value) {
1489 $tmp[delimiter_reverse($value)] = $value;
1491 ksort($tmp, SORT_STRING);
1492 $result = count($tmp) . ' (' .implode(', ', $tmp) . ')';
1495 foreach($progress['hosts'] as $value) {
1496 $tmp = array_merge_recursive(
1498 array_leaf(explode('.', delimiter_reverse($value) . '.'), TRUE, $value)
1501 ksort($tmp, SORT_STRING);
1503 $tmp = array_joinkey_leaf($tmp, '.', TRUE, TRUE);
1504 $tmp = array_joinkey_leaf($tmp, '.', TRUE, FALSE);
1505 $tmp = array_joinkey_leaf($tmp, '.', TRUE, FALSE);
1506 //$tmp = array_joinkey_leaf($tmp, '.', TRUE, FALSE);
1508 foreach($tmp as $key => $value) {
1509 if (is_array($value)) {
1511 $tmp[$key] = implode(', ', array_flat_leaves($value));
1515 //$tmp = array_unique_recursive($tmp); // Buggy?
1516 $result = var_export_shrink($tmp, TRUE, TRUE);
1523 function array_joinkey_leaf($array = array('A' => array('B' => 'C.D')),
1524 $delim = '.', $reverse = FALSE, $allowmulti = FALSE)
1526 if (! is_array($array)) return $array;
1529 foreach(array_keys($array) as $key) {
1530 if (! is_array($array[$key]) || (! $allowmulti && count($array[$key]) > 1)) {
1531 $result[$key] = & $array[$key]; // Do nothing
1533 foreach(array_keys($array[$key]) as $_key) {
1534 $joinkey = $reverse ?
1535 $_key . $delim . $key :
1536 $key . $delim . $_key;
1537 $result[$joinkey] = & $array[$key][$_key];
1542 return $result; // array('A.B' => 'C.D')
1545 // ---------------------
1548 // Common bahavior for blocking
1549 // NOTE: Call this function from various blocking feature, to disgueise the reason 'why blocked'
1550 function spam_exit($mode = '', $data = array())
1553 case '': echo("\n"); break;
1555 echo('<pre>' . "\n");
1556 echo htmlspecialchars(var_export($data, TRUE));
1557 echo('</pre>' . "\n");
1566 // ---------------------
1569 // TODO: Record them
1570 // Simple/fast spam filter ($target: 'a string' or an array())
1571 function pkwk_spamfilter($action, $page, $target = array('title' => ''), $method = array(), $exitmode = '')
1573 $progress = check_uri_spam($target, $method);
1575 if (! empty($progress['is_spam'])) {
1576 // Mail to administrator(s)
1577 pkwk_spamnotify($action, $page, $target, $progress, $method);
1580 spam_exit($exitmode, $progress);
1584 // ---------------------
1585 // PukiWiki original
1587 // Mail to administrator(s)
1588 function pkwk_spamnotify($action, $page, $target = array('title' => ''), $progress = array(), $method = array())
1590 global $notify, $notify_subject;
1592 if (! $notify) return;
1594 $asap = isset($method['asap']);
1596 $summary['ACTION'] = 'Blocked by: ' . summarize_spam_progress($progress, TRUE);
1598 $summary['METRICS'] = summarize_spam_progress($progress);
1601 $tmp = summarize_detail_badhost($progress);
1602 if ($tmp != '') $summary['DETAIL_BADHOST'] = $tmp;
1604 $tmp = summarize_detail_newtral($progress);
1605 if (! $asap && $tmp != '') $summary['DETAIL_NEUTRAL_HOST'] = $tmp;
1607 $summary['COMMENT'] = $action;
1608 $summary['PAGE'] = '[blocked] ' . (is_pagename($page) ? $page : '');
1609 $summary['URI'] = get_script_uri() . '?' . rawurlencode($page);
1610 $summary['USER_AGENT'] = TRUE;
1611 $summary['REMOTE_ADDR'] = TRUE;
1612 pkwk_mail_notify($notify_subject, var_export($target, TRUE), $summary, TRUE);