2 // $Id: spam.php,v 1.191 2007/06/24 03:13: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 = 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 // Note: mb_ereg_replace() is one of mbstring extension's functions
115 // and need to init its encoding.
116 function strings($binary = '', $min_len = 4, $ignore_space = FALSE, $multibyte = FALSE)
119 $binary = (is_array($binary) || $binary === TRUE) ? '' : strval($binary);
121 $regex = $ignore_space ?
122 '[^[:graph:] \t\n]+' : // Remove "\0" etc, and readable spaces
123 '[^[:graph:][:space:]]+'; // Preserve readable spaces if possible
125 $binary = $multibyte ?
126 mb_ereg_replace($regex, "\n", $binary) :
127 preg_replace('/' . $regex . '/s', "\n", $binary);
130 $binary = preg_replace(
145 // The last character seems "\n" or not
146 $br = (! empty($binary) && $binary[strlen($binary) - 1] == "\n") ? "\n" : '';
148 $min_len = min(1024, intval($min_len));
149 $regex = '/^.{' . $min_len . ',}/S';
150 $binary = implode("\n", preg_grep($regex, explode("\n", $binary))) . $br;
156 // Reverse $string with specified delimiter
157 function delimiter_reverse($string = 'foo.bar.example.com', $from_delim = '.', $to_delim = '.')
159 if (! is_string($string) || ! is_string($from_delim) || ! is_string($to_delim))
162 // com.example.bar.foo
163 return implode($to_delim, array_reverse(explode($from_delim, $string)));
167 // ---------------------
170 // Return an array of URIs in the $string
171 // [OK] http://nasty.example.org#nasty_string
172 // [OK] http://nasty.example.org:80/foo/xxx#nasty_string/bar
173 // [OK] ftp://nasty.example.org:80/dfsdfs
174 // [OK] ftp://cnn.example.com&story=breaking_news@10.0.0.1/top_story.htm (from RFC3986)
175 function uri_pickup($string = '')
177 if (! is_string($string)) return array();
179 // Not available for: IDN(ignored)
182 // scheme://userinfo@host:port/path/or/pathinfo/maybefile.and?query=string#fragment
183 // Refer RFC3986 (Regex below is not strict)
184 '#(\b[a-z][a-z0-9.+-]{1,8}):[/\\\]+' . // 1: Scheme
186 '([^\s<>"\'\[\]/\#?@]*)' . // 2: Userinfo (Username)
190 '\[[0-9a-f:.]+\]' . '|' . // IPv6([colon-hex and dot]): RFC2732
191 '(?:[0-9]{1,3}\.){3}[0-9]{1,3}' . '|' . // IPv4(dot-decimal): 001.22.3.44
192 '[a-z0-9_-][a-z0-9_.-]+[a-z0-9_-]' . // hostname(FQDN) : foo.example.org
194 '(?::([0-9]*))?' . // 4: Port
195 '((?:/+[^\s<>"\'\[\]/\#]+)*/+)?' . // 5: Directory path or path-info
196 '([^\s<>"\'\[\]\#?]+)?' . // 6: File?
197 '(?:\?([^\s<>"\'\[\]\#]+))?' . // 7: Query string
198 '(?:\#([a-z0-9._~%!$&\'()*+,;=:@-]*))?' . // 8: Fragment
200 $string, $array, PREG_SET_ORDER | PREG_OFFSET_CAPTURE
204 static $parts = array(
205 1 => 'scheme', 2 => 'userinfo', 3 => 'host', 4 => 'port',
206 5 => 'path', 6 => 'file', 7 => 'query', 8 => 'fragment'
208 $default = array('');
209 foreach(array_keys($array) as $uri) {
210 $_uri = & $array[$uri];
211 array_rename_keys($_uri, $parts, TRUE, $default);
212 $offset = $_uri['scheme'][1]; // Scheme's offset = URI's offset
213 foreach(array_keys($_uri) as $part) {
214 $_uri[$part] = & $_uri[$part][0]; // Remove offsets
218 foreach(array_keys($array) as $uri) {
219 $_uri = & $array[$uri];
220 if ($_uri['scheme'] === '') {
221 unset($array[$uri]); // Considererd harmless
224 unset($_uri[0]); // Matched string itself
225 $_uri['area']['offset'] = $offset; // Area offset for area_measure()
231 // Normalize an array of URI arrays
232 // NOTE: Give me the uri_pickup() results
233 function uri_pickup_normalize(& $pickups, $destructive = TRUE)
235 if (! is_array($pickups)) return $pickups;
238 foreach (array_keys($pickups) as $key) {
239 $_key = & $pickups[$key];
240 $_key['scheme'] = isset($_key['scheme']) ? scheme_normalize($_key['scheme']) : '';
241 $_key['host'] = isset($_key['host']) ? host_normalize($_key['host']) : '';
242 $_key['port'] = isset($_key['port']) ? port_normalize($_key['port'], $_key['scheme'], FALSE) : '';
243 $_key['path'] = isset($_key['path']) ? strtolower(path_normalize($_key['path'])) : '';
244 $_key['file'] = isset($_key['file']) ? file_normalize($_key['file']) : '';
245 $_key['query'] = isset($_key['query']) ? query_normalize($_key['query']) : '';
246 $_key['fragment'] = isset($_key['fragment']) ? strtolower($_key['fragment']) : '';
249 foreach (array_keys($pickups) as $key) {
250 $_key = & $pickups[$key];
251 $_key['scheme'] = isset($_key['scheme']) ? scheme_normalize($_key['scheme']) : '';
252 $_key['host'] = isset($_key['host']) ? strtolower($_key['host']) : '';
253 $_key['port'] = isset($_key['port']) ? port_normalize($_key['port'], $_key['scheme'], FALSE) : '';
254 $_key['path'] = isset($_key['path']) ? path_normalize($_key['path']) : '';
261 // An URI array => An URI (See uri_pickup())
263 // $pickups = uri_pickup('a string include some URIs');
265 // foreach (array_keys($pickups) as $key) {
266 // $uris[$key] = uri_pickup_implode($pickups[$key]);
268 function uri_pickup_implode($uri = array())
270 if (empty($uri) || ! is_array($uri)) return NULL;
273 if (isset($uri['scheme']) && $uri['scheme'] !== '') {
274 $tmp[] = & $uri['scheme'];
277 if (isset($uri['userinfo']) && $uri['userinfo'] !== '') {
278 $tmp[] = & $uri['userinfo'];
281 if (isset($uri['host']) && $uri['host'] !== '') {
282 $tmp[] = & $uri['host'];
284 if (isset($uri['port']) && $uri['port'] !== '') {
286 $tmp[] = & $uri['port'];
288 if (isset($uri['path']) && $uri['path'] !== '') {
289 $tmp[] = & $uri['path'];
291 if (isset($uri['file']) && $uri['file'] !== '') {
292 $tmp[] = & $uri['file'];
294 if (isset($uri['query']) && $uri['query'] !== '') {
296 $tmp[] = & $uri['query'];
298 if (isset($uri['fragment']) && $uri['fragment'] !== '') {
300 $tmp[] = & $uri['fragment'];
303 return implode('', $tmp);
306 // $array['something'] => $array['wanted']
307 function array_rename_keys(& $array, $keys = array('from' => 'to'), $force = FALSE, $default = '')
309 if (! is_array($array) || ! is_array($keys)) return FALSE;
311 // Nondestructive test
313 foreach(array_keys($keys) as $from)
314 if (! isset($array[$from]))
317 foreach($keys as $from => $to) {
318 if ($from === $to) continue;
319 if (! $force || isset($array[$from])) {
320 $array[$to] = & $array[$from];
321 unset($array[$from]);
323 $array[$to] = $default;
330 // ---------------------
333 // Pickup all of markup areas
334 function area_pickup($string = '', $method = array())
337 if (empty($method)) return $area;
339 // Anchor tag pair by preg_match and preg_match_all()
341 // [OK] <a href= >Good site!</a>
342 // [OK] <a href= "#" >test</a>
343 // [OK] <a href="http://nasty.example.com">visit http://nasty.example.com/</a>
344 // [OK] <a href=\'http://nasty.example.com/\' >discount foobar</a>
345 // [NG] <a href="http://ng.example.com">visit http://ng.example.com _not_ended_
346 $regex = '#<a\b[^>]*\bhref\b[^>]*>.*?</a\b[^>]*(>)#is';
347 if (isset($method['area_anchor'])) {
349 $count = isset($method['asap']) ?
350 preg_match($regex, $string) :
351 preg_match_all($regex, $string, $areas);
352 if (! empty($count)) $area['area_anchor'] = $count;
354 if (isset($method['uri_anchor'])) {
356 preg_match_all($regex, $string, $areas, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
357 foreach(array_keys($areas) as $_area) {
358 $areas[$_area] = array(
359 $areas[$_area][0][1], // Area start (<a href>)
360 $areas[$_area][1][1], // Area end (</a>)
363 if (! empty($areas)) $area['uri_anchor'] = $areas;
366 // phpBB's "BBCode" pair by preg_match and preg_match_all()
368 // [OK] [url]http://nasty.example.com/[/url]
369 // [OK] [link]http://nasty.example.com/[/link]
370 // [OK] [url=http://nasty.example.com]visit http://nasty.example.com/[/url]
371 // [OK] [link http://nasty.example.com/]buy something[/link]
372 $regex = '#\[(url|link)\b[^\]]*\].*?\[/\1\b[^\]]*(\])#is';
373 if (isset($method['area_bbcode'])) {
375 $count = isset($method['asap']) ?
376 preg_match($regex, $string) :
377 preg_match_all($regex, $string, $areas, PREG_SET_ORDER);
378 if (! empty($count)) $area['area_bbcode'] = $count;
380 if (isset($method['uri_bbcode'])) {
382 preg_match_all($regex, $string, $areas, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
383 foreach(array_keys($areas) as $_area) {
384 $areas[$_area] = array(
385 $areas[$_area][0][1], // Area start ([url])
386 $areas[$_area][2][1], // Area end ([/url])
389 if (! empty($areas)) $area['uri_bbcode'] = $areas;
392 // Various Wiki syntax
393 // [text_or_uri>text_or_uri]
394 // [text_or_uri:text_or_uri]
395 // [text_or_uri|text_or_uri]
396 // [text_or_uri->text_or_uri]
397 // [text_or_uri text_or_uri] // MediaWiki
398 // MediaWiki: [http://nasty.example.com/ visit http://nasty.example.com/]
403 // If in doubt, it's a little doubtful
404 // if (Area => inside <= Area) $brief += -1
405 function area_measure($areas, & $array, $belief = -1, $a_key = 'area', $o_key = 'offset')
407 if (! is_array($areas) || ! is_array($array)) return;
409 $areas_keys = array_keys($areas);
410 foreach(array_keys($array) as $u_index) {
411 $offset = isset($array[$u_index][$o_key]) ?
412 intval($array[$u_index][$o_key]) : 0;
413 foreach($areas_keys as $a_index) {
414 if (isset($array[$u_index][$a_key])) {
415 $offset_s = intval($areas[$a_index][0]);
416 $offset_e = intval($areas[$a_index][1]);
417 // [Area => inside <= Area]
418 if ($offset_s < $offset && $offset < $offset_e) {
419 $array[$u_index][$a_key] += $belief;
426 // ---------------------
429 // Domain exposure callback (See spam_uri_pickup_preprocess())
430 // http://victim.example.org/?foo+site:nasty.example.com+bar
431 // => http://nasty.example.com/?refer=victim.example.org
432 // NOTE: 'refer=' is not so good for (at this time).
433 // Consider about using IP address of the victim, try to avoid that.
434 function _preg_replace_callback_domain_exposure($matches = array())
438 // Preserve the victim URI as a complicity or ...
439 if (isset($matches[5])) {
441 $matches[1] . '://' . // scheme
442 $matches[2] . '/' . // victim.example.org
443 $matches[3]; // The rest of all (before victim)
447 if (isset($matches[4])) {
449 $matches[1] . '://' . // scheme
450 $matches[4] . // nasty.example.com
451 '/?refer=' . strtolower($matches[2]) . // victim.example.org
458 // Preprocess: Removing uninterest part for URI detection
459 function spam_uri_removing_hocus_pocus($binary = '', $method = array())
461 $length = 4 ; // 'http'(1) and '://'(2) and 'fqdn'(1)
462 if (is_array($method)) {
463 // '<a'(2) or 'href='(5) or '>'(1) or '</a>'(4)
464 // '[uri'(4) or ']'(1) or '[/uri]'(6)
465 if (isset($method['area_anchor']) || isset($method['uri_anchor']) ||
466 isset($method['area_bbcode']) || isset($method['uri_bbcode']))
467 $length = 1; // Seems not effective
470 // Removing sequential spaces and too short lines
471 $binary = strings($binary, $length, TRUE, FALSE); // Multibyte NOT needed
473 // Remove words (has no '<>[]:') between spaces
474 $binary = preg_replace('/[ \t][\w.,()\ \t]+[ \t]/', ' ', $binary);
479 // Preprocess: rawurldecode() and adding space(s) and something
480 // to detect/count some URIs _if possible_
481 // NOTE: It's maybe danger to var_dump(result). [e.g. 'javascript:']
482 // [OK] http://victim.example.org/?site:nasty.example.org
483 // [OK] http://victim.example.org/nasty.example.org
484 // [OK] http://victim.example.org/go?http%3A%2F%2Fnasty.example.org
485 // [OK] http://victim.example.org/http://nasty.example.org
486 function spam_uri_pickup_preprocess($string = '', $method = array())
488 if (! is_string($string)) return '';
490 $string = spam_uri_removing_hocus_pocus(rawurldecode($string), $method);
491 //var_dump(htmlspecialchars($string));
493 // Domain exposure (simple)
494 // http://victim.example.org/nasty.example.org/path#frag
495 // => http://nasty.example.org/?refer=victim.example.org and original
496 $string = preg_replace(
499 'ime\.nu' . '|' . // 2ch.net
500 'ime\.st' . '|' . // 2ch.net
501 'link\.toolbot\.com' . '|' .
504 '/([a-z0-9.%_-]+\.[a-z0-9.%_-]+)#i', // nasty.example.org
505 'http://$2/?refer=$1 $0', // Preserve $0 or remove?
509 // Domain exposure (gate-big5)
510 // http://victim.example.org/gate/big5/nasty.example.org/path
511 // => http://nasty.example.org/?refer=victim.example.org and original
512 $string = preg_replace(
515 'big5.51job.com' . '|' .
516 'big5.china.com' . '|' .
517 'big5.xinhuanet.com' . '|' .
520 '/([a-z0-9.%_-]+\.[a-z0-9.%_-]+)' .
521 '#i', // nasty.example.org
522 'http://$2/?refer=$1 $0', // Preserve $0 or remove?
526 // Domain exposure (See _preg_replace_callback_domain_exposure())
527 $string = preg_replace_callback(
531 // Something Google: http://www.google.com/supported_domains
532 '(?:[a-z0-9.]+\.)?google\.[a-z]{2,3}(?:\.[a-z]{2})?' .
535 '(?:[a-z0-9.]+\.)?altavista.com' .
539 '([a-z0-9?=&.%_/\'\\\+-]+)' . // path/?query=foo+bar+
540 '\bsite:([a-z0-9.%_-]+\.[a-z0-9.%_-]+)' . // site:nasty.example.com
541 //'()' . // Preserve or remove?
544 '_preg_replace_callback_domain_exposure',
548 // URI exposure (uriuri => uri uri)
549 $string = preg_replace(
551 '#(?<! )(?:https?|ftp):/#i',
552 // '#[a-z][a-z0-9.+-]{1,8}://#i',
553 // '#[a-z][a-z0-9.+-]{1,8}://#i'
562 // Main function of spam-uri pickup,
563 // A wrapper function of uri_pickup()
564 function spam_uri_pickup($string = '', $method = array())
566 if (! is_array($method) || empty($method)) {
567 $method = check_uri_spam_method();
570 $string = spam_uri_pickup_preprocess($string, $method);
572 $array = uri_pickup($string);
574 // Area elevation of URIs, for '(especially external)link' intension
575 if (! empty($array)) {
577 if (isset($method['uri_anchor'])) $_method['uri_anchor'] = & $method['uri_anchor'];
578 if (isset($method['uri_bbcode'])) $_method['uri_bbcode'] = & $method['uri_bbcode'];
579 $areas = area_pickup($string, $_method, TRUE);
580 if (! empty($areas)) {
581 $area_shadow = array();
582 foreach (array_keys($array) as $key) {
583 $area_shadow[$key] = & $array[$key]['area'];
584 foreach (array_keys($_method) as $_key) {
585 $area_shadow[$key][$_key] = 0;
588 foreach (array_keys($_method) as $_key) {
589 if (isset($areas[$_key])) {
590 area_measure($areas[$_key], $area_shadow, 1, $_key);
596 // Remove 'offset's for area_measure()
597 foreach(array_keys($array) as $key)
598 unset($array[$key]['area']['offset']);
604 // ---------------------
607 // Scheme normalization: Renaming the schemes
608 // snntp://example.org => nntps://example.org
609 // NOTE: Keep the static lists simple. See also port_normalize().
610 function scheme_normalize($scheme = '', $abbrevs_harmfull = TRUE)
612 // Abbreviations they have no intention of link
613 static $abbrevs = array(
618 // Aliases => normalized ones
619 static $aliases = array(
629 if (! is_string($scheme)) return '';
631 $scheme = strtolower($scheme);
632 if (isset($abbrevs[$scheme])) {
633 $scheme = $abbrevs_harmfull ? $abbrevs[$scheme] : '';
635 if (isset($aliases[$scheme])) {
636 $scheme = $aliases[$scheme];
642 // Hostname normlization (Destructive)
643 // www.foo => www.foo ('foo' seems TLD)
644 // www.foo.bar => foo.bar
645 // www.10.20 => www.10.20 (Invalid hostname)
647 // 'www' is mostly used as traditional hostname of WWW server.
648 // 'www.foo.bar' may be identical with 'foo.bar'.
649 function host_normalize($host = '')
651 if (! is_string($host)) return '';
653 $host = strtolower($host);
655 if (preg_match('/^www\.(.+\.[a-z]+)$/', $host, $matches)) {
662 // Port normalization: Suppress the (redundant) default port
663 // HTTP://example.org:80/ => http://example.org/
664 // HTTP://example.org:8080/ => http://example.org:8080/
665 // HTTPS://example.org:443/ => https://example.org/
666 function port_normalize($port, $scheme, $scheme_normalize = FALSE)
668 // Schemes that users _maybe_ want to add protocol-handlers
669 // to their web browsers. (and attackers _maybe_ want to use ...)
670 // Reference: http://www.iana.org/assignments/port-numbers
671 static $array = array(
672 // scheme => default port
698 // intval() converts '0-1' to '0', so preg_match() rejects these invalid ones
699 if (! is_numeric($port) || $port < 0 || preg_match('/[^0-9]/i', $port))
702 $port = intval($port);
703 if ($scheme_normalize) $scheme = scheme_normalize($scheme);
704 if (isset($array[$scheme]) && $port == $array[$scheme])
705 $port = ''; // Ignore the defaults
710 // Path normalization
711 // http://example.org => http://example.org/
712 // http://example.org#hoge => http://example.org/#hoge
713 // http://example.org/path/a/b/./c////./d => http://example.org/path/a/b/c/d
714 // http://example.org/path/../../a/../back => http://example.org/back
715 function path_normalize($path = '', $divider = '/', $add_root = TRUE)
717 if (! is_string($divider)) return is_string($path) ? $path : '';
720 $first_div = & $divider;
724 if (! is_string($path) || $path == '') return $first_div;
726 if (strpos($path, $divider, strlen($path) - strlen($divider)) === FALSE) {
729 $last_div = & $divider;
732 $array = explode($divider, $path);
734 // Remove paddings ('//' and '/./')
735 foreach(array_keys($array) as $key) {
736 if ($array[$key] == '' || $array[$key] == '.') {
741 // Remove back-tracks ('/../')
743 foreach($array as $value) {
744 if ($value == '..') {
747 array_push($tmp, $value);
755 return $first_div . implode($divider, $array) . $last_div;
759 // DirectoryIndex normalize (Destructive and rough)
760 // TODO: sample.en.ja.html.gz => sample.html
761 function file_normalize($file = 'index.html.en')
763 static $simple_defaults = array(
764 'default.htm' => TRUE,
765 'default.html' => TRUE,
766 'default.asp' => TRUE,
767 'default.aspx' => TRUE,
768 'index' => TRUE, // Some system can omit the suffix
771 static $content_suffix = array(
772 // index.xxx, sample.xxx
787 static $language_suffix = array(
788 // Reference: Apache 2.0.59 'AddLanguage' default
817 // Reference: Apache 2.0.59 default 'index.html' variants
823 static $charset_suffix = array(
824 // Reference: Apache 2.0.59 'AddCharset' default
825 'iso8859-1' => TRUE, // ISO-8859-1
826 'latin1' => TRUE, // ISO-8859-1
827 'iso8859-2' => TRUE, // ISO-8859-2
828 'latin2' => TRUE, // ISO-8859-2
829 'cen' => TRUE, // ISO-8859-2
830 'iso8859-3' => TRUE, // ISO-8859-3
831 'latin3' => TRUE, // ISO-8859-3
832 'iso8859-4' => TRUE, // ISO-8859-4
833 'latin4' => TRUE, // ISO-8859-4
834 'iso8859-5' => TRUE, // ISO-8859-5
835 'latin5' => TRUE, // ISO-8859-5
836 'cyr' => TRUE, // ISO-8859-5
837 'iso-ru' => TRUE, // ISO-8859-5
838 'iso8859-6' => TRUE, // ISO-8859-6
839 'latin6' => TRUE, // ISO-8859-6
840 'arb' => TRUE, // ISO-8859-6
841 'iso8859-7' => TRUE, // ISO-8859-7
842 'latin7' => TRUE, // ISO-8859-7
843 'grk' => TRUE, // ISO-8859-7
844 'iso8859-8' => TRUE, // ISO-8859-8
845 'latin8' => TRUE, // ISO-8859-8
846 'heb' => TRUE, // ISO-8859-8
847 'iso8859-9' => TRUE, // ISO-8859-9
848 'latin9' => TRUE, // ISO-8859-9
849 'trk' => TRUE, // ISO-8859-9
850 'iso2022-jp'=> TRUE, // ISO-2022-JP
851 'jis' => TRUE, // ISO-2022-JP
852 'iso2022-kr'=> TRUE, // ISO-2022-KR
853 'kis' => TRUE, // ISO-2022-KR
854 'iso2022-cn'=> TRUE, // ISO-2022-CN
855 'cis' => TRUE, // ISO-2022-CN
857 'cp-1251' => TRUE, // ru, WINDOWS-1251
858 'win-1251' => TRUE, // ru, WINDOWS-1251
859 'cp866' => TRUE, // ru
860 'koi8-r' => TRUE, // ru, KOI8-r
861 'koi8-ru' => TRUE, // ru, KOI8-r
862 'koi8-uk' => TRUE, // ru, KOI8-ru
863 'ua' => TRUE, // ru, KOI8-ru
864 'ucs2' => TRUE, // ru, ISO-10646-UCS-2
865 'ucs4' => TRUE, // ru, ISO-10646-UCS-4
868 // Reference: Apache 2.0.59 default 'index.html' variants
873 // May uncompress by web browsers on the fly
874 // Must be at the last of the filename
875 // Reference: Apache 2.0.59 'AddEncoding'
876 static $encoding_suffix = array(
881 if (! is_string($file)) return '';
882 $_file = strtolower($file);
883 if (isset($simple_defaults[$_file])) return '';
886 // Roughly removing language/character-set/encoding suffixes
888 // * Apache 2 document about 'Content-negotiaton', 'mod_mime' and 'mod_negotiation'
889 // http://httpd.apache.org/docs/2.0/content-negotiation.html
890 // http://httpd.apache.org/docs/2.0/mod/mod_mime.html
891 // http://httpd.apache.org/docs/2.0/mod/mod_negotiation.html
892 // * http://www.iana.org/assignments/character-sets
893 // * RFC3066: Tags for the Identification of Languages
894 // http://www.ietf.org/rfc/rfc3066.txt
895 // * ISO 639: codes of 'language names'
896 $suffixes = explode('.', $_file);
897 $body = array_shift($suffixes);
899 // Remove the last .gz/.z
900 $last_key = end(array_keys($suffixes));
901 if (isset($encoding_suffix[$suffixes[$last_key]])) {
902 unset($suffixes[$last_key]);
905 // Cut language and charset suffixes
906 foreach($suffixes as $key => $value){
907 if (isset($language_suffix[$value]) || isset($charset_suffix[$value])) {
908 unset($suffixes[$key]);
911 if (empty($suffixes)) return $body;
914 $count = count($suffixes);
916 $current = current($suffixes);
917 if ($body == 'index' && $count == 1 && isset($content_suffix[$current])) return '';
922 // Sort query-strings if possible (Destructive and rough)
923 // [OK] &&&&f=d&b&d&c&a=0dd => a=0dd&b&c&d&f=d
924 // [OK] nothing==&eg=dummy&eg=padding&eg=foobar => eg=foobar
925 function query_normalize($string = '', $equal = TRUE, $equal_cutempty = TRUE, $stortolower = TRUE)
927 if (! is_string($string)) return '';
928 if ($stortolower) $string = strtolower($string);
930 $array = explode('&', $string);
932 // Remove '&' paddings
933 foreach(array_keys($array) as $key) {
934 if ($array[$key] == '') {
939 // Consider '='-sepalated input and paddings
941 $equals = $not_equals = array();
942 foreach ($array as $part) {
943 if (strpos($part, '=') === FALSE) {
944 $not_equals[] = $part;
946 list($key, $value) = explode('=', $part, 2);
947 $value = ltrim($value, '=');
948 if (! $equal_cutempty || $value != '') {
949 $equals[$key] = $value;
954 $array = & $not_equals;
955 foreach ($equals as $key => $value) {
956 $array[] = $key . '=' . $value;
962 return implode('&', $array);
965 // ---------------------
966 // Part One : Checker
968 // Rough implementation of globbing
970 // USAGE: $regex = '/^' . generate_glob_regex('*.txt', '/') . '$/i';
972 function generate_glob_regex($string = '', $divider = '/')
974 static $from = array(
977 // 22 => '[', // Maybe cause regex compilation error (e.g. '[]')
993 if (! is_string($string)) return '';
995 $string = str_replace($from, $mid, $string); // Hide
996 $string = preg_quote($string, $divider);
997 $string = str_replace($mid, $to, $string); // Unhide
1002 // Rough hostname checker
1004 // TODO: Strict digit, 0x, CIDR, IPv6
1005 function is_ip($string = '')
1007 if (preg_match('/^' .
1008 '(?:[0-9]{1,3}\.){3}[0-9]{1,3}' . '|' .
1009 '(?:[0-9]{1,3}\.){1,3}' . '$/',
1011 return 4; // Seems IPv4(dot-decimal)
1013 return 0; // Seems not IP
1017 // Generate host (FQDN, IPv4, ...) regex
1018 // 'localhost' : Matches with 'localhost' only
1019 // 'example.org' : Matches with 'example.org' only (See host_normalize() about 'www')
1020 // '.example.org' : Matches with ALL FQDN ended with '.example.org'
1021 // '*.example.org' : Almost the same of '.example.org' except 'www.example.org'
1022 // '10.20.30.40' : Matches with IPv4 address '10.20.30.40' only
1023 // [TODO] '192.' : Matches with all IPv4 hosts started with '192.'
1024 // TODO: IPv4, CIDR?, IPv6
1025 function generate_host_regex($string = '', $divider = '/')
1027 if (! is_string($string)) return '';
1029 if (mb_strpos($string, '.') === FALSE)
1030 return generate_glob_regex($string, $divider);
1033 if (is_ip($string)) {
1035 return generate_glob_regex($string, $divider);
1037 // FQDN or something
1038 $part = explode('.', $string, 2);
1039 if ($part[0] == '') {
1040 $part[0] = '(?:.*\.)?'; // And all related FQDN
1041 } else if ($part[0] == '*') {
1042 $part[0] = '.*\.'; // All subdomains/hosts only
1044 return generate_glob_regex($string, $divider);
1046 $part[1] = generate_glob_regex($part[1], $divider);
1047 return implode('', $part);
1051 function get_blocklist($list = '')
1055 if ($list === NULL) {
1056 $regexes = NULL; // Unset
1060 if (! isset($regexes)) {
1062 if (file_exists(SPAM_INI_FILE)) {
1063 $blocklist = array();
1064 include(SPAM_INI_FILE);
1065 // $blocklist['badhost'] = array(
1066 // '*.blogspot.com', // Blog services's subdomains (only)
1067 // 'IANA-examples' => '#^(?:.*\.)?example\.(?:com|net|org)$#',
1069 if (isset($blocklist['list'])) {
1070 $regexes['list'] = & $blocklist['list'];
1073 $blocklist['list'] = array(
1074 'goodhost' => FALSE,
1078 foreach(array_keys($blocklist['list']) as $_list) {
1079 if (! isset($blocklist[$_list])) continue;
1080 foreach ($blocklist[$_list] as $key => $value) {
1081 if (is_array($value)) {
1082 $regexes[$_list][$key] = array();
1083 foreach($value as $_key => $_value) {
1084 get_blocklist_add($regexes[$_list][$key], $_key, $_value);
1087 get_blocklist_add($regexes[$_list], $key, $value);
1090 unset($blocklist[$_list]);
1096 return $regexes; // ALL
1097 } else if (isset($regexes[$list])) {
1098 return $regexes[$list];
1104 // Subroutine of get_blocklist()
1105 function get_blocklist_add(& $array, $key = 0, $value = '*.example.org')
1107 if (is_string($key)) {
1108 $array[$key] = & $value; // Treat $value as a regex
1110 $array[$value] = '/^' . generate_host_regex($value, '/') . '$/i';
1114 // Blocklist metrics: Separate $host, to $blocked and not blocked
1115 function blocklist_distiller(& $hosts, $keys = array('goodhost', 'badhost'), $asap = FALSE)
1117 if (! is_array($hosts)) $hosts = array($hosts);
1118 if (! is_array($keys)) $keys = array($keys);
1120 $list = get_blocklist('list');
1123 foreach($keys as $key){
1124 foreach (get_blocklist($key) as $label => $regex) {
1125 if (is_array($regex)) {
1126 foreach($regex as $_label => $_regex) {
1127 $group = preg_grep($_regex, $hosts);
1129 $hosts = array_diff($hosts, $group);
1130 $blocked[$key][$label][$_label] = $group;
1131 if ($asap && $list[$key]) break;
1135 $group = preg_grep($regex, $hosts);
1137 $hosts = array_diff($hosts, $group);
1138 $blocked[$key][$label] = $group;
1139 if ($asap && $list[$key]) break;
1148 // Default (enabled) methods and thresholds (for content insertion)
1149 function check_uri_spam_method($times = 1, $t_area = 0, $rule = TRUE)
1151 $times = intval($times);
1152 $t_area = intval($t_area);
1156 'quantity' => 8 * $times, // Allow N URIs
1157 'non_uniqhost' => 3 * $times, // Allow N duped (and normalized) Hosts
1158 //'non_uniquri'=> 3 * $times, // Allow N duped (and normalized) URIs
1161 'area_anchor' => $t_area, // Using <a href> HTML tag
1162 'area_bbcode' => $t_area, // Using [url] or [link] BBCode
1163 //'uri_anchor' => $t_area, // URI inside <a href> HTML tag
1164 //'uri_bbcode' => $t_area, // URI inside [url] or [link] BBCode
1169 //'asap' => TRUE, // Quit or return As Soon As Possible
1170 'uniqhost' => TRUE, // Show uniq host (at block notification mail)
1171 'badhost' => TRUE, // Check badhost
1177 // Remove non-$positive values
1178 foreach (array_keys($positive) as $key) {
1179 if ($positive[$key] < 0) unset($positive[$key]);
1182 return $positive + $bool;
1185 // Simple/fast spam check
1186 function check_uri_spam($target = '', $method = array())
1191 // Theme to do => Dummy, optional value, or optional array()
1193 //'uniqhost' => TRUE,
1194 //'non_uniqhost'=> 3,
1195 //'non_uniquri' => 3,
1196 //'badhost' => TRUE,
1197 //'area_anchor' => 0,
1198 //'area_bbcode' => 0,
1199 //'uri_anchor' => 0,
1200 //'uri_bbcode' => 0,
1203 // Theme => Volume found (int)
1206 // Flag. If someting defined here,
1207 // one or more spam will be included
1212 //'category' => array(
1217 // Hosts not blocked
1222 $sum = & $progress['sum'];
1223 $is_spam = & $progress['is_spam'];
1224 $progress['method'] = & $method; // Argument
1225 $blocked = & $progress['blocked'];
1226 $hosts = & $progress['hosts'];
1227 $asap = isset($method['asap']);
1230 if (! is_array($method) || empty($method)) {
1231 $method = check_uri_spam_method();
1233 foreach(array_keys($method) as $key) {
1234 if (! isset($sum[$key])) $sum[$key] = 0;
1236 if (! isset($sum['quantity'])) $sum['quantity'] = 0;
1238 if (is_array($target)) {
1239 foreach($target as $str) {
1240 if (! is_string($str)) continue;
1242 $_progress = check_uri_spam($str, $method); // Recurse
1245 $_sum = & $_progress['sum'];
1246 foreach (array_keys($_sum) as $key) {
1247 if (! isset($sum[$key])) {
1248 $sum[$key] = & $_sum[$key];
1250 $sum[$key] += $_sum[$key];
1255 $_is_spam = & $_progress['is_spam'];
1256 foreach (array_keys($_is_spam) as $key) {
1257 $is_spam[$key] = TRUE;
1260 if ($asap && $is_spam) break;
1263 $blocked = array_merge_recursive($blocked, $_progress['blocked']);
1264 $hosts = array_merge_recursive($hosts, $_progress['hosts']);
1268 $blocked = array_unique_recursive($blocked);
1269 $hosts = array_unique_recursive($hosts);
1271 // Recount $sum['badhost']
1272 $sum['badhost'] = array_count_leaves($blocked);
1277 // Area: There's HTML anchor tag
1278 if ((! $asap || ! $is_spam) && isset($method['area_anchor'])) {
1279 $key = 'area_anchor';
1280 $_asap = isset($method['asap']) ? array('asap' => TRUE) : array();
1281 $result = area_pickup($target, array($key => TRUE) + $_asap);
1283 $sum[$key] = $result[$key];
1284 if (isset($method[$key]) && $sum[$key] > $method[$key]) {
1285 $is_spam[$key] = TRUE;
1290 // Area: There's 'BBCode' linking tag
1291 if ((! $asap || ! $is_spam) && isset($method['area_bbcode'])) {
1292 $key = 'area_bbcode';
1293 $_asap = isset($method['asap']) ? array('asap' => TRUE) : array();
1294 $result = area_pickup($target, array($key => TRUE) + $_asap);
1296 $sum[$key] = $result[$key];
1297 if (isset($method[$key]) && $sum[$key] > $method[$key]) {
1298 $is_spam[$key] = TRUE;
1304 if ($asap && $is_spam) return $progress;
1307 $pickups = uri_pickup_normalize(spam_uri_pickup($target, $method));
1310 if (empty($pickups)) return $progress;
1312 // URI: Check quantity
1313 $sum['quantity'] += count($pickups);
1315 if ((! $asap || ! $is_spam) && isset($method['quantity']) &&
1316 $sum['quantity'] > $method['quantity']) {
1317 $is_spam['quantity'] = TRUE;
1320 // URI: used inside HTML anchor tag pair
1321 if ((! $asap || ! $is_spam) && isset($method['uri_anchor'])) {
1322 $key = 'uri_anchor';
1323 foreach($pickups as $pickup) {
1324 if (isset($pickup['area'][$key])) {
1325 $sum[$key] += $pickup['area'][$key];
1326 if(isset($method[$key]) &&
1327 $sum[$key] > $method[$key]) {
1328 $is_spam[$key] = TRUE;
1329 if ($asap && $is_spam) break;
1331 if ($asap && $is_spam) break;
1336 // URI: used inside 'BBCode' pair
1337 if ((! $asap || ! $is_spam) && isset($method['uri_bbcode'])) {
1338 $key = 'uri_bbcode';
1339 foreach($pickups as $pickup) {
1340 if (isset($pickup['area'][$key])) {
1341 $sum[$key] += $pickup['area'][$key];
1342 if(isset($method[$key]) &&
1343 $sum[$key] > $method[$key]) {
1344 $is_spam[$key] = TRUE;
1345 if ($asap && $is_spam) break;
1347 if ($asap && $is_spam) break;
1352 // URI: Uniqueness (and removing non-uniques)
1353 if ((! $asap || ! $is_spam) && isset($method['non_uniquri'])) {
1356 foreach (array_keys($pickups) as $key) {
1357 $uris[$key] = uri_pickup_implode($pickups[$key]);
1359 $count = count($uris);
1360 $uris = array_unique($uris);
1361 $sum['non_uniquri'] += $count - count($uris);
1362 if ($sum['non_uniquri'] > $method['non_uniquri']) {
1363 $is_spam['non_uniquri'] = TRUE;
1365 if (! $asap || ! $is_spam) {
1366 foreach (array_diff(array_keys($pickups),
1367 array_keys($uris)) as $remove) {
1368 unset($pickups[$remove]);
1375 if ($asap && $is_spam) return $progress;
1377 // Host: Uniqueness (uniq / non-uniq)
1378 foreach ($pickups as $pickup) $hosts[] = & $pickup['host'];
1379 $hosts = array_unique($hosts);
1380 $sum['uniqhost'] += count($hosts);
1381 if ((! $asap || ! $is_spam) && isset($method['non_uniqhost'])) {
1382 $sum['non_uniqhost'] = $sum['quantity'] - $sum['uniqhost'];
1383 if ($sum['non_uniqhost'] > $method['non_uniqhost']) {
1384 $is_spam['non_uniqhost'] = TRUE;
1389 if ($asap && $is_spam) return $progress;
1391 // URI: Bad host (Separate good/bad hosts from $hosts)
1392 if ((! $asap || ! $is_spam) && isset($method['badhost'])) {
1395 $list = get_blocklist('list');
1396 $blocked = blocklist_distiller($hosts, array_keys($list), $asap);
1397 foreach($list as $key=>$type){
1398 if (! $type) unset($blocked[$key]); // Ignore goodhost etc
1402 if (! empty($blocked)) $is_spam['badhost'] = TRUE;
1408 // Count leaves (A leaf = value that is not an array, or an empty array)
1409 function array_count_leaves($array = array(), $count_empty = FALSE)
1411 if (! is_array($array) || (empty($array) && $count_empty)) return 1;
1415 foreach ($array as $part) {
1416 $count += array_count_leaves($part, $count_empty);
1421 // An array-leaves to a flat array
1422 function array_flat_leaves($array, $unique = TRUE)
1424 if (! is_array($array)) return $array;
1427 foreach(array_keys($array) as $key) {
1428 if (is_array($array[$key])) {
1430 foreach(array_flat_leaves($array[$key]) as $_value) {
1434 $tmp[] = & $array[$key];
1438 return $unique ? array_values(array_unique($tmp)) : $tmp;
1441 // An array() to an array leaf
1442 function array_leaf($array = array('A', 'B', 'C.D'), $stem = FALSE, $edge = TRUE)
1444 if (! is_array($array)) return $array;
1448 foreach($array as $arg) {
1449 if (! is_string($arg) && ! is_int($arg)) continue;
1450 $tmp[$arg] = array();
1452 $tmp = & $tmp[$arg];
1455 $parent[key($parent)] = & $edge;
1457 $parent = key($parent);
1460 return $leaf; // array('A' => array('B' => 'C.D'))
1464 // ---------------------
1467 // Summarize $progress (blocked only)
1468 function summarize_spam_progress($progress = array(), $blockedonly = FALSE)
1471 $tmp = array_keys($progress['is_spam']);
1474 $method = & $progress['method'];
1475 if (isset($progress['sum'])) {
1476 foreach ($progress['sum'] as $key => $value) {
1477 if (isset($method[$key]) && $value) {
1478 $tmp[] = $key . '(' . $value . ')';
1484 return implode(', ', $tmp);
1487 function summarize_detail_badhost($progress = array())
1489 if (! isset($progress['blocked']) || empty($progress['blocked'])) return '';
1493 foreach($progress['blocked'] as $list => $lvalue) {
1494 foreach($lvalue as $group => $gvalue) {
1495 $flat = implode(', ', array_flat_leaves($gvalue));
1496 if ($flat === $group) {
1497 $blocked[$list][] = $flat;
1499 $blocked[$list][$group] = $flat;
1505 // From: 'A-1' => array('ie.to')
1506 // To: 'A-1' => 'ie.to'
1507 foreach($blocked as $list => $lvalue) {
1508 if (is_array($lvalue) &&
1509 count($lvalue) == 1 &&
1510 is_numeric(key($lvalue))) {
1511 $blocked[$list] = current($lvalue);
1515 return var_export_shrink($blocked, TRUE, TRUE);
1518 function summarize_detail_newtral($progress = array())
1520 if (! isset($progress['hosts']) ||
1521 ! is_array($progress['hosts']) ||
1522 empty($progress['hosts'])) return '';
1524 // Generate a responsible $trie
1526 foreach($progress['hosts'] as $value) {
1527 // 'A.foo.bar.example.com'
1528 $resp = whois_responsibility($value); // 'example.com'
1530 // One or more test, or do nothing here
1531 $resp = strval($value);
1534 $rest = rtrim(substr($value, 0, - strlen($resp)), '.'); // 'A.foo.bar'
1536 $trie = array_merge_recursive($trie, array($resp => array($rest => NULL)));
1539 // Format: var_export_shrink() -like output
1541 ksort_by_domain($trie);
1542 foreach(array_keys($trie) as $key) {
1543 ksort_by_domain($trie[$key]);
1544 if (count($trie[$key]) == 1 && key($trie[$key]) == '') {
1545 // Just one 'responsibility.example.com'
1546 $result[] = ' \'' . $key . '\',';
1548 // One subdomain-or-host, or several ones
1550 foreach(array_keys($trie[$key]) as $sub) {
1554 $subs[] = $sub . '.' . $key;
1557 $result[] = ' \'' . $key . '\' => \'' . implode(', ', $subs) . '\',';
1563 implode("\n", $result) . "\n" .
1567 // ksort() by domain
1568 function ksort_by_domain(& $array)
1571 foreach(array_keys($array) as $key) {
1572 $sort[delimiter_reverse($key)] = $key;
1574 ksort($sort, SORT_STRING);
1576 foreach($sort as $key) {
1577 $result[$key] = & $array[$key];
1582 // Check responsibility-root of the FQDN
1583 // 'foo.bar.example.com' => 'example.com' (.com has the last whois for it)
1584 // 'foo.bar.example.au' => 'example.au' (.au has the last whois for it)
1585 // 'foo.bar.example.edu.au' => 'example.edu.au' (.edu.au has the last whois for it)
1586 // 'foo.bar.example.act.edu.au' => 'example.act.edu.au' (.act.edu.au has the last whois for it)
1587 function whois_responsibility($fqdn = 'foo.bar.example.com', $parent = FALSE, $implicit = TRUE)
1589 // Domains who have 2nd and/or 3rd level domains
1590 static $domain = array(
1593 // http://www.auda.org.au/
1594 // NIC : http://www.aunic.net/
1595 // Whois: http://www.ausregistry.com.au/
1597 // .au Second Level Domains
1598 // http://www.auda.org.au/domains/
1603 'edu' => array( // http://www.domainname.edu.au/
1616 'act' => TRUE, // Australian Capital Territory
1617 'nt' => TRUE, // Northern Territory
1618 'nsw' => TRUE, // New South Wales
1619 'qld' => TRUE, // Queensland
1620 'sa' => TRUE, // South Australia
1621 'tas' => TRUE, // Tasmania
1622 'vic' => TRUE, // Victoria
1623 'wa' => TRUE, // Western Australia
1632 // NIC : http://www.inet.com.bh/ (.bh policies not found)
1633 // Whois: (Not available) http://www.inet.com.bh/
1643 // NIC : http://www.cnnic.net.cn/en/index/
1644 // Whois: http://ewhois.cnnic.cn/
1646 // Provisional Administrative Rules for Registration of Domain Names in China
1647 // http://www.cnnic.net.cn/html/Dir/2003/11/27/1520.htm
1695 // NIC : http://www.inregistry.in/
1696 // Whois: http://www.inregistry.in/whois_search/
1698 // Policies http://www.inregistry.in/policies/
1709 // Reserved Names by the government (for the 2nd level)
1710 // http://www.inregistry.in/policies/reserved_names
1713 // ccTLD: South Korea
1714 // NIC : http://www.nic.or.kr/english/
1715 // Whois: http://whois.nida.or.kr/english/
1717 // .kr domain policy [appendix 1] : Qualifications for Second Level Domains
1718 // http://domain.nida.or.kr/eng/policy.jsp
1749 'gyeongbuk' => TRUE,
1750 'gyeongnam' => TRUE,
1755 // NIC : http://jprs.co.jp/en/
1756 // Whois: http://whois.jprs.jp/en/
1758 // Guide to JP Domain Name
1759 // http://jprs.co.jp/en/jpdomain.html
1774 // Examples for 3rd level domains
1775 //'kumamoto' => array(
1776 // // http://www.pref.kumamoto.jp/link/list.asp#4
1777 // 'amakusa' => TRUE,
1778 // 'hitoyoshi' => TRUE,
1780 // 'kumamoto' => TRUE,
1790 'fukushima' => TRUE,
1793 'hiroshima' => TRUE,
1800 'kagoshima' => TRUE,
1803 'kitakyushu'=> TRUE,
1828 'tokushima' => TRUE,
1834 'yamaguchi' => TRUE,
1835 'yamanashi' => TRUE,
1840 // NIC : http://www.nic.mx/
1841 // Whois: http://www.nic.mx/es/Busqueda.Who_Is
1843 // Politicas Generales de Nombres de Dominio
1844 // http://www.nic.mx/es/Politicas?CATEGORY=INDICE
1853 // NIC : http://www.cctld.ru/en/
1854 // Whois: http://www.ripn.net:8080/nic/whois/en/
1856 // List of Reserved second-level Domain Names
1857 // http://www.cctld.ru/en/doc/detail.php?id21=20&i21=2
1876 'arkhangelsk' => TRUE,
1877 'astrakhan' => TRUE,
1879 'bashkiria' => TRUE,
1886 'chelyabinsk' => TRUE,
1889 'chuvashia' => TRUE,
1901 'joshkar-ola' => TRUE,
1905 'kamchatka' => TRUE,
1910 'khabarovsk' => TRUE,
1911 'khakassia' => TRUE,
1918 'krasnoyarsk' => TRUE,
1941 'novosibirsk' => TRUE,
1952 'pyatigorsk' => TRUE,
1954 'rubtsovsk' => TRUE,
1963 'stavropol' => TRUE,
1968 'tatarstan' => TRUE,
1971 'tsaritsyn' => TRUE,
1981 'vladikavkaz' => TRUE,
1983 'vladivostok' => TRUE,
1984 'volgograd' => TRUE,
1991 'yaroslavl' => TRUE,
1992 'yekaterinburg' => TRUE,
1993 'yuzhno-sakhalinsk' => TRUE,
1997 // ccTLD: Seychelles
1998 // NIC : http://www.nic.sc/
1999 // Whois: (Not available)
2001 // http://www.nic.sc/policies.html
2010 // NIC : http://www.twnic.net.tw/
2011 // Whois: http://www.twnic.net.tw/
2013 // Guidelines for Administration of Domain Name Registration
2014 // http://www.twnic.net.tw/english/dn/dn_02.htm
2015 // II. Types of TWNIC Domain Names and Application Requirements
2016 // http://www.twnic.net.tw/english/dn/dn_02_b.htm
2027 // Reserved words for the 2nd level
2028 // http://mydn.twnic.net.tw/en/dn02/INDEX.htm
2032 // NIC : http://www.psg.com/dns/tz/
2033 // Whois: (Not available)
2035 // TZ DOMAIN NAMING STRUCTURE
2036 // http://www.psg.com/dns/tz/tz.txt
2045 // NIC : http://www.nic.net.ua/
2046 // Whois: http://whois.com.ua/
2048 // policy for alternative 2nd level domain names (a2ld)
2049 // http://www.nic.net.ua/doc/a2ld
2050 // http://whois.com.ua/
2051 'cherkassy' => TRUE,
2052 'chernigov' => TRUE,
2053 'chernovtsy' => TRUE,
2060 'dnepropetrovsk' => TRUE,
2066 'ivano-frankivsk' => TRUE,
2071 'kirovograd' => TRUE,
2089 'sebastopol' => TRUE,
2097 'zaporizhzhe' => TRUE,
2103 // ccTLD: United Kingdom
2104 // NIC : http://www.nic.uk/
2106 // Second Level Domains
2107 // http://www.nic.uk/registrants/aboutdomainnames/sld/
2117 // Delegated Second Level Domains
2118 // http://www.nic.uk/registrants/aboutdomainnames/sld/delegated/
2127 // ccTLD: United States of America
2128 // NIC : http://nic.us/
2129 // Whois: http://whois.us/
2141 // United States Postal Service: State abbreviations (for postal codes)
2142 // http://www.usps.com/ncsc/lookups/abbreviations.html
2143 'ak' => TRUE, // Alaska
2144 'al' => TRUE, // Alabama
2145 'ar' => TRUE, // Arkansas
2146 'as' => TRUE, // American samoa
2147 'az' => TRUE, // Arizona
2148 'ca' => TRUE, // California
2149 'co' => TRUE, // Colorado
2150 'ct' => TRUE, // Connecticut
2151 'dc' => TRUE, // District of Columbia
2152 'de' => TRUE, // Delaware
2153 'fl' => TRUE, // Florida
2154 'fm' => TRUE, // Federated states of Micronesia
2155 'ga' => TRUE, // Georgia
2156 'gu' => TRUE, // Guam
2157 'hi' => TRUE, // Hawaii
2158 'ia' => TRUE, // Iowa
2159 'id' => TRUE, // Idaho
2160 'il' => TRUE, // Illinois
2161 'in' => TRUE, // Indiana
2162 'ks' => TRUE, // Kansas
2163 'ky' => TRUE, // Kentucky
2164 'la' => TRUE, // Louisiana
2165 'ma' => TRUE, // Massachusetts
2166 'md' => TRUE, // Maryland
2167 'me' => TRUE, // Maine
2168 'mh' => TRUE, // Marshall Islands
2169 'mi' => TRUE, // Michigan
2170 'mn' => TRUE, // Minnesota
2171 'mo' => TRUE, // Missouri
2172 'mp' => TRUE, // Northern mariana islands
2173 'ms' => TRUE, // Mississippi
2174 'mt' => TRUE, // Montana
2175 'nc' => TRUE, // North Carolina
2176 'nd' => TRUE, // North Dakota
2177 'ne' => TRUE, // Nebraska
2178 'nh' => TRUE, // New Hampshire
2179 'nj' => TRUE, // New Jersey
2180 'nm' => TRUE, // New Mexico
2181 'nv' => TRUE, // Nevada
2182 'ny' => TRUE, // New York
2183 'oh' => TRUE, // Ohio
2184 'ok' => TRUE, // Oklahoma
2185 'or' => TRUE, // Oregon
2186 'pa' => TRUE, // Pennsylvania
2187 'pr' => TRUE, // Puerto Rico
2188 'pw' => TRUE, // Palau
2189 'ri' => TRUE, // Rhode Island
2190 'sc' => TRUE, // South Carolina
2191 'sd' => TRUE, // South Dakota
2192 'tn' => TRUE, // Tennessee
2193 'tx' => TRUE, // Texas
2194 'ut' => TRUE, // Utah
2195 'va' => TRUE, // Virginia
2196 'vi' => TRUE, // Virgin Islands
2197 'vt' => TRUE, // Vermont
2198 'wa' => TRUE, // Washington
2199 'wi' => TRUE, // Wisconsin
2200 'wv' => TRUE, // West Virginia
2201 'wy' => TRUE, // Wyoming
2204 // ccTLD: South Africa
2205 // NIC : http://www.zadna.org.za/
2207 // ac.za http://www.tenet.ac.za/cgi/cgi_domainquery.exe
2208 // co.za http://co.za/whois.shtml
2209 // gov.za http://dnsadmin.gov.za/
2210 // org.za http://www.org.za/
2212 // Second-level subdomains of .ZA
2213 // http://www.zadna.org.za/slds.html
2224 // Provincial Domains
2225 // http://www.esn.org.za/dns/
2239 if (! is_string($fqdn)) return '';
2240 if (is_ip($fqdn)) return $fqdn;
2243 $dcursor = & $domain;
2244 $array = array_reverse(explode('.', $fqdn));
2247 if (! isset($array[$i])) break;
2248 $acursor = $array[$i];
2249 if (is_array($dcursor) && isset($dcursor[$acursor])) {
2250 $result[] = & $array[$i];
2251 $dcursor = & $dcursor[$acursor];
2253 if (! $parent && isset($acursor)) {
2254 $result[] = & $array[$i]; // Whois servers must know this subdomain
2261 // Implicit responsibility: Top-Level-Domains must not be yours
2262 // 'bar.foo.something' => 'foo.something'
2263 if ($implicit && count($result) == 1 && count($array) > 1) {
2264 $result[] = & $array[1];
2267 return $result ? implode('.', array_reverse($result)) : '';
2271 // ---------------------
2275 function spam_dispose()
2277 get_blocklist(NULL);
2280 // Common bahavior for blocking
2281 // NOTE: Call this function from various blocking feature, to disgueise the reason 'why blocked'
2282 function spam_exit($mode = '', $data = array())
2291 echo('<pre>' . "\n");
2292 echo htmlspecialchars(var_export($data, TRUE));
2293 echo('</pre>' . "\n");
2297 if ($exit) exit; // Force exit
2301 // ---------------------
2304 // TODO: Record them
2305 // Simple/fast spam filter ($target: 'a string' or an array())
2306 function pkwk_spamfilter($action, $page, $target = array('title' => ''), $method = array(), $exitmode = '')
2308 $progress = check_uri_spam($target, $method);
2310 if (empty($progress['is_spam'])) {
2314 // TODO: detect encoding from $target for mbstring functions
2316 // foreach(array_keys($target) as $key) {
2317 // $tmp[strings($key, 0, FALSE, TRUE)] = strings($target[$key], 0, FALSE, TRUE); // Removing "\0" etc
2319 // $target = & $tmp;
2321 pkwk_spamnotify($action, $page, $target, $progress, $method);
2322 spam_exit($exitmode, $progress);
2326 // ---------------------
2327 // PukiWiki original
2329 // Mail to administrator(s)
2330 function pkwk_spamnotify($action, $page, $target = array('title' => ''), $progress = array(), $method = array())
2332 global $notify, $notify_subject;
2334 if (! $notify) return;
2336 $asap = isset($method['asap']);
2338 $summary['ACTION'] = 'Blocked by: ' . summarize_spam_progress($progress, TRUE);
2340 $summary['METRICS'] = summarize_spam_progress($progress);
2343 $tmp = summarize_detail_badhost($progress);
2344 if ($tmp != '') $summary['DETAIL_BADHOST'] = $tmp;
2346 $tmp = summarize_detail_newtral($progress);
2347 if (! $asap && $tmp != '') $summary['DETAIL_NEUTRAL_HOST'] = $tmp;
2349 $summary['COMMENT'] = $action;
2350 $summary['PAGE'] = '[blocked] ' . (is_pagename($page) ? $page : '');
2351 $summary['URI'] = get_script_uri() . '?' . rawurlencode($page);
2352 $summary['USER_AGENT'] = TRUE;
2353 $summary['REMOTE_ADDR'] = TRUE;
2354 pkwk_mail_notify($notify_subject, var_export($target, TRUE), $summary, TRUE);