2 // $Id: spam.php,v 1.179 2007/06/16 03:39: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));
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 = var_export($expression, TRUE);
48 $result = preg_replace(
49 // Remove a newline and spaces
50 '# => \n *array \(#', ' => array (',
54 if ($ignore_numeric_keys) {
55 $result =preg_replace(
56 // Remove numeric keys
57 '#^( *)[0-9]+ => #m', '$1',
70 // Remove redundant values from array()
71 function array_unique_recursive($array = array())
73 if (! is_array($array)) return $array;
76 foreach($array as $key => $value){
77 if (is_array($value)) {
78 $array[$key] = array_unique_recursive($value);
80 if (isset($tmp[$value])) {
91 // Renumber all numeric keys from 0
92 function array_renumber_numeric_keys(& $array)
94 if (! is_array($array)) return $array;
98 foreach($array as $key => $value){
99 if (is_array($value)) array_renumber_numeric_keys($array[$key]); // Recurse
100 if (is_numeric($key)) $tmp[$key] = ++$count;
102 array_rename_keys($array, $tmp);
107 // Roughly strings(1) using PCRE
108 // This function is useful to:
109 // * Reduce the size of data, from removing unprintable binary data
110 // * Detect _bare_strings_ from binary data
112 // http://www.freebsd.org/cgi/man.cgi?query=strings (Man-page of GNU strings)
113 // http://www.pcre.org/pcre.txt
114 function strings($binary = '', $min_len = 4, $ignore_space = FALSE, $multibyte = TRUE)
117 $binary = (is_array($binary) || $binary === TRUE) ? '' : strval($binary);
119 $regex = $ignore_space ?
120 '[^[:graph:] \t\n]+' : // Remove "\0" etc, and readable spaces
121 '[^[:graph:][:space:]]+'; // Preserve readable spaces if possible
123 $binary = $multibyte ?
124 mb_ereg_replace($regex, "\n", $binary) :
125 preg_replace('/' . $regex . '/s', "\n", $binary);
128 $binary = preg_replace(
143 // The last character seems "\n" or not
144 $br = (! empty($binary) && $binary[strlen($binary) - 1] == "\n") ? "\n" : '';
146 $min_len = min(1024, intval($min_len));
147 $regex = '/^.{' . $min_len . ',}/S';
148 $binary = implode("\n", preg_grep($regex, explode("\n", $binary))) . $br;
154 // Reverse $string with specified delimiter
155 function delimiter_reverse($string = 'foo.bar.example.com', $from_delim = '.', $to_delim = '.')
157 if (! is_string($string) || ! is_string($from_delim) || ! is_string($to_delim))
160 // com.example.bar.foo
161 return implode($to_delim, array_reverse(explode($from_delim, $string)));
165 // ---------------------
168 // Return an array of URIs in the $string
169 // [OK] http://nasty.example.org#nasty_string
170 // [OK] http://nasty.example.org:80/foo/xxx#nasty_string/bar
171 // [OK] ftp://nasty.example.org:80/dfsdfs
172 // [OK] ftp://cnn.example.com&story=breaking_news@10.0.0.1/top_story.htm (from RFC3986)
173 function uri_pickup($string = '')
175 if (! is_string($string)) return array();
177 // Not available for: IDN(ignored)
180 // scheme://userinfo@host:port/path/or/pathinfo/maybefile.and?query=string#fragment
181 // Refer RFC3986 (Regex below is not strict)
182 '#(\b[a-z][a-z0-9.+-]{1,8}):[/\\\]+' . // 1: Scheme
184 '([^\s<>"\'\[\]/\#?@]*)' . // 2: Userinfo (Username)
188 '\[[0-9a-f:.]+\]' . '|' . // IPv6([colon-hex and dot]): RFC2732
189 '(?:[0-9]{1,3}\.){3}[0-9]{1,3}' . '|' . // IPv4(dot-decimal): 001.22.3.44
190 '[a-z0-9][a-z0-9.-]+[a-z0-9]' . // hostname(FQDN) : foo.example.org
192 '(?::([0-9]*))?' . // 4: Port
193 '((?:/+[^\s<>"\'\[\]/\#]+)*/+)?' . // 5: Directory path or path-info
194 '([^\s<>"\'\[\]\#?]+)?' . // 6: File?
195 '(?:\?([^\s<>"\'\[\]\#]+))?' . // 7: Query string
196 '(?:\#([a-z0-9._~%!$&\'()*+,;=:@-]*))?' . // 8: Fragment
198 $string, $array, PREG_SET_ORDER | PREG_OFFSET_CAPTURE
202 static $parts = array(
203 1 => 'scheme', 2 => 'userinfo', 3 => 'host', 4 => 'port',
204 5 => 'path', 6 => 'file', 7 => 'query', 8 => 'fragment'
206 $default = array('');
207 foreach(array_keys($array) as $uri) {
208 $_uri = & $array[$uri];
209 array_rename_keys($_uri, $parts, TRUE, $default);
210 $offset = $_uri['scheme'][1]; // Scheme's offset = URI's offset
211 foreach(array_keys($_uri) as $part) {
212 $_uri[$part] = & $_uri[$part][0]; // Remove offsets
216 foreach(array_keys($array) as $uri) {
217 $_uri = & $array[$uri];
218 if ($_uri['scheme'] === '') {
219 unset($array[$uri]); // Considererd harmless
222 unset($_uri[0]); // Matched string itself
223 $_uri['area']['offset'] = $offset; // Area offset for area_measure()
229 // Normalize an array of URI arrays
230 // NOTE: Give me the uri_pickup() results
231 function uri_pickup_normalize(& $pickups, $destructive = TRUE)
233 if (! is_array($pickups)) return $pickups;
236 foreach (array_keys($pickups) as $key) {
237 $_key = & $pickups[$key];
238 $_key['scheme'] = isset($_key['scheme']) ? scheme_normalize($_key['scheme']) : '';
239 $_key['host'] = isset($_key['host']) ? host_normalize($_key['host']) : '';
240 $_key['port'] = isset($_key['port']) ? port_normalize($_key['port'], $_key['scheme'], FALSE) : '';
241 $_key['path'] = isset($_key['path']) ? strtolower(path_normalize($_key['path'])) : '';
242 $_key['file'] = isset($_key['file']) ? file_normalize($_key['file']) : '';
243 $_key['query'] = isset($_key['query']) ? query_normalize($_key['query']) : '';
244 $_key['fragment'] = isset($_key['fragment']) ? strtolower($_key['fragment']) : '';
247 foreach (array_keys($pickups) as $key) {
248 $_key = & $pickups[$key];
249 $_key['scheme'] = isset($_key['scheme']) ? scheme_normalize($_key['scheme']) : '';
250 $_key['host'] = isset($_key['host']) ? strtolower($_key['host']) : '';
251 $_key['port'] = isset($_key['port']) ? port_normalize($_key['port'], $_key['scheme'], FALSE) : '';
252 $_key['path'] = isset($_key['path']) ? path_normalize($_key['path']) : '';
259 // An URI array => An URI (See uri_pickup())
261 // $pickups = uri_pickup('a string include some URIs');
263 // foreach (array_keys($pickups) as $key) {
264 // $uris[$key] = uri_pickup_implode($pickups[$key]);
266 function uri_pickup_implode($uri = array())
268 if (empty($uri) || ! is_array($uri)) return NULL;
271 if (isset($uri['scheme']) && $uri['scheme'] !== '') {
272 $tmp[] = & $uri['scheme'];
275 if (isset($uri['userinfo']) && $uri['userinfo'] !== '') {
276 $tmp[] = & $uri['userinfo'];
279 if (isset($uri['host']) && $uri['host'] !== '') {
280 $tmp[] = & $uri['host'];
282 if (isset($uri['port']) && $uri['port'] !== '') {
284 $tmp[] = & $uri['port'];
286 if (isset($uri['path']) && $uri['path'] !== '') {
287 $tmp[] = & $uri['path'];
289 if (isset($uri['file']) && $uri['file'] !== '') {
290 $tmp[] = & $uri['file'];
292 if (isset($uri['query']) && $uri['query'] !== '') {
294 $tmp[] = & $uri['query'];
296 if (isset($uri['fragment']) && $uri['fragment'] !== '') {
298 $tmp[] = & $uri['fragment'];
301 return implode('', $tmp);
304 // $array['something'] => $array['wanted']
305 function array_rename_keys(& $array, $keys = array('from' => 'to'), $force = FALSE, $default = '')
307 if (! is_array($array) || ! is_array($keys)) return FALSE;
309 // Nondestructive test
311 foreach(array_keys($keys) as $from)
312 if (! isset($array[$from]))
315 foreach($keys as $from => $to) {
316 if ($from === $to) continue;
317 if (! $force || isset($array[$from])) {
318 $array[$to] = & $array[$from];
319 unset($array[$from]);
321 $array[$to] = $default;
328 // ---------------------
331 // Pickup all of markup areas
332 function area_pickup($string = '', $method = array())
335 if (empty($method)) return $area;
337 // Anchor tag pair by preg_match and preg_match_all()
339 // [OK] <a href= >Good site!</a>
340 // [OK] <a href= "#" >test</a>
341 // [OK] <a href="http://nasty.example.com">visit http://nasty.example.com/</a>
342 // [OK] <a href=\'http://nasty.example.com/\' >discount foobar</a>
343 // [NG] <a href="http://ng.example.com">visit http://ng.example.com _not_ended_
344 $regex = '#<a\b[^>]*\bhref\b[^>]*>.*?</a\b[^>]*(>)#is';
345 if (isset($method['area_anchor'])) {
347 $count = isset($method['asap']) ?
348 preg_match($regex, $string) :
349 preg_match_all($regex, $string, $areas);
350 if (! empty($count)) $area['area_anchor'] = $count;
352 if (isset($method['uri_anchor'])) {
354 preg_match_all($regex, $string, $areas, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
355 foreach(array_keys($areas) as $_area) {
356 $areas[$_area] = array(
357 $areas[$_area][0][1], // Area start (<a href>)
358 $areas[$_area][1][1], // Area end (</a>)
361 if (! empty($areas)) $area['uri_anchor'] = $areas;
364 // phpBB's "BBCode" pair by preg_match and preg_match_all()
366 // [OK] [url]http://nasty.example.com/[/url]
367 // [OK] [link]http://nasty.example.com/[/link]
368 // [OK] [url=http://nasty.example.com]visit http://nasty.example.com/[/url]
369 // [OK] [link http://nasty.example.com/]buy something[/link]
370 $regex = '#\[(url|link)\b[^\]]*\].*?\[/\1\b[^\]]*(\])#is';
371 if (isset($method['area_bbcode'])) {
373 $count = isset($method['asap']) ?
374 preg_match($regex, $string) :
375 preg_match_all($regex, $string, $areas, PREG_SET_ORDER);
376 if (! empty($count)) $area['area_bbcode'] = $count;
378 if (isset($method['uri_bbcode'])) {
380 preg_match_all($regex, $string, $areas, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
381 foreach(array_keys($areas) as $_area) {
382 $areas[$_area] = array(
383 $areas[$_area][0][1], // Area start ([url])
384 $areas[$_area][2][1], // Area end ([/url])
387 if (! empty($areas)) $area['uri_bbcode'] = $areas;
390 // Various Wiki syntax
391 // [text_or_uri>text_or_uri]
392 // [text_or_uri:text_or_uri]
393 // [text_or_uri|text_or_uri]
394 // [text_or_uri->text_or_uri]
395 // [text_or_uri text_or_uri] // MediaWiki
396 // MediaWiki: [http://nasty.example.com/ visit http://nasty.example.com/]
401 // If in doubt, it's a little doubtful
402 // if (Area => inside <= Area) $brief += -1
403 function area_measure($areas, & $array, $belief = -1, $a_key = 'area', $o_key = 'offset')
405 if (! is_array($areas) || ! is_array($array)) return;
407 $areas_keys = array_keys($areas);
408 foreach(array_keys($array) as $u_index) {
409 $offset = isset($array[$u_index][$o_key]) ?
410 intval($array[$u_index][$o_key]) : 0;
411 foreach($areas_keys as $a_index) {
412 if (isset($array[$u_index][$a_key])) {
413 $offset_s = intval($areas[$a_index][0]);
414 $offset_e = intval($areas[$a_index][1]);
415 // [Area => inside <= Area]
416 if ($offset_s < $offset && $offset < $offset_e) {
417 $array[$u_index][$a_key] += $belief;
424 // ---------------------
427 // Domain exposure callback (See spam_uri_pickup_preprocess())
428 // http://victim.example.org/?foo+site:nasty.example.com+bar
429 // => http://nasty.example.com/?refer=victim.example.org
430 // NOTE: 'refer=' is not so good for (at this time).
431 // Consider about using IP address of the victim, try to avoid that.
432 function _preg_replace_callback_domain_exposure($matches = array())
436 // Preserve the victim URI as a complicity or ...
437 if (isset($matches[5])) {
439 $matches[1] . '://' . // scheme
440 $matches[2] . '/' . // victim.example.org
441 $matches[3]; // The rest of all (before victim)
445 if (isset($matches[4])) {
447 $matches[1] . '://' . // scheme
448 $matches[4] . // nasty.example.com
449 '/?refer=' . strtolower($matches[2]) . // victim.example.org
456 // Preprocess: Removing uninterest part for URI detection
457 function spam_uri_removing_hocus_pocus($binary = '', $method = array())
459 $length = 4 ; // 'http'(1) and '://'(2) and 'fqdn'(1)
460 if (is_array($method)) {
461 // '<a'(2) or 'href='(5) or '>'(1) or '</a>'(4)
462 // '[uri'(4) or ']'(1) or '[/uri]'(6)
463 if (isset($method['area_anchor']) || isset($method['uri_anchor']) ||
464 isset($method['area_bbcode']) || isset($method['uri_bbcode']))
465 $length = 1; // Seems not effective
468 // Removing sequential spaces and too short lines
469 $binary = strings($binary, $length, TRUE, TRUE);
471 // Remove words (has no '<>[]:') between spaces
472 $binary = preg_replace('/[ \t][\w.,()\ \t]+[ \t]/', ' ', $binary);
477 // Preprocess: rawurldecode() and adding space(s) and something
478 // to detect/count some URIs _if possible_
479 // NOTE: It's maybe danger to var_dump(result). [e.g. 'javascript:']
480 // [OK] http://victim.example.org/?site:nasty.example.org
481 // [OK] http://victim.example.org/nasty.example.org
482 // [OK] http://victim.example.org/go?http%3A%2F%2Fnasty.example.org
483 // [OK] http://victim.example.org/http://nasty.example.org
484 function spam_uri_pickup_preprocess($string = '', $method = array())
486 if (! is_string($string)) return '';
488 $string = spam_uri_removing_hocus_pocus(rawurldecode($string), $method);
489 //var_dump(htmlspecialchars($string));
491 // Domain exposure (simple)
492 // http://victim.example.org/nasty.example.org/path#frag
493 // => http://nasty.example.org/?refer=victim.example.org and original
494 $string = preg_replace(
497 'ime\.nu' . '|' . // 2ch.net
498 'ime\.st' . '|' . // 2ch.net
499 'link\.toolbot\.com' . '|' .
502 '/([a-z0-9.%_-]+\.[a-z0-9.%_-]+)#i', // nasty.example.org
503 'http://$2/?refer=$1 $0', // Preserve $0 or remove?
507 // Domain exposure (gate-big5)
508 // http://victim.example.org/gate/big5/nasty.example.org/path
509 // => http://nasty.example.org/?refer=victim.example.org and original
510 $string = preg_replace(
513 'big5.51job.com' . '|' .
514 'big5.china.com' . '|' .
515 'big5.xinhuanet.com' . '|' .
518 '/([a-z0-9.%_-]+\.[a-z0-9.%_-]+)' .
519 '#i', // nasty.example.org
520 'http://$2/?refer=$1 $0', // Preserve $0 or remove?
524 // Domain exposure (See _preg_replace_callback_domain_exposure())
525 $string = preg_replace_callback(
529 // Something Google: http://www.google.com/supported_domains
530 '(?:[a-z0-9.]+\.)?google\.[a-z]{2,3}(?:\.[a-z]{2})?' .
533 '(?:[a-z0-9.]+\.)?altavista.com' .
537 '([a-z0-9?=&.%_/\'\\\+-]+)' . // path/?query=foo+bar+
538 '\bsite:([a-z0-9.%_-]+\.[a-z0-9.%_-]+)' . // site:nasty.example.com
539 //'()' . // Preserve or remove?
542 '_preg_replace_callback_domain_exposure',
546 // URI exposure (uriuri => uri uri)
547 $string = preg_replace(
549 '#(?<! )(?:https?|ftp):/#i',
550 // '#[a-z][a-z0-9.+-]{1,8}://#i',
551 // '#[a-z][a-z0-9.+-]{1,8}://#i'
560 // Main function of spam-uri pickup,
561 // A wrapper function of uri_pickup()
562 function spam_uri_pickup($string = '', $method = array())
564 if (! is_array($method) || empty($method)) {
565 $method = check_uri_spam_method();
568 $string = spam_uri_pickup_preprocess($string, $method);
570 $array = uri_pickup($string);
572 // Area elevation of URIs, for '(especially external)link' intension
573 if (! empty($array)) {
575 if (isset($method['uri_anchor'])) $_method['uri_anchor'] = & $method['uri_anchor'];
576 if (isset($method['uri_bbcode'])) $_method['uri_bbcode'] = & $method['uri_bbcode'];
577 $areas = area_pickup($string, $_method, TRUE);
578 if (! empty($areas)) {
579 $area_shadow = array();
580 foreach (array_keys($array) as $key) {
581 $area_shadow[$key] = & $array[$key]['area'];
582 foreach (array_keys($_method) as $_key) {
583 $area_shadow[$key][$_key] = 0;
586 foreach (array_keys($_method) as $_key) {
587 if (isset($areas[$_key])) {
588 area_measure($areas[$_key], $area_shadow, 1, $_key);
594 // Remove 'offset's for area_measure()
595 foreach(array_keys($array) as $key)
596 unset($array[$key]['area']['offset']);
602 // ---------------------
605 // Scheme normalization: Renaming the schemes
606 // snntp://example.org => nntps://example.org
607 // NOTE: Keep the static lists simple. See also port_normalize().
608 function scheme_normalize($scheme = '', $abbrevs_harmfull = TRUE)
610 // Abbreviations they have no intention of link
611 static $abbrevs = array(
616 // Aliases => normalized ones
617 static $aliases = array(
627 if (! is_string($scheme)) return '';
629 $scheme = strtolower($scheme);
630 if (isset($abbrevs[$scheme])) {
631 $scheme = $abbrevs_harmfull ? $abbrevs[$scheme] : '';
633 if (isset($aliases[$scheme])) {
634 $scheme = $aliases[$scheme];
640 // Hostname normlization (Destructive)
641 // www.foo => www.foo ('foo' seems TLD)
642 // www.foo.bar => foo.bar
643 // www.10.20 => www.10.20 (Invalid hostname)
645 // 'www' is mostly used as traditional hostname of WWW server.
646 // 'www.foo.bar' may be identical with 'foo.bar'.
647 function host_normalize($host = '')
649 if (! is_string($host)) return '';
651 $host = strtolower($host);
653 if (preg_match('/^www\.(.+\.[a-z]+)$/', $host, $matches)) {
660 // Port normalization: Suppress the (redundant) default port
661 // HTTP://example.org:80/ => http://example.org/
662 // HTTP://example.org:8080/ => http://example.org:8080/
663 // HTTPS://example.org:443/ => https://example.org/
664 function port_normalize($port, $scheme, $scheme_normalize = FALSE)
666 // Schemes that users _maybe_ want to add protocol-handlers
667 // to their web browsers. (and attackers _maybe_ want to use ...)
668 // Reference: http://www.iana.org/assignments/port-numbers
669 static $array = array(
670 // scheme => default port
696 // intval() converts '0-1' to '0', so preg_match() rejects these invalid ones
697 if (! is_numeric($port) || $port < 0 || preg_match('/[^0-9]/i', $port))
700 $port = intval($port);
701 if ($scheme_normalize) $scheme = scheme_normalize($scheme);
702 if (isset($array[$scheme]) && $port == $array[$scheme])
703 $port = ''; // Ignore the defaults
708 // Path normalization
709 // http://example.org => http://example.org/
710 // http://example.org#hoge => http://example.org/#hoge
711 // http://example.org/path/a/b/./c////./d => http://example.org/path/a/b/c/d
712 // http://example.org/path/../../a/../back => http://example.org/back
713 function path_normalize($path = '', $divider = '/', $add_root = TRUE)
715 if (! is_string($divider)) return is_string($path) ? $path : '';
718 $first_div = & $divider;
722 if (! is_string($path) || $path == '') return $first_div;
724 if (strpos($path, $divider, strlen($path) - strlen($divider)) === FALSE) {
727 $last_div = & $divider;
730 $array = explode($divider, $path);
732 // Remove paddings ('//' and '/./')
733 foreach(array_keys($array) as $key) {
734 if ($array[$key] == '' || $array[$key] == '.') {
739 // Remove back-tracks ('/../')
741 foreach($array as $value) {
742 if ($value == '..') {
745 array_push($tmp, $value);
753 return $first_div . implode($divider, $array) . $last_div;
757 // DirectoryIndex normalize (Destructive and rough)
758 // TODO: sample.en.ja.html.gz => sample.html
759 function file_normalize($file = 'index.html.en')
761 static $simple_defaults = array(
762 'default.htm' => TRUE,
763 'default.html' => TRUE,
764 'default.asp' => TRUE,
765 'default.aspx' => TRUE,
766 'index' => TRUE, // Some system can omit the suffix
769 static $content_suffix = array(
770 // index.xxx, sample.xxx
785 static $language_suffix = array(
786 // Reference: Apache 2.0.59 'AddLanguage' default
815 // Reference: Apache 2.0.59 default 'index.html' variants
821 static $charset_suffix = array(
822 // Reference: Apache 2.0.59 'AddCharset' default
823 'iso8859-1' => TRUE, // ISO-8859-1
824 'latin1' => TRUE, // ISO-8859-1
825 'iso8859-2' => TRUE, // ISO-8859-2
826 'latin2' => TRUE, // ISO-8859-2
827 'cen' => TRUE, // ISO-8859-2
828 'iso8859-3' => TRUE, // ISO-8859-3
829 'latin3' => TRUE, // ISO-8859-3
830 'iso8859-4' => TRUE, // ISO-8859-4
831 'latin4' => TRUE, // ISO-8859-4
832 'iso8859-5' => TRUE, // ISO-8859-5
833 'latin5' => TRUE, // ISO-8859-5
834 'cyr' => TRUE, // ISO-8859-5
835 'iso-ru' => TRUE, // ISO-8859-5
836 'iso8859-6' => TRUE, // ISO-8859-6
837 'latin6' => TRUE, // ISO-8859-6
838 'arb' => TRUE, // ISO-8859-6
839 'iso8859-7' => TRUE, // ISO-8859-7
840 'latin7' => TRUE, // ISO-8859-7
841 'grk' => TRUE, // ISO-8859-7
842 'iso8859-8' => TRUE, // ISO-8859-8
843 'latin8' => TRUE, // ISO-8859-8
844 'heb' => TRUE, // ISO-8859-8
845 'iso8859-9' => TRUE, // ISO-8859-9
846 'latin9' => TRUE, // ISO-8859-9
847 'trk' => TRUE, // ISO-8859-9
848 'iso2022-jp'=> TRUE, // ISO-2022-JP
849 'jis' => TRUE, // ISO-2022-JP
850 'iso2022-kr'=> TRUE, // ISO-2022-KR
851 'kis' => TRUE, // ISO-2022-KR
852 'iso2022-cn'=> TRUE, // ISO-2022-CN
853 'cis' => TRUE, // ISO-2022-CN
855 'cp-1251' => TRUE, // ru, WINDOWS-1251
856 'win-1251' => TRUE, // ru, WINDOWS-1251
857 'cp866' => TRUE, // ru
858 'koi8-r' => TRUE, // ru, KOI8-r
859 'koi8-ru' => TRUE, // ru, KOI8-r
860 'koi8-uk' => TRUE, // ru, KOI8-ru
861 'ua' => TRUE, // ru, KOI8-ru
862 'ucs2' => TRUE, // ru, ISO-10646-UCS-2
863 'ucs4' => TRUE, // ru, ISO-10646-UCS-4
866 // Reference: Apache 2.0.59 default 'index.html' variants
871 // May uncompress by web browsers on the fly
872 // Must be at the last of the filename
873 // Reference: Apache 2.0.59 'AddEncoding'
874 static $encoding_suffix = array(
879 if (! is_string($file)) return '';
880 $_file = strtolower($file);
881 if (isset($simple_defaults[$_file])) return '';
884 // Roughly removing language/character-set/encoding suffixes
886 // * Apache 2 document about 'Content-negotiaton', 'mod_mime' and 'mod_negotiation'
887 // http://httpd.apache.org/docs/2.0/content-negotiation.html
888 // http://httpd.apache.org/docs/2.0/mod/mod_mime.html
889 // http://httpd.apache.org/docs/2.0/mod/mod_negotiation.html
890 // * http://www.iana.org/assignments/character-sets
891 // * RFC3066: Tags for the Identification of Languages
892 // http://www.ietf.org/rfc/rfc3066.txt
893 // * ISO 639: codes of 'language names'
894 $suffixes = explode('.', $_file);
895 $body = array_shift($suffixes);
897 // Remove the last .gz/.z
898 $last_key = end(array_keys($suffixes));
899 if (isset($encoding_suffix[$suffixes[$last_key]])) {
900 unset($suffixes[$last_key]);
903 // Cut language and charset suffixes
904 foreach($suffixes as $key => $value){
905 if (isset($language_suffix[$value]) || isset($charset_suffix[$value])) {
906 unset($suffixes[$key]);
909 if (empty($suffixes)) return $body;
912 $count = count($suffixes);
914 $current = current($suffixes);
915 if ($body == 'index' && $count == 1 && isset($content_suffix[$current])) return '';
920 // Sort query-strings if possible (Destructive and rough)
921 // [OK] &&&&f=d&b&d&c&a=0dd => a=0dd&b&c&d&f=d
922 // [OK] nothing==&eg=dummy&eg=padding&eg=foobar => eg=foobar
923 function query_normalize($string = '', $equal = TRUE, $equal_cutempty = TRUE, $stortolower = TRUE)
925 if (! is_string($string)) return '';
926 if ($stortolower) $string = strtolower($string);
928 $array = explode('&', $string);
930 // Remove '&' paddings
931 foreach(array_keys($array) as $key) {
932 if ($array[$key] == '') {
937 // Consider '='-sepalated input and paddings
939 $equals = $not_equals = array();
940 foreach ($array as $part) {
941 if (strpos($part, '=') === FALSE) {
942 $not_equals[] = $part;
944 list($key, $value) = explode('=', $part, 2);
945 $value = ltrim($value, '=');
946 if (! $equal_cutempty || $value != '') {
947 $equals[$key] = $value;
952 $array = & $not_equals;
953 foreach ($equals as $key => $value) {
954 $array[] = $key . '=' . $value;
960 return implode('&', $array);
963 // ---------------------
964 // Part One : Checker
966 // Rough implementation of globbing
968 // USAGE: $regex = '/^' . generate_glob_regex('*.txt', '/') . '$/i';
970 function generate_glob_regex($string = '', $divider = '/')
972 static $from = array(
975 // 22 => '[', // Maybe cause regex compilation error (e.g. '[]')
991 if (! is_string($string)) return '';
993 $string = str_replace($from, $mid, $string); // Hide
994 $string = preg_quote($string, $divider);
995 $string = str_replace($mid, $to, $string); // Unhide
1000 // Rough hostname checker
1002 // TODO: Strict digit, 0x, CIDR, IPv6
1003 function is_ip($string = '')
1005 if (preg_match('/^' .
1006 '(?:[0-9]{1,3}\.){3}[0-9]{1,3}' . '|' .
1007 '(?:[0-9]{1,3}\.){1,3}' . '$/',
1009 return 4; // Seems IPv4(dot-decimal)
1011 return 0; // Seems not IP
1015 // Generate host (FQDN, IPv4, ...) regex
1016 // 'localhost' : Matches with 'localhost' only
1017 // 'example.org' : Matches with 'example.org' only (See host_normalize() about 'www')
1018 // '.example.org' : Matches with ALL FQDN ended with '.example.org'
1019 // '*.example.org' : Almost the same of '.example.org' except 'www.example.org'
1020 // '10.20.30.40' : Matches with IPv4 address '10.20.30.40' only
1021 // [TODO] '192.' : Matches with all IPv4 hosts started with '192.'
1022 // TODO: IPv4, CIDR?, IPv6
1023 function generate_host_regex($string = '', $divider = '/')
1025 if (! is_string($string)) return '';
1027 if (mb_strpos($string, '.') === FALSE)
1028 return generate_glob_regex($string, $divider);
1031 if (is_ip($string)) {
1033 return generate_glob_regex($string, $divider);
1035 // FQDN or something
1036 $part = explode('.', $string, 2);
1037 if ($part[0] == '') {
1038 $part[0] = '(?:.*\.)?'; // And all related FQDN
1039 } else if ($part[0] == '*') {
1040 $part[0] = '.*\.'; // All subdomains/hosts only
1042 return generate_glob_regex($string, $divider);
1044 $part[1] = generate_glob_regex($part[1], $divider);
1045 return implode('', $part);
1049 function get_blocklist($list = '')
1053 if ($list === NULL) {
1054 $regexes = NULL; // Unset
1058 if (! isset($regexes)) {
1060 if (file_exists(SPAM_INI_FILE)) {
1061 $blocklist = array();
1062 include(SPAM_INI_FILE);
1063 // $blocklist['badhost'] = array(
1064 // '*.blogspot.com', // Blog services's subdomains (only)
1065 // 'IANA-examples' => '#^(?:.*\.)?example\.(?:com|net|org)$#',
1067 if (isset($blocklist['list'])) {
1068 $regexes['list'] = & $blocklist['list'];
1071 $blocklist['list'] = array(
1072 'goodhost' => FALSE,
1076 foreach(array_keys($blocklist['list']) as $_list) {
1077 if (! isset($blocklist[$_list])) continue;
1078 foreach ($blocklist[$_list] as $key => $value) {
1079 if (is_array($value)) {
1080 $regexes[$_list][$key] = array();
1081 foreach($value as $_key => $_value) {
1082 get_blocklist_add($regexes[$_list][$key], $_key, $_value);
1085 get_blocklist_add($regexes[$_list], $key, $value);
1088 unset($blocklist[$_list]);
1094 return $regexes; // ALL
1095 } else if (isset($regexes[$list])) {
1096 return $regexes[$list];
1102 // Subroutine of get_blocklist()
1103 function get_blocklist_add(& $array, $key = 0, $value = '*.example.org')
1105 if (is_string($key)) {
1106 $array[$key] = & $value; // Treat $value as a regex
1108 $array[$value] = '/^' . generate_host_regex($value, '/') . '$/i';
1112 // Blocklist metrics: Separate $host, to $blocked and not blocked
1113 function blocklist_distiller(& $hosts, $keys = array('goodhost', 'badhost'), $asap = FALSE)
1115 if (! is_array($hosts)) $hosts = array($hosts);
1116 if (! is_array($keys)) $keys = array($keys);
1118 $list = get_blocklist('list');
1121 foreach($keys as $key){
1122 foreach (get_blocklist($key) as $label => $regex) {
1123 if (is_array($regex)) {
1124 foreach($regex as $_label => $_regex) {
1125 $group = preg_grep($_regex, $hosts);
1127 $hosts = array_diff($hosts, $group);
1128 $blocked[$key][$label][$_label] = $group;
1129 if ($asap && $list[$key]) break;
1133 $group = preg_grep($regex, $hosts);
1135 $hosts = array_diff($hosts, $group);
1136 $blocked[$key][$label] = $group;
1137 if ($asap && $list[$key]) break;
1146 // Default (enabled) methods and thresholds (for content insertion)
1147 function check_uri_spam_method($times = 1, $t_area = 0, $rule = TRUE)
1149 $times = intval($times);
1150 $t_area = intval($t_area);
1154 'quantity' => 8 * $times, // Allow N URIs
1155 'non_uniqhost' => 3 * $times, // Allow N duped (and normalized) Hosts
1156 //'non_uniquri'=> 3 * $times, // Allow N duped (and normalized) URIs
1159 'area_anchor' => $t_area, // Using <a href> HTML tag
1160 'area_bbcode' => $t_area, // Using [url] or [link] BBCode
1161 //'uri_anchor' => $t_area, // URI inside <a href> HTML tag
1162 //'uri_bbcode' => $t_area, // URI inside [url] or [link] BBCode
1167 //'asap' => TRUE, // Quit or return As Soon As Possible
1168 'uniqhost' => TRUE, // Show uniq host (at block notification mail)
1169 'badhost' => TRUE, // Check badhost
1175 // Remove non-$positive values
1176 foreach (array_keys($positive) as $key) {
1177 if ($positive[$key] < 0) unset($positive[$key]);
1180 return $positive + $bool;
1183 // Simple/fast spam check
1184 function check_uri_spam($target = '', $method = array())
1189 // Theme to do => Dummy, optional value, or optional array()
1191 //'uniqhost' => TRUE,
1192 //'non_uniqhost'=> 3,
1193 //'non_uniquri' => 3,
1194 //'badhost' => TRUE,
1195 //'area_anchor' => 0,
1196 //'area_bbcode' => 0,
1197 //'uri_anchor' => 0,
1198 //'uri_bbcode' => 0,
1201 // Theme => Volume found (int)
1204 // Flag. If someting defined here,
1205 // one or more spam will be included
1210 //'category' => array(
1215 // Hosts not blocked
1220 $sum = & $progress['sum'];
1221 $is_spam = & $progress['is_spam'];
1222 $progress['method'] = & $method; // Argument
1223 $blocked = & $progress['blocked'];
1224 $hosts = & $progress['hosts'];
1225 $asap = isset($method['asap']);
1228 if (! is_array($method) || empty($method)) {
1229 $method = check_uri_spam_method();
1231 foreach(array_keys($method) as $key) {
1232 if (! isset($sum[$key])) $sum[$key] = 0;
1234 if (! isset($sum['quantity'])) $sum['quantity'] = 0;
1236 if (is_array($target)) {
1237 foreach($target as $str) {
1238 if (! is_string($str)) continue;
1240 $_progress = check_uri_spam($str, $method); // Recurse
1243 $_sum = & $_progress['sum'];
1244 foreach (array_keys($_sum) as $key) {
1245 if (! isset($sum[$key])) {
1246 $sum[$key] = & $_sum[$key];
1248 $sum[$key] += $_sum[$key];
1253 $_is_spam = & $_progress['is_spam'];
1254 foreach (array_keys($_is_spam) as $key) {
1255 $is_spam[$key] = TRUE;
1258 if ($asap && $is_spam) break;
1261 $blocked = array_merge_recursive($blocked, $_progress['blocked']);
1262 $hosts = array_merge_recursive($hosts, $_progress['hosts']);
1266 $blocked = array_unique_recursive($blocked);
1267 $hosts = array_unique_recursive($hosts);
1269 // Recount $sum['badhost']
1270 $sum['badhost'] = array_count_leaves($blocked);
1275 // Area: There's HTML anchor tag
1276 if ((! $asap || ! $is_spam) && isset($method['area_anchor'])) {
1277 $key = 'area_anchor';
1278 $_asap = isset($method['asap']) ? array('asap' => TRUE) : array();
1279 $result = area_pickup($target, array($key => TRUE) + $_asap);
1281 $sum[$key] = $result[$key];
1282 if (isset($method[$key]) && $sum[$key] > $method[$key]) {
1283 $is_spam[$key] = TRUE;
1288 // Area: There's 'BBCode' linking tag
1289 if ((! $asap || ! $is_spam) && isset($method['area_bbcode'])) {
1290 $key = 'area_bbcode';
1291 $_asap = isset($method['asap']) ? array('asap' => TRUE) : array();
1292 $result = area_pickup($target, array($key => TRUE) + $_asap);
1294 $sum[$key] = $result[$key];
1295 if (isset($method[$key]) && $sum[$key] > $method[$key]) {
1296 $is_spam[$key] = TRUE;
1302 if ($asap && $is_spam) return $progress;
1305 $pickups = uri_pickup_normalize(spam_uri_pickup($target, $method));
1308 if (empty($pickups)) return $progress;
1310 // URI: Check quantity
1311 $sum['quantity'] += count($pickups);
1313 if ((! $asap || ! $is_spam) && isset($method['quantity']) &&
1314 $sum['quantity'] > $method['quantity']) {
1315 $is_spam['quantity'] = TRUE;
1318 // URI: used inside HTML anchor tag pair
1319 if ((! $asap || ! $is_spam) && isset($method['uri_anchor'])) {
1320 $key = 'uri_anchor';
1321 foreach($pickups as $pickup) {
1322 if (isset($pickup['area'][$key])) {
1323 $sum[$key] += $pickup['area'][$key];
1324 if(isset($method[$key]) &&
1325 $sum[$key] > $method[$key]) {
1326 $is_spam[$key] = TRUE;
1327 if ($asap && $is_spam) break;
1329 if ($asap && $is_spam) break;
1334 // URI: used inside 'BBCode' pair
1335 if ((! $asap || ! $is_spam) && isset($method['uri_bbcode'])) {
1336 $key = 'uri_bbcode';
1337 foreach($pickups as $pickup) {
1338 if (isset($pickup['area'][$key])) {
1339 $sum[$key] += $pickup['area'][$key];
1340 if(isset($method[$key]) &&
1341 $sum[$key] > $method[$key]) {
1342 $is_spam[$key] = TRUE;
1343 if ($asap && $is_spam) break;
1345 if ($asap && $is_spam) break;
1350 // URI: Uniqueness (and removing non-uniques)
1351 if ((! $asap || ! $is_spam) && isset($method['non_uniquri'])) {
1354 foreach (array_keys($pickups) as $key) {
1355 $uris[$key] = uri_pickup_implode($pickups[$key]);
1357 $count = count($uris);
1358 $uris = array_unique($uris);
1359 $sum['non_uniquri'] += $count - count($uris);
1360 if ($sum['non_uniquri'] > $method['non_uniquri']) {
1361 $is_spam['non_uniquri'] = TRUE;
1363 if (! $asap || ! $is_spam) {
1364 foreach (array_diff(array_keys($pickups),
1365 array_keys($uris)) as $remove) {
1366 unset($pickups[$remove]);
1373 if ($asap && $is_spam) return $progress;
1375 // Host: Uniqueness (uniq / non-uniq)
1376 foreach ($pickups as $pickup) $hosts[] = & $pickup['host'];
1377 $hosts = array_unique($hosts);
1378 $sum['uniqhost'] += count($hosts);
1379 if ((! $asap || ! $is_spam) && isset($method['non_uniqhost'])) {
1380 $sum['non_uniqhost'] = $sum['quantity'] - $sum['uniqhost'];
1381 if ($sum['non_uniqhost'] > $method['non_uniqhost']) {
1382 $is_spam['non_uniqhost'] = TRUE;
1387 if ($asap && $is_spam) return $progress;
1389 // URI: Bad host (Separate good/bad hosts from $hosts)
1390 if ((! $asap || ! $is_spam) && isset($method['badhost'])) {
1393 $list = get_blocklist('list');
1394 $blocked = blocklist_distiller($hosts, array_keys($list), $asap);
1395 foreach($list as $key=>$type){
1396 if (! $type) unset($blocked[$key]); // Ignore goodhost etc
1400 if (! empty($blocked)) $is_spam['badhost'] = TRUE;
1406 // Count leaves (A leaf = value that is not an array, or an empty array)
1407 function array_count_leaves($array = array(), $count_empty = FALSE)
1409 if (! is_array($array) || (empty($array) && $count_empty)) return 1;
1413 foreach ($array as $part) {
1414 $count += array_count_leaves($part, $count_empty);
1419 // An array-leaves to a flat array
1420 function array_flat_leaves($array, $unique = TRUE)
1422 if (! is_array($array)) return $array;
1425 foreach(array_keys($array) as $key) {
1426 if (is_array($array[$key])) {
1428 foreach(array_flat_leaves($array[$key]) as $_value) {
1432 $tmp[] = & $array[$key];
1436 return $unique ? array_values(array_unique($tmp)) : $tmp;
1439 // An array() to an array leaf
1440 function array_leaf($array = array('A', 'B', 'C.D'), $stem = FALSE, $edge = TRUE)
1442 if (! is_array($array)) return $array;
1446 foreach($array as $arg) {
1447 if (! is_string($arg) && ! is_int($arg)) continue;
1448 $tmp[$arg] = array();
1450 $tmp = & $tmp[$arg];
1453 $parent[key($parent)] = & $edge;
1455 $parent = key($parent);
1458 return $leaf; // array('A' => array('B' => 'C.D'))
1462 // ---------------------
1465 // Summarize $progress (blocked only)
1466 function summarize_spam_progress($progress = array(), $blockedonly = FALSE)
1469 $tmp = array_keys($progress['is_spam']);
1472 $method = & $progress['method'];
1473 if (isset($progress['sum'])) {
1474 foreach ($progress['sum'] as $key => $value) {
1475 if (isset($method[$key]) && $value) {
1476 $tmp[] = $key . '(' . $value . ')';
1482 return implode(', ', $tmp);
1485 function summarize_detail_badhost($progress = array())
1487 if (! isset($progress['blocked']) || empty($progress['blocked'])) return '';
1491 foreach($progress['blocked'] as $list => $lvalue) {
1492 foreach($lvalue as $group => $gvalue) {
1493 $flat = implode(', ', array_flat_leaves($gvalue));
1494 if ($flat === $group) {
1495 $blocked[$list][] = $flat;
1497 $blocked[$list][$group] = $flat;
1503 // From: 'A-1' => array('ie.to')
1504 // To: 'A-1' => 'ie.to'
1505 foreach($blocked as $list => $lvalue) {
1506 if (is_array($lvalue) &&
1507 count($lvalue) == 1 &&
1508 is_numeric(key($lvalue))) {
1509 $blocked[$list] = current($lvalue);
1513 return var_export_shrink($blocked, TRUE, TRUE);
1516 function summarize_detail_newtral($progress = array())
1518 if (! isset($progress['hosts']) ||
1519 ! is_array($progress['hosts']) ||
1520 empty($progress['hosts'])) return '';
1526 foreach($progress['hosts'] as $value) {
1528 // Try to shorten (pre) -- array('example.com', 'bar', 'foo')
1529 $resp = whois_responsibility($value); // 'example.com'
1530 $rest = rtrim(substr($value, 0, - strlen($resp)), '.'); // 'foo.bar'
1532 $parts = explode('.', delimiter_reverse('.' . $rest));
1533 array_unshift($parts, $resp);
1535 $parts = array($resp, $rest);
1538 $trie = array_merge_recursive(
1540 array_leaf($parts, TRUE, $value)
1544 // Try to shorten (post, non-recursive) -- 'foo.bar.example.com'
1545 array_joinbranch_leaf($trie, '.', 0, TRUE);
1547 // Sort and flatten -- 'A.foo.bar.example.com, B.foo.bar.example.com'
1548 foreach(array_keys($trie) as $key) {
1549 if (is_array($trie[$key])) {
1550 ksort_by_domain($trie[$key]);
1551 $trie[$key] = implode(', ', array_flat_leaves($trie[$key]));
1555 // TODO: ltrim('.') from $trie
1557 ksort_by_domain($trie);
1559 // TODO: from array('foobar' => 'foobar') to 'foobar'
1561 return var_export_shrink($trie, TRUE, TRUE);
1564 // ksort() by domain
1565 function ksort_by_domain(& $array)
1568 foreach(array_keys($array) as $key) {
1569 $sort[delimiter_reverse($key)] = $key;
1571 ksort($sort, SORT_STRING);
1573 foreach($sort as $key) {
1574 $result[$key] = & $array[$key];
1579 // array('F' => array('B' => array('C' => array('d' => array('' => 'foobar')))))
1581 // array('F.B.C.d.' => 'foobar')
1582 function array_joinbranch_leaf(& $array, $delim = '.', $limit = 0, $reverse = FALSE)
1585 if (! is_array($array)) return $result; // Nothing to do
1587 $limit = max(0, intval($limit));
1590 foreach(array_keys($array) as $key) {
1594 $single = array($key => & $array[$key]); // Keep it single
1595 $cursor = & $single;
1596 while(is_array($cursor) && count($cursor) == 1) { // Once
1598 $kstack[] = key($cursor);
1599 $cursor = & $cursor[$kstack[$k]];
1600 if ($limit != 0 && $k == $limit) break;
1605 if ($reverse) $kstack = array_reverse($kstack);
1606 $joinkey = implode($delim, $kstack);
1608 unset($array[$key]);
1609 $array[$joinkey] = & $cursor;
1610 $result[$joinkey] = $k + 1; // Key seems not an single array => joined length
1618 // Check responsibility-root of the FQDN
1619 // 'foo.bar.example.com' => 'example.com' (.com has the last whois for it)
1620 // 'foo.bar.example.au' => 'example.au' (.au has the last whois for it)
1621 // 'foo.bar.example.edu.au' => 'example.edu.au' (.edu.au has the last whois for it)
1622 // 'foo.bar.example.act.edu.au' => 'example.act.edu.au' (.act.edu.au has the last whois for it)
1623 function whois_responsibility($fqdn = 'foo.bar.example.com', $parent = FALSE, $implicit = TRUE)
1625 // Domains who have 2nd and/or 3rd level domains
1626 static $domain = array(
1629 // http://www.auda.org.au/
1630 // NIC : http://www.aunic.net/
1631 // Whois: http://www.ausregistry.com.au/
1633 // .au Second Level Domains
1634 // http://www.auda.org.au/domains/
1639 'edu' => array( // http://www.domainname.edu.au/
1652 'act' => TRUE, // Australian Capital Territory
1653 'nt' => TRUE, // Northern Territory
1654 'nsw' => TRUE, // New South Wales
1655 'qld' => TRUE, // Queensland
1656 'sa' => TRUE, // South Australia
1657 'tas' => TRUE, // Tasmania
1658 'vic' => TRUE, // Victoria
1659 'wa' => TRUE, // Western Australia
1668 // NIC : http://www.cnnic.net.cn/en/index/
1669 // Whois: http://ewhois.cnnic.cn/
1671 // Provisional Administrative Rules for Registration of Domain Names in China
1672 // http://www.cnnic.net.cn/html/Dir/2003/11/27/1520.htm
1719 // ccTLD: South Korea
1720 // NIC : http://www.nic.or.kr/english/
1721 // Whois: http://whois.nida.or.kr/english/
1723 // .kr domain policy [appendix 1] : Qualifications for Second Level Domains
1724 // http://domain.nida.or.kr/eng/policy.jsp
1755 'gyeongbuk' => TRUE,
1756 'gyeongnam' => TRUE,
1761 // NIC : http://jprs.co.jp/en/
1762 // Whois: http://whois.jprs.jp/en/
1764 // Guide to JP Domain Name
1765 // http://jprs.co.jp/en/jpdomain.html
1779 // Examples for 3rd level domains
1780 //'kumamoto' => array(
1781 // // http://www.pref.kumamoto.jp/link/list.asp#4
1782 // 'amakusa' => TRUE,
1783 // 'hitoyoshi' => TRUE,
1785 // 'kumamoto' => TRUE,
1795 'fukushima' => TRUE,
1798 'hiroshima' => TRUE,
1805 'kagoshima' => TRUE,
1808 'kitakyushu'=> TRUE,
1833 'tokushima' => TRUE,
1839 'yamaguchi' => TRUE,
1840 'yamanashi' => TRUE,
1845 // NIC : http://www.nic.net.ua/
1846 // Whois: http://whois.com.ua/
1848 // policy for alternative 2nd level domain names (a2ld)
1849 // http://www.nic.net.ua/doc/a2ld
1850 // http://whois.com.ua/
1851 'cherkassy' => TRUE,
1852 'chernigov' => TRUE,
1853 'chernovtsy' => TRUE,
1860 'dnepropetrovsk' => TRUE,
1866 'ivano-frankivsk' => TRUE,
1871 'kirovograd' => TRUE,
1889 'sebastopol' => TRUE,
1897 'zaporizhzhe' => TRUE,
1903 // ccTLD: United Kingdom
1904 // NIC : http://www.nic.uk/
1906 // Second Level Domains
1907 // http://www.nic.uk/registrants/aboutdomainnames/sld/
1917 // Delegated Second Level Domains
1918 // http://www.nic.uk/registrants/aboutdomainnames/sld/delegated/
1927 // ccTLD: United States of America
1928 // NIC : http://nic.us/
1929 // Whois: http://whois.us/
1941 // United States Postal Service: State abbreviations (for postal codes)
1942 // http://www.usps.com/ncsc/lookups/abbreviations.html
1943 'ak' => TRUE, // Alaska
1944 'al' => TRUE, // Alabama
1945 'ar' => TRUE, // Arkansas
1946 'as' => TRUE, // American samoa
1947 'az' => TRUE, // Arizona
1948 'ca' => TRUE, // California
1949 'co' => TRUE, // Colorado
1950 'ct' => TRUE, // Connecticut
1951 'dc' => TRUE, // District of Columbia
1952 'de' => TRUE, // Delaware
1953 'fl' => TRUE, // Florida
1954 'fm' => TRUE, // Federated states of Micronesia
1955 'ga' => TRUE, // Georgia
1956 'gu' => TRUE, // Guam
1957 'hi' => TRUE, // Hawaii
1958 'ia' => TRUE, // Iowa
1959 'id' => TRUE, // Idaho
1960 'il' => TRUE, // Illinois
1961 'in' => TRUE, // Indiana
1962 'ks' => TRUE, // Kansas
1963 'ky' => TRUE, // Kentucky
1964 'la' => TRUE, // Louisiana
1965 'ma' => TRUE, // Massachusetts
1966 'md' => TRUE, // Maryland
1967 'me' => TRUE, // Maine
1968 'mh' => TRUE, // Marshall Islands
1969 'mi' => TRUE, // Michigan
1970 'mn' => TRUE, // Minnesota
1971 'mo' => TRUE, // Missouri
1972 'mp' => TRUE, // Northern mariana islands
1973 'ms' => TRUE, // Mississippi
1974 'mt' => TRUE, // Montana
1975 'nc' => TRUE, // North Carolina
1976 'nd' => TRUE, // North Dakota
1977 'ne' => TRUE, // Nebraska
1978 'nh' => TRUE, // New Hampshire
1979 'nj' => TRUE, // New Jersey
1980 'nm' => TRUE, // New Mexico
1981 'nv' => TRUE, // Nevada
1982 'ny' => TRUE, // New York
1983 'oh' => TRUE, // Ohio
1984 'ok' => TRUE, // Oklahoma
1985 'or' => TRUE, // Oregon
1986 'pa' => TRUE, // Pennsylvania
1987 'pr' => TRUE, // Puerto Rico
1988 'pw' => TRUE, // Palau
1989 'ri' => TRUE, // Rhode Island
1990 'sc' => TRUE, // South Carolina
1991 'sd' => TRUE, // South Dakota
1992 'tn' => TRUE, // Tennessee
1993 'tx' => TRUE, // Texas
1994 'ut' => TRUE, // Utah
1995 'va' => TRUE, // Virginia
1996 'vi' => TRUE, // Virgin Islands
1997 'vt' => TRUE, // Vermont
1998 'wa' => TRUE, // Washington
1999 'wi' => TRUE, // Wisconsin
2000 'wv' => TRUE, // West Virginia
2001 'wy' => TRUE, // Wyoming
2005 if (! is_string($fqdn)) return '';
2008 $dcursor = & $domain;
2009 $array = array_reverse(explode('.', $fqdn));
2012 $acursor = $array[$i];
2013 if (is_array($dcursor) && isset($dcursor[$acursor])) {
2014 $result[] = & $array[$i];
2015 $dcursor = & $dcursor[$acursor];
2017 if (! $parent && isset($acursor)) {
2018 $result[] = & $array[$i]; // Whois servers must know this subdomain
2025 // Implicit responsibility: Top-Level-Domains must not be yours
2026 // 'bar.foo.something' => 'foo.something'
2027 if ($implicit && count($result) == 1 && count($array) > 1) {
2028 $result[] = & $array[1];
2031 return $result ? implode('.', array_reverse($result)) : '';
2035 // ---------------------
2039 function spam_dispose()
2041 get_blocklist(NULL);
2044 // Common bahavior for blocking
2045 // NOTE: Call this function from various blocking feature, to disgueise the reason 'why blocked'
2046 function spam_exit($mode = '', $data = array())
2055 echo('<pre>' . "\n");
2056 echo htmlspecialchars(var_export($data, TRUE));
2057 echo('</pre>' . "\n");
2061 if ($exit) exit; // Force exit
2065 // ---------------------
2068 // TODO: Record them
2069 // Simple/fast spam filter ($target: 'a string' or an array())
2070 function pkwk_spamfilter($action, $page, $target = array('title' => ''), $method = array(), $exitmode = '')
2072 $progress = check_uri_spam($target, $method);
2074 if (empty($progress['is_spam'])) {
2077 $target = strings($target, 0); // Removing "\0" etc
2078 pkwk_spamnotify($action, $page, $target, $progress, $method);
2079 spam_exit($exitmode, $progress);
2083 // ---------------------
2084 // PukiWiki original
2086 // Mail to administrator(s)
2087 function pkwk_spamnotify($action, $page, $target = array('title' => ''), $progress = array(), $method = array())
2089 global $notify, $notify_subject;
2091 if (! $notify) return;
2093 $asap = isset($method['asap']);
2095 $summary['ACTION'] = 'Blocked by: ' . summarize_spam_progress($progress, TRUE);
2097 $summary['METRICS'] = summarize_spam_progress($progress);
2100 $tmp = summarize_detail_badhost($progress);
2101 if ($tmp != '') $summary['DETAIL_BADHOST'] = $tmp;
2103 $tmp = summarize_detail_newtral($progress);
2104 if (! $asap && $tmp != '') $summary['DETAIL_NEUTRAL_HOST'] = $tmp;
2106 $summary['COMMENT'] = $action;
2107 $summary['PAGE'] = '[blocked] ' . (is_pagename($page) ? $page : '');
2108 $summary['URI'] = get_script_uri() . '?' . rawurlencode($page);
2109 $summary['USER_AGENT'] = TRUE;
2110 $summary['REMOTE_ADDR'] = TRUE;
2111 pkwk_mail_notify($notify_subject, var_export($target, TRUE), $summary, TRUE);