2 // $Id: spam.php,v 1.156 2007/05/05 10:54:29 henoheno Exp $
3 // Copyright (C) 2006-2007 PukiWiki Developers Team
4 // License: GPL v2 or (at your option) any later version
6 // Functions for Concept-work of spam-uri metrics
8 // (PHP 4 >= 4.3.0): preg_match_all(PREG_OFFSET_CAPTURE): $method['uri_XXX'] related feature
10 if (! defined('SPAM_INI_FILE')) define('SPAM_INI_FILE', 'spam.ini.php');
12 // ---------------------
15 // (PHP 4 >= 4.2.0): var_export(): mail-reporting and dump related
16 if (! function_exists('var_export')) {
17 function var_export() {
18 return 'var_export() is not found on this server' . "\n";
22 // (PHP 4 >= 4.2.0): preg_grep() enables invert option
23 function preg_grep_invert($pattern = '//', $input = array())
26 if (! isset($invert)) $invert = defined('PREG_GREP_INVERT');
29 return preg_grep($pattern, $input, PREG_GREP_INVERT);
31 $result = preg_grep($pattern, $input);
33 return array_diff($input, preg_grep($pattern, $input));
42 // Very roughly, shrink the lines of var_export()
43 // NOTE: If the same data exists, it must be corrupted.
44 function var_export_shrink($expression, $return = FALSE, $ignore_numeric_keys = FALSE)
46 $result =preg_replace(
47 // Remove a newline and spaces
48 '# => \n *array \(#', ' => array (',
49 var_export($expression, TRUE)
52 if ($ignore_numeric_keys) {
53 $result =preg_replace(
54 // Remove numeric keys
55 '#^( *)[0-9]+ => #m', '$1',
68 // Remove redundant values from array()
69 function array_unique_recursive($array = array())
71 if (! is_array($array)) return $array;
74 foreach($array as $key => $value){
75 if (is_array($value)) {
76 $array[$key] = array_unique_recursive($value);
78 if (isset($tmp[$value])) {
89 // Renumber all numeric keys from 0
90 function array_renumber_numeric_keys(& $array)
92 if (! is_array($array)) return $array;
96 foreach($array as $key => $value){
97 if (is_array($value)) array_renumber_numeric_keys($array[$key]); // Recurse
98 if (is_numeric($key)) $tmp[$key] = ++$count;
100 array_rename_keys($array, $tmp);
105 // Roughly strings(1) using PCRE
106 // This function is useful to:
107 // * Reduce the size of data, from removing unprintable binary data
108 // * Detect _bare_strings_ from binary data
110 // http://www.freebsd.org/cgi/man.cgi?query=strings (Man-page of GNU strings)
111 // http://www.pcre.org/pcre.txt
112 function strings($binary = '', $min_len = 4, $ignore_space = FALSE)
115 $binary = preg_replace(
117 '/(?:[^[:graph:] \t\n]|[\r])+/s',
130 $binary = preg_replace('/(?:[^[:graph:][:space:]]|[\r])+/s', "\n", $binary);
134 $min_len = min(1024, intval($min_len));
137 preg_grep('/^.{' . $min_len . ',}/S',
138 explode("\n", $binary)
146 // Reverse $string with specified delimiter
147 function delimiter_reverse($string = 'foo.bar.example.com', $from_delim = '.', $to_delim = '.')
149 if (! is_string($string) || ! is_string($from_delim) || ! is_string($to_delim))
152 // com.example.bar.foo
153 return implode($to_delim, array_reverse(explode($from_delim, $string)));
157 // ---------------------
160 // Return an array of URIs in the $string
161 // [OK] http://nasty.example.org#nasty_string
162 // [OK] http://nasty.example.org:80/foo/xxx#nasty_string/bar
163 // [OK] ftp://nasty.example.org:80/dfsdfs
164 // [OK] ftp://cnn.example.com&story=breaking_news@10.0.0.1/top_story.htm (from RFC3986)
165 function uri_pickup($string = '')
167 if (! is_string($string)) return array();
169 // Not available for: IDN(ignored)
172 // scheme://userinfo@host:port/path/or/pathinfo/maybefile.and?query=string#fragment
173 // Refer RFC3986 (Regex below is not strict)
174 '#(\b[a-z][a-z0-9.+-]{1,8}):/+' . // 1: Scheme
176 '([^\s<>"\'\[\]/\#?@]*)' . // 2: Userinfo (Username)
180 '\[[0-9a-f:.]+\]' . '|' . // IPv6([colon-hex and dot]): RFC2732
181 '(?:[0-9]{1,3}\.){3}[0-9]{1,3}' . '|' . // IPv4(dot-decimal): 001.22.3.44
182 '[a-z0-9.-]+' . // hostname(FQDN) : foo.example.org
184 '(?::([0-9]*))?' . // 4: Port
185 '((?:/+[^\s<>"\'\[\]/\#]+)*/+)?' . // 5: Directory path or path-info
186 '([^\s<>"\'\[\]\#?]+)?' . // 6: File?
187 '(?:\?([^\s<>"\'\[\]\#]+))?' . // 7: Query string
188 '(?:\#([a-z0-9._~%!$&\'()*+,;=:@-]*))?' . // 8: Fragment
190 $string, $array, PREG_SET_ORDER | PREG_OFFSET_CAPTURE
194 static $parts = array(
195 1 => 'scheme', 2 => 'userinfo', 3 => 'host', 4 => 'port',
196 5 => 'path', 6 => 'file', 7 => 'query', 8 => 'fragment'
198 $default = array('');
199 foreach(array_keys($array) as $uri) {
200 $_uri = & $array[$uri];
201 array_rename_keys($_uri, $parts, TRUE, $default);
202 $offset = $_uri['scheme'][1]; // Scheme's offset = URI's offset
203 foreach(array_keys($_uri) as $part) {
204 $_uri[$part] = & $_uri[$part][0]; // Remove offsets
208 foreach(array_keys($array) as $uri) {
209 $_uri = & $array[$uri];
210 if ($_uri['scheme'] === '') {
211 unset($array[$uri]); // Considererd harmless
214 unset($_uri[0]); // Matched string itself
215 $_uri['area']['offset'] = $offset; // Area offset for area_measure()
221 // Normalize an array of URI arrays
222 // NOTE: Give me the uri_pickup() results
223 function uri_pickup_normalize(& $pickups, $destructive = TRUE)
225 if (! is_array($pickups)) return $pickups;
228 foreach (array_keys($pickups) as $key) {
229 $_key = & $pickups[$key];
230 $_key['scheme'] = isset($_key['scheme']) ? scheme_normalize($_key['scheme']) : '';
231 $_key['host'] = isset($_key['host']) ? host_normalize($_key['host']) : '';
232 $_key['port'] = isset($_key['port']) ? port_normalize($_key['port'], $_key['scheme'], FALSE) : '';
233 $_key['path'] = isset($_key['path']) ? strtolower(path_normalize($_key['path'])) : '';
234 $_key['file'] = isset($_key['file']) ? file_normalize($_key['file']) : '';
235 $_key['query'] = isset($_key['query']) ? query_normalize($_key['query']) : '';
236 $_key['fragment'] = isset($_key['fragment']) ? strtolower($_key['fragment']) : '';
239 foreach (array_keys($pickups) as $key) {
240 $_key = & $pickups[$key];
241 $_key['scheme'] = isset($_key['scheme']) ? scheme_normalize($_key['scheme']) : '';
242 $_key['host'] = isset($_key['host']) ? strtolower($_key['host']) : '';
243 $_key['port'] = isset($_key['port']) ? port_normalize($_key['port'], $_key['scheme'], FALSE) : '';
244 $_key['path'] = isset($_key['path']) ? path_normalize($_key['path']) : '';
251 // An URI array => An URI (See uri_pickup())
253 // $pickups = uri_pickup('a string include some URIs');
255 // foreach (array_keys($pickups) as $key) {
256 // $uris[$key] = uri_pickup_implode($pickups[$key]);
258 function uri_pickup_implode($uri = array())
260 if (empty($uri) || ! is_array($uri)) return NULL;
263 if (isset($uri['scheme']) && $uri['scheme'] !== '') {
264 $tmp[] = & $uri['scheme'];
267 if (isset($uri['userinfo']) && $uri['userinfo'] !== '') {
268 $tmp[] = & $uri['userinfo'];
271 if (isset($uri['host']) && $uri['host'] !== '') {
272 $tmp[] = & $uri['host'];
274 if (isset($uri['port']) && $uri['port'] !== '') {
276 $tmp[] = & $uri['port'];
278 if (isset($uri['path']) && $uri['path'] !== '') {
279 $tmp[] = & $uri['path'];
281 if (isset($uri['file']) && $uri['file'] !== '') {
282 $tmp[] = & $uri['file'];
284 if (isset($uri['query']) && $uri['query'] !== '') {
286 $tmp[] = & $uri['query'];
288 if (isset($uri['fragment']) && $uri['fragment'] !== '') {
290 $tmp[] = & $uri['fragment'];
293 return implode('', $tmp);
296 // $array['something'] => $array['wanted']
297 function array_rename_keys(& $array, $keys = array('from' => 'to'), $force = FALSE, $default = '')
299 if (! is_array($array) || ! is_array($keys)) return FALSE;
301 // Nondestructive test
303 foreach(array_keys($keys) as $from)
304 if (! isset($array[$from]))
307 foreach($keys as $from => $to) {
308 if ($from === $to) continue;
309 if (! $force || isset($array[$from])) {
310 $array[$to] = & $array[$from];
311 unset($array[$from]);
313 $array[$to] = $default;
320 // ---------------------
323 // Pickup all of markup areas
324 function area_pickup($string = '', $method = array())
327 if (empty($method)) return $area;
329 // Anchor tag pair by preg_match and preg_match_all()
331 // [OK] <a href= >Good site!</a>
332 // [OK] <a href= "#" >test</a>
333 // [OK] <a href="http://nasty.example.com">visit http://nasty.example.com/</a>
334 // [OK] <a href=\'http://nasty.example.com/\' >discount foobar</a>
335 // [NG] <a href="http://ng.example.com">visit http://ng.example.com _not_ended_
336 $regex = '#<a\b[^>]*\bhref\b[^>]*>.*?</a\b[^>]*(>)#is';
337 if (isset($method['area_anchor'])) {
339 $count = isset($method['asap']) ?
340 preg_match($regex, $string) :
341 preg_match_all($regex, $string, $areas);
342 if (! empty($count)) $area['area_anchor'] = $count;
344 if (isset($method['uri_anchor'])) {
346 preg_match_all($regex, $string, $areas, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
347 foreach(array_keys($areas) as $_area) {
348 $areas[$_area] = array(
349 $areas[$_area][0][1], // Area start (<a href>)
350 $areas[$_area][1][1], // Area end (</a>)
353 if (! empty($areas)) $area['uri_anchor'] = $areas;
356 // phpBB's "BBCode" pair by preg_match and preg_match_all()
358 // [OK] [url]http://nasty.example.com/[/url]
359 // [OK] [link]http://nasty.example.com/[/link]
360 // [OK] [url=http://nasty.example.com]visit http://nasty.example.com/[/url]
361 // [OK] [link http://nasty.example.com/]buy something[/link]
362 $regex = '#\[(url|link)\b[^\]]*\].*?\[/\1\b[^\]]*(\])#is';
363 if (isset($method['area_bbcode'])) {
365 $count = isset($method['asap']) ?
366 preg_match($regex, $string) :
367 preg_match_all($regex, $string, $areas, PREG_SET_ORDER);
368 if (! empty($count)) $area['area_bbcode'] = $count;
370 if (isset($method['uri_bbcode'])) {
372 preg_match_all($regex, $string, $areas, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
373 foreach(array_keys($areas) as $_area) {
374 $areas[$_area] = array(
375 $areas[$_area][0][1], // Area start ([url])
376 $areas[$_area][2][1], // Area end ([/url])
379 if (! empty($areas)) $area['uri_bbcode'] = $areas;
382 // Various Wiki syntax
383 // [text_or_uri>text_or_uri]
384 // [text_or_uri:text_or_uri]
385 // [text_or_uri|text_or_uri]
386 // [text_or_uri->text_or_uri]
387 // [text_or_uri text_or_uri] // MediaWiki
388 // MediaWiki: [http://nasty.example.com/ visit http://nasty.example.com/]
393 // If in doubt, it's a little doubtful
394 // if (Area => inside <= Area) $brief += -1
395 function area_measure($areas, & $array, $belief = -1, $a_key = 'area', $o_key = 'offset')
397 if (! is_array($areas) || ! is_array($array)) return;
399 $areas_keys = array_keys($areas);
400 foreach(array_keys($array) as $u_index) {
401 $offset = isset($array[$u_index][$o_key]) ?
402 intval($array[$u_index][$o_key]) : 0;
403 foreach($areas_keys as $a_index) {
404 if (isset($array[$u_index][$a_key])) {
405 $offset_s = intval($areas[$a_index][0]);
406 $offset_e = intval($areas[$a_index][1]);
407 // [Area => inside <= Area]
408 if ($offset_s < $offset && $offset < $offset_e) {
409 $array[$u_index][$a_key] += $belief;
416 // ---------------------
419 // Domain exposure callback (See spam_uri_pickup_preprocess())
420 // http://victim.example.org/?foo+site:nasty.example.com+bar
421 // => http://nasty.example.com/?refer=victim.example.org
422 // NOTE: 'refer=' is not so good for (at this time).
423 // Consider about using IP address of the victim, try to avoid that.
424 function _preg_replace_callback_domain_exposure($matches = array())
428 // Preserve the victim URI as a complicity or ...
429 if (isset($matches[5])) {
431 $matches[1] . '://' . // scheme
432 $matches[2] . '/' . // victim.example.org
433 $matches[3]; // The rest of all (before victim)
437 if (isset($matches[4])) {
439 $matches[1] . '://' . // scheme
440 $matches[4] . // nasty.example.com
441 '/?refer=' . strtolower($matches[2]) . // victim.example.org
448 // Preprocess: rawurldecode() and adding space(s) and something
449 // to detect/count some URIs _if possible_
450 // NOTE: It's maybe danger to var_dump(result). [e.g. 'javascript:']
451 // [OK] http://victim.example.org/?site:nasty.example.org
452 // [OK] http://victim.example.org/nasty.example.org
453 // [OK] http://victim.example.org/go?http%3A%2F%2Fnasty.example.org
454 // [OK] http://victim.example.org/http://nasty.example.org
455 function spam_uri_pickup_preprocess($string = '')
457 if (! is_string($string)) return '';
459 $string = rawurldecode($string);
461 // Domain exposure (simple)
462 // http://victim.example.org/nasty.example.org/path#frag
463 // => http://nasty.example.org/?refer=victim.example.org and original
464 $string = preg_replace(
467 'ime\.nu' . '|' . // 2ch.net
468 'ime\.st' . '|' . // 2ch.net
469 'link\.toolbot\.com' . '|' .
472 '/([a-z0-9.%_-]+\.[a-z0-9.%_-]+)#i', // nasty.example.org
473 'http://$2/?refer=$1 $0', // Preserve $0 or remove?
477 // Domain exposure (See _preg_replace_callback_domain_exposure())
478 $string = preg_replace_callback(
482 // Something Google: http://www.google.com/supported_domains
483 '(?:[a-z0-9.]+\.)?google\.[a-z]{2,3}(?:\.[a-z]{2})?' .
486 '(?:[a-z0-9.]+\.)?altavista.com' .
490 '([a-z0-9?=&.%_/\'\\\+-]+)' . // path/?query=foo+bar+
491 '\bsite:([a-z0-9.%_-]+\.[a-z0-9.%_-]+)' . // site:nasty.example.com
492 //'()' . // Preserve or remove?
495 '_preg_replace_callback_domain_exposure',
499 // URI exposure (uriuri => uri uri)
500 $string = preg_replace(
502 '#(?<! )(?:https?|ftp):/#i',
503 // '#[a-z][a-z0-9.+-]{1,8}://#i',
504 // '#[a-z][a-z0-9.+-]{1,8}://#i'
513 // Main function of spam-uri pickup,
514 // A wrapper function of uri_pickup()
515 function spam_uri_pickup($string = '', $method = array())
517 if (! is_array($method) || empty($method)) {
518 $method = check_uri_spam_method();
521 $string = spam_uri_pickup_preprocess($string);
523 $array = uri_pickup($string);
525 // Area elevation of URIs, for '(especially external)link' intension
526 if (! empty($array)) {
528 if (isset($method['uri_anchor'])) $_method['uri_anchor'] = & $method['uri_anchor'];
529 if (isset($method['uri_bbcode'])) $_method['uri_bbcode'] = & $method['uri_bbcode'];
530 $areas = area_pickup($string, $_method, TRUE);
531 if (! empty($areas)) {
532 $area_shadow = array();
533 foreach (array_keys($array) as $key) {
534 $area_shadow[$key] = & $array[$key]['area'];
535 foreach (array_keys($_method) as $_key) {
536 $area_shadow[$key][$_key] = 0;
539 foreach (array_keys($_method) as $_key) {
540 if (isset($areas[$_key])) {
541 area_measure($areas[$_key], $area_shadow, 1, $_key);
547 // Remove 'offset's for area_measure()
548 foreach(array_keys($array) as $key)
549 unset($array[$key]['area']['offset']);
555 // ---------------------
558 // Scheme normalization: Renaming the schemes
559 // snntp://example.org => nntps://example.org
560 // NOTE: Keep the static lists simple. See also port_normalize().
561 function scheme_normalize($scheme = '', $abbrevs_harmfull = TRUE)
563 // Abbreviations they have no intention of link
564 static $abbrevs = array(
569 // Aliases => normalized ones
570 static $aliases = array(
580 if (! is_string($scheme)) return '';
582 $scheme = strtolower($scheme);
583 if (isset($abbrevs[$scheme])) {
584 $scheme = $abbrevs_harmfull ? $abbrevs[$scheme] : '';
586 if (isset($aliases[$scheme])) {
587 $scheme = $aliases[$scheme];
593 // Hostname normlization (Destructive)
594 // www.foo => www.foo ('foo' seems TLD)
595 // www.foo.bar => foo.bar
596 // www.10.20 => www.10.20 (Invalid hostname)
598 // 'www' is mostly used as traditional hostname of WWW server.
599 // 'www.foo.bar' may be identical with 'foo.bar'.
600 function host_normalize($host = '')
602 if (! is_string($host)) return '';
604 $host = strtolower($host);
606 if (preg_match('/^www\.(.+\.[a-z]+)$/', $host, $matches)) {
613 // Port normalization: Suppress the (redundant) default port
614 // HTTP://example.org:80/ => http://example.org/
615 // HTTP://example.org:8080/ => http://example.org:8080/
616 // HTTPS://example.org:443/ => https://example.org/
617 function port_normalize($port, $scheme, $scheme_normalize = FALSE)
619 // Schemes that users _maybe_ want to add protocol-handlers
620 // to their web browsers. (and attackers _maybe_ want to use ...)
621 // Reference: http://www.iana.org/assignments/port-numbers
622 static $array = array(
623 // scheme => default port
649 // intval() converts '0-1' to '0', so preg_match() rejects these invalid ones
650 if (! is_numeric($port) || $port < 0 || preg_match('/[^0-9]/i', $port))
653 $port = intval($port);
654 if ($scheme_normalize) $scheme = scheme_normalize($scheme);
655 if (isset($array[$scheme]) && $port == $array[$scheme])
656 $port = ''; // Ignore the defaults
661 // Path normalization
662 // http://example.org => http://example.org/
663 // http://example.org#hoge => http://example.org/#hoge
664 // http://example.org/path/a/b/./c////./d => http://example.org/path/a/b/c/d
665 // http://example.org/path/../../a/../back => http://example.org/back
666 function path_normalize($path = '', $divider = '/', $add_root = TRUE)
668 if (! is_string($divider)) return is_string($path) ? $path : '';
671 $first_div = & $divider;
675 if (! is_string($path) || $path == '') return $first_div;
677 if (strpos($path, $divider, strlen($path) - strlen($divider)) === FALSE) {
680 $last_div = & $divider;
683 $array = explode($divider, $path);
685 // Remove paddings ('//' and '/./')
686 foreach(array_keys($array) as $key) {
687 if ($array[$key] == '' || $array[$key] == '.') {
692 // Remove back-tracks ('/../')
694 foreach($array as $value) {
695 if ($value == '..') {
698 array_push($tmp, $value);
706 return $first_div . implode($divider, $array) . $last_div;
710 // DirectoryIndex normalize (Destructive and rough)
711 // TODO: sample.en.ja.html.gz => sample.html
712 function file_normalize($file = 'index.html.en')
714 static $simple_defaults = array(
715 'default.htm' => TRUE,
716 'default.html' => TRUE,
717 'default.asp' => TRUE,
718 'default.aspx' => TRUE,
719 'index' => TRUE, // Some system can omit the suffix
722 static $content_suffix = array(
723 // index.xxx, sample.xxx
738 static $language_suffix = array(
739 // Reference: Apache 2.0.59 'AddLanguage' default
768 // Reference: Apache 2.0.59 default 'index.html' variants
774 static $charset_suffix = array(
775 // Reference: Apache 2.0.59 'AddCharset' default
776 'iso8859-1' => TRUE, // ISO-8859-1
777 'latin1' => TRUE, // ISO-8859-1
778 'iso8859-2' => TRUE, // ISO-8859-2
779 'latin2' => TRUE, // ISO-8859-2
780 'cen' => TRUE, // ISO-8859-2
781 'iso8859-3' => TRUE, // ISO-8859-3
782 'latin3' => TRUE, // ISO-8859-3
783 'iso8859-4' => TRUE, // ISO-8859-4
784 'latin4' => TRUE, // ISO-8859-4
785 'iso8859-5' => TRUE, // ISO-8859-5
786 'latin5' => TRUE, // ISO-8859-5
787 'cyr' => TRUE, // ISO-8859-5
788 'iso-ru' => TRUE, // ISO-8859-5
789 'iso8859-6' => TRUE, // ISO-8859-6
790 'latin6' => TRUE, // ISO-8859-6
791 'arb' => TRUE, // ISO-8859-6
792 'iso8859-7' => TRUE, // ISO-8859-7
793 'latin7' => TRUE, // ISO-8859-7
794 'grk' => TRUE, // ISO-8859-7
795 'iso8859-8' => TRUE, // ISO-8859-8
796 'latin8' => TRUE, // ISO-8859-8
797 'heb' => TRUE, // ISO-8859-8
798 'iso8859-9' => TRUE, // ISO-8859-9
799 'latin9' => TRUE, // ISO-8859-9
800 'trk' => TRUE, // ISO-8859-9
801 'iso2022-jp'=> TRUE, // ISO-2022-JP
802 'jis' => TRUE, // ISO-2022-JP
803 'iso2022-kr'=> TRUE, // ISO-2022-KR
804 'kis' => TRUE, // ISO-2022-KR
805 'iso2022-cn'=> TRUE, // ISO-2022-CN
806 'cis' => TRUE, // ISO-2022-CN
808 'cp-1251' => TRUE, // ru, WINDOWS-1251
809 'win-1251' => TRUE, // ru, WINDOWS-1251
810 'cp866' => TRUE, // ru
811 'koi8-r' => TRUE, // ru, KOI8-r
812 'koi8-ru' => TRUE, // ru, KOI8-r
813 'koi8-uk' => TRUE, // ru, KOI8-ru
814 'ua' => TRUE, // ru, KOI8-ru
815 'ucs2' => TRUE, // ru, ISO-10646-UCS-2
816 'ucs4' => TRUE, // ru, ISO-10646-UCS-4
819 // Reference: Apache 2.0.59 default 'index.html' variants
824 // May uncompress by web browsers on the fly
825 // Must be at the last of the filename
826 // Reference: Apache 2.0.59 'AddEncoding'
827 static $encoding_suffix = array(
832 if (! is_string($file)) return '';
833 $_file = strtolower($file);
834 if (isset($simple_defaults[$_file])) return '';
837 // Roughly removing language/character-set/encoding suffixes
839 // * Apache 2 document about 'Content-negotiaton', 'mod_mime' and 'mod_negotiation'
840 // http://httpd.apache.org/docs/2.0/content-negotiation.html
841 // http://httpd.apache.org/docs/2.0/mod/mod_mime.html
842 // http://httpd.apache.org/docs/2.0/mod/mod_negotiation.html
843 // * http://www.iana.org/assignments/character-sets
844 // * RFC3066: Tags for the Identification of Languages
845 // http://www.ietf.org/rfc/rfc3066.txt
846 // * ISO 639: codes of 'language names'
847 $suffixes = explode('.', $_file);
848 $body = array_shift($suffixes);
850 // Remove the last .gz/.z
851 $last_key = end(array_keys($suffixes));
852 if (isset($encoding_suffix[$suffixes[$last_key]])) {
853 unset($suffixes[$last_key]);
856 // Cut language and charset suffixes
857 foreach($suffixes as $key => $value){
858 if (isset($language_suffix[$value]) || isset($charset_suffix[$value])) {
859 unset($suffixes[$key]);
862 if (empty($suffixes)) return $body;
865 $count = count($suffixes);
867 $current = current($suffixes);
868 if ($body == 'index' && $count == 1 && isset($content_suffix[$current])) return '';
873 // Sort query-strings if possible (Destructive and rough)
874 // [OK] &&&&f=d&b&d&c&a=0dd => a=0dd&b&c&d&f=d
875 // [OK] nothing==&eg=dummy&eg=padding&eg=foobar => eg=foobar
876 function query_normalize($string = '', $equal = TRUE, $equal_cutempty = TRUE, $stortolower = TRUE)
878 if (! is_string($string)) return '';
879 if ($stortolower) $string = strtolower($string);
881 $array = explode('&', $string);
883 // Remove '&' paddings
884 foreach(array_keys($array) as $key) {
885 if ($array[$key] == '') {
890 // Consider '='-sepalated input and paddings
892 $equals = $not_equals = array();
893 foreach ($array as $part) {
894 if (strpos($part, '=') === FALSE) {
895 $not_equals[] = $part;
897 list($key, $value) = explode('=', $part, 2);
898 $value = ltrim($value, '=');
899 if (! $equal_cutempty || $value != '') {
900 $equals[$key] = $value;
905 $array = & $not_equals;
906 foreach ($equals as $key => $value) {
907 $array[] = $key . '=' . $value;
913 return implode('&', $array);
916 // ---------------------
917 // Part One : Checker
919 // Rough implementation of globbing
921 // USAGE: $regex = '/^' . generate_glob_regex('*.txt', '/') . '$/i';
923 function generate_glob_regex($string = '', $divider = '/')
925 static $from = array(
928 // 22 => '[', // Maybe cause regex compilation error (e.g. '[]')
944 if (! is_string($string)) return '';
946 $string = str_replace($from, $mid, $string); // Hide
947 $string = preg_quote($string, $divider);
948 $string = str_replace($mid, $to, $string); // Unhide
953 // Rough hostname checker
955 // TODO: Strict digit, 0x, CIDR, IPv6
956 function is_ip($string = '')
958 if (preg_match('/^' .
959 '(?:[0-9]{1,3}\.){3}[0-9]{1,3}' . '|' .
960 '(?:[0-9]{1,3}\.){1,3}' . '$/',
962 return 4; // Seems IPv4(dot-decimal)
964 return 0; // Seems not IP
968 // Generate host (FQDN, IPv4, ...) regex
969 // 'localhost' : Matches with 'localhost' only
970 // 'example.org' : Matches with 'example.org' only (See host_normalize() about 'www')
971 // '.example.org' : Matches with ALL FQDN ended with '.example.org'
972 // '*.example.org' : Almost the same of '.example.org' except 'www.example.org'
973 // '10.20.30.40' : Matches with IPv4 address '10.20.30.40' only
974 // [TODO] '192.' : Matches with all IPv4 hosts started with '192.'
975 // TODO: IPv4, CIDR?, IPv6
976 function generate_host_regex($string = '', $divider = '/')
978 if (! is_string($string)) return '';
980 if (mb_strpos($string, '.') === FALSE)
981 return generate_glob_regex($string, $divider);
984 if (is_ip($string)) {
986 return generate_glob_regex($string, $divider);
989 $part = explode('.', $string, 2);
990 if ($part[0] == '') {
991 $part[0] = '(?:.*\.)?'; // And all related FQDN
992 } else if ($part[0] == '*') {
993 $part[0] = '.*\.'; // All subdomains/hosts only
995 return generate_glob_regex($string, $divider);
997 $part[1] = generate_glob_regex($part[1], $divider);
998 return implode('', $part);
1002 function get_blocklist($list = '')
1006 if (! isset($regexs)) {
1008 if (file_exists(SPAM_INI_FILE)) {
1009 $blocklist = array();
1010 include(SPAM_INI_FILE);
1011 // $blocklist['badhost'] = array(
1012 // '*.blogspot.com', // Blog services's subdomains (only)
1013 // 'IANA-examples' => '#^(?:.*\.)?example\.(?:com|net|org)$#',
1015 if (isset($blocklist['list'])) {
1016 $regexs['list'] = & $blocklist['list'];
1019 $blocklist['list'] = array(
1020 'goodhost' => FALSE,
1024 foreach(array_keys($blocklist['list']) as $_list) {
1025 if (! isset($blocklist[$_list])) continue;
1026 foreach ($blocklist[$_list] as $key => $value) {
1027 if (is_array($value)) {
1028 $regexs[$_list][$key] = array();
1029 foreach($value as $_key => $_value) {
1030 get_blocklist_add($regexs[$_list][$key], $_key, $_value);
1033 get_blocklist_add($regexs[$_list], $key, $value);
1036 unset($blocklist[$_list]);
1042 return $regexs; // ALL
1043 } else if (isset($regexs[$list])) {
1044 return $regexs[$list];
1050 // Subroutine of get_blocklist()
1051 function get_blocklist_add(& $array, $key = 0, $value = '*.example.org')
1053 if (is_string($key)) {
1054 $array[$key] = & $value; // Treat $value as a regex
1056 $array[$value] = '/^' . generate_host_regex($value, '/') . '$/i';
1060 // Blocklist metrics: Separate $host, to $blocked and not blocked
1061 function blocklist_distiller(& $hosts, $keys = array('goodhost', 'badhost'), $asap = FALSE)
1063 if (! is_array($hosts)) $hosts = array($hosts);
1064 if (! is_array($keys)) $keys = array($keys);
1066 $list = get_blocklist('list');
1069 foreach($keys as $key){
1070 foreach (get_blocklist($key) as $label => $regex) {
1071 if (is_array($regex)) {
1072 foreach($regex as $_label => $_regex) {
1073 $group = preg_grep($_regex, $hosts);
1075 $hosts = array_diff($hosts, $group);
1076 $blocked[$key][$label][$_label] = $group;
1077 if ($asap && $list[$key]) break;
1081 $group = preg_grep($regex, $hosts);
1083 $hosts = array_diff($hosts, $group);
1084 $blocked[$key][$label] = $group;
1085 if ($asap && $list[$key]) break;
1094 // Simple example for badhost (not used now)
1095 function is_badhost($hosts = array(), $asap = TRUE, $bool = TRUE)
1097 $list = get_blocklist('list');
1098 $blocked = blocklist_distiller($hosts, array_keys($list), $asap);
1099 foreach($list as $key=>$type){
1100 if (! $type) unset($blocked[$key]); // Ignore goodhost etc
1103 return $bool ? ! empty($blocked) : $blocked;
1107 // Default (enabled) methods and thresholds (for content insertion)
1108 function check_uri_spam_method($times = 1, $t_area = 0, $rule = TRUE)
1110 $times = intval($times);
1111 $t_area = intval($t_area);
1115 'quantity' => 8 * $times, // Allow N URIs
1116 'non_uniqhost' => 3 * $times, // Allow N duped (and normalized) Hosts
1117 //'non_uniquri'=> 3 * $times, // Allow N duped (and normalized) URIs
1120 'area_anchor' => $t_area, // Using <a href> HTML tag
1121 'area_bbcode' => $t_area, // Using [url] or [link] BBCode
1122 //'uri_anchor' => $t_area, // URI inside <a href> HTML tag
1123 //'uri_bbcode' => $t_area, // URI inside [url] or [link] BBCode
1128 //'asap' => TRUE, // Quit or return As Soon As Possible
1129 'uniqhost' => TRUE, // Show uniq host (at block notification mail)
1130 'badhost' => TRUE, // Check badhost
1136 // Remove non-$positive values
1137 foreach (array_keys($positive) as $key) {
1138 if ($positive[$key] < 0) unset($positive[$key]);
1141 return $positive + $bool;
1144 // Simple/fast spam check
1145 function check_uri_spam($target = '', $method = array())
1150 // Theme to do => Dummy, optional value, or optional array()
1152 //'uniqhost' => TRUE,
1153 //'non_uniqhost'=> 3,
1154 //'non_uniquri' => 3,
1155 //'badhost' => TRUE,
1156 //'area_anchor' => 0,
1157 //'area_bbcode' => 0,
1158 //'uri_anchor' => 0,
1159 //'uri_bbcode' => 0,
1162 // Theme => Volume found (int)
1165 // Flag. If someting defined here,
1166 // one or more spam will be included
1171 //'category' => array(
1176 // Hosts not blocked
1181 $sum = & $progress['sum'];
1182 $is_spam = & $progress['is_spam'];
1183 $progress['method'] = & $method; // Argument
1184 $blocked = & $progress['blocked'];
1185 $hosts = & $progress['hosts'];
1186 $asap = isset($method['asap']);
1189 if (! is_array($method) || empty($method)) {
1190 $method = check_uri_spam_method();
1192 foreach(array_keys($method) as $key) {
1193 if (! isset($sum[$key])) $sum[$key] = 0;
1196 if (is_array($target)) {
1197 foreach($target as $str) {
1198 if (! is_string($str)) continue;
1200 $_progress = check_uri_spam($str, $method); // Recurse
1203 $_sum = & $_progress['sum'];
1204 foreach (array_keys($_sum) as $key) {
1205 if (! isset($sum[$key])) {
1206 $sum[$key] = & $_sum[$key];
1208 $sum[$key] += $_sum[$key];
1213 $_is_spam = & $_progress['is_spam'];
1214 foreach (array_keys($_is_spam) as $key) {
1215 $is_spam[$key] = TRUE;
1218 if ($asap && $is_spam) break;
1221 $blocked = array_merge_leaves($blocked, $_progress['blocked'], FALSE, FALSE);
1222 $hosts = array_merge_leaves($hosts, $_progress['hosts'], FALSE, FALSE);
1226 $blocked = array_unique_recursive($blocked);
1227 $hosts = array_unique_recursive($hosts);
1229 // Renumber numeric keys
1230 array_renumber_numeric_keys($blocked);
1231 array_renumber_numeric_keys($hosts);
1233 // Recount $sum['badhost']
1234 $sum['badhost'] = array_count_leaves($blocked);
1239 // Area: There's HTML anchor tag
1240 if ((! $asap || ! $is_spam) && isset($method['area_anchor'])) {
1241 $key = 'area_anchor';
1242 $_asap = isset($method['asap']) ? array('asap' => TRUE) : array();
1243 $result = area_pickup($target, array($key => TRUE) + $_asap);
1245 $sum[$key] = $result[$key];
1246 if (isset($method[$key]) && $sum[$key] > $method[$key]) {
1247 $is_spam[$key] = TRUE;
1252 // Area: There's 'BBCode' linking tag
1253 if ((! $asap || ! $is_spam) && isset($method['area_bbcode'])) {
1254 $key = 'area_bbcode';
1255 $_asap = isset($method['asap']) ? array('asap' => TRUE) : array();
1256 $result = area_pickup($target, array($key => TRUE) + $_asap);
1258 $sum[$key] = $result[$key];
1259 if (isset($method[$key]) && $sum[$key] > $method[$key]) {
1260 $is_spam[$key] = TRUE;
1266 if ($asap && $is_spam) return $progress;
1269 $pickups = uri_pickup_normalize(spam_uri_pickup($target, $method));
1272 if (empty($pickups)) return $progress;
1274 // URI: Check quantity
1275 $sum['quantity'] += count($pickups);
1277 if ((! $asap || ! $is_spam) && isset($method['quantity']) &&
1278 $sum['quantity'] > $method['quantity']) {
1279 $is_spam['quantity'] = TRUE;
1282 // URI: used inside HTML anchor tag pair
1283 if ((! $asap || ! $is_spam) && isset($method['uri_anchor'])) {
1284 $key = 'uri_anchor';
1285 foreach($pickups as $pickup) {
1286 if (isset($pickup['area'][$key])) {
1287 $sum[$key] += $pickup['area'][$key];
1288 if(isset($method[$key]) &&
1289 $sum[$key] > $method[$key]) {
1290 $is_spam[$key] = TRUE;
1291 if ($asap && $is_spam) break;
1293 if ($asap && $is_spam) break;
1298 // URI: used inside 'BBCode' pair
1299 if ((! $asap || ! $is_spam) && isset($method['uri_bbcode'])) {
1300 $key = 'uri_bbcode';
1301 foreach($pickups as $pickup) {
1302 if (isset($pickup['area'][$key])) {
1303 $sum[$key] += $pickup['area'][$key];
1304 if(isset($method[$key]) &&
1305 $sum[$key] > $method[$key]) {
1306 $is_spam[$key] = TRUE;
1307 if ($asap && $is_spam) break;
1309 if ($asap && $is_spam) break;
1314 // URI: Uniqueness (and removing non-uniques)
1315 if ((! $asap || ! $is_spam) && isset($method['non_uniquri'])) {
1318 foreach (array_keys($pickups) as $key) {
1319 $uris[$key] = uri_pickup_implode($pickups[$key]);
1321 $count = count($uris);
1322 $uris = array_unique($uris);
1323 $sum['non_uniquri'] += $count - count($uris);
1324 if ($sum['non_uniquri'] > $method['non_uniquri']) {
1325 $is_spam['non_uniquri'] = TRUE;
1327 if (! $asap || ! $is_spam) {
1328 foreach (array_diff(array_keys($pickups),
1329 array_keys($uris)) as $remove) {
1330 unset($pickups[$remove]);
1337 if ($asap && $is_spam) return $progress;
1339 // Host: Uniqueness (uniq / non-uniq)
1340 foreach ($pickups as $pickup) $hosts[] = & $pickup['host'];
1341 $hosts = array_unique($hosts);
1342 $sum['uniqhost'] += count($hosts);
1343 if ((! $asap || ! $is_spam) && isset($method['non_uniqhost'])) {
1344 $sum['non_uniqhost'] = $sum['quantity'] - $sum['uniqhost'];
1345 if ($sum['non_uniqhost'] > $method['non_uniqhost']) {
1346 $is_spam['non_uniqhost'] = TRUE;
1351 if ($asap && $is_spam) return $progress;
1353 // URI: Bad host (Separate good/bad hosts from $hosts)
1354 if ((! $asap || ! $is_spam) && isset($method['badhost'])) {
1357 $list = get_blocklist('list');
1358 $blocked = blocklist_distiller($hosts, array_keys($list), $asap);
1359 foreach($list as $key=>$type){
1360 if (! $type) unset($blocked[$key]); // Ignore goodhost etc
1364 if (! empty($blocked)) $is_spam['badhost'] = TRUE;
1370 // Count leaves (A leaf = value that is not an array, or an empty array)
1371 function array_count_leaves($array = array(), $count_empty = FALSE)
1373 if (! is_array($array) || (empty($array) && $count_empty)) return 1;
1377 foreach ($array as $part) {
1378 $count += array_count_leaves($part, $count_empty);
1383 // Merge two leaves' value
1384 function array_merge_leaves(& $array1, & $array2, $unique_values = TRUE, $renumber_numeric = TRUE)
1386 $array = array_merge_recursive($array1, $array2);
1388 // Redundant values (and keys) are vanished
1389 if ($unique_values) $array = array_unique_recursive($array);
1391 // All NUMERIC keys are always renumbered from 0
1392 if ($renumber_numeric) array_renumber_numeric_keys($array);
1397 // Shrink array('key' => array('key')) to array('key') (Not used now)
1398 function array_shrink_leaves(& $array)
1400 if (! is_array($array)) return $array;
1402 foreach($array as $key => $value){
1403 // Recurse. Removing more leaves beforehand
1404 if (is_array($value)) array_shrink_leaves($array[$key]);
1408 foreach($array as $key => $value){
1409 if (is_array($value)) {
1410 $count = count($value);
1411 if ($count == 1 && current($value) == $key) {
1412 unset($array[$key]);
1421 // array-leave to flat array() (with unique)
1422 function array_flat_leaves($array)
1425 if (! is_array($array)) return $array;
1428 foreach($array as $key => $value) {
1429 if (is_array($value)) {
1430 foreach(array_flat_leaves($value) as $_value) {
1431 $tmp[$_value] = TRUE;
1434 $tmp[$value] = TRUE;
1438 return array_keys($tmp);
1441 // ---------------------
1444 // TODO: Don't show unused $method!
1445 // Summarize $progress (blocked only)
1446 function summarize_spam_progress($progress = array(), $blockedonly = FALSE)
1449 $tmp = array_keys($progress['is_spam']);
1452 $method = & $progress['method'];
1453 if (isset($progress['sum'])) {
1454 foreach ($progress['sum'] as $key => $value) {
1455 if (isset($method[$key]) && $value) {
1456 $tmp[] = $key . '(' . $value . ')';
1462 return implode(', ', $tmp);
1465 function summarize_detail_badhost($progress = array())
1467 if (! isset($progress['blocked']) || empty($progress['blocked'])) return '';
1470 foreach($progress['blocked'] as $list => $lvalue) {
1471 foreach($lvalue as $group => $gvalue) {
1472 $flat = implode(', ', array_flat_leaves($gvalue));
1473 if ($flat == $group) {
1474 $blocked[$list][] = $flat;
1476 $blocked[$list][$group] = $flat;
1481 return var_export_shrink($blocked, TRUE, TRUE);
1484 function summarize_detail_newtral($progress = array())
1486 if (! isset($progress['hosts']) ||
1487 ! is_array($progress['hosts']) ||
1488 empty($progress['hosts'])) return '';
1492 foreach($progress['hosts'] as $value) {
1493 $tmp[delimiter_reverse($value)] = $value;
1497 return count($tmp) . ' (' .implode(', ', $tmp) . ')';
1501 // ---------------------
1504 // Common bahavior for blocking
1505 // NOTE: Call this function from various blocking feature, to disgueise the reason 'why blocked'
1506 function spam_exit($mode = '', $data = array())
1509 case '': echo("\n"); break;
1511 echo('<pre>' . "\n");
1512 echo htmlspecialchars(var_export($data, TRUE));
1513 echo('</pre>' . "\n");
1522 // ---------------------
1525 // TODO: Record them
1526 // Simple/fast spam filter ($target: 'a string' or an array())
1527 function pkwk_spamfilter($action, $page, $target = array('title' => ''), $method = array(), $exitmode = '')
1529 $progress = check_uri_spam($target, $method);
1531 if (! empty($progress['is_spam'])) {
1532 // Mail to administrator(s)
1533 pkwk_spamnotify($action, $page, $target, $progress, $method);
1536 spam_exit($exitmode, $progress);
1540 // ---------------------
1541 // PukiWiki original
1543 // Mail to administrator(s)
1544 function pkwk_spamnotify($action, $page, $target = array('title' => ''), $progress = array(), $method = array())
1546 global $notify, $notify_subject;
1548 if (! $notify) return;
1550 $asap = isset($method['asap']);
1552 $summary['ACTION'] = 'Blocked by: ' . summarize_spam_progress($progress, TRUE);
1554 $summary['METRICS'] = summarize_spam_progress($progress);
1557 $tmp = summarize_detail_badhost($progress);
1558 if ($tmp != '') $summary['DETAIL_BADHOST'] = $tmp;
1560 $tmp = summarize_detail_newtral($progress);
1561 if (! $asap && $tmp != '') $summary['DETAIL_NEUTRAL_HOST'] = $tmp;
1563 $summary['COMMENT'] = $action;
1564 $summary['PAGE'] = '[blocked] ' . (is_pagename($page) ? $page : '');
1565 $summary['URI'] = get_script_uri() . '?' . rawurlencode($page);
1566 $summary['USER_AGENT'] = TRUE;
1567 $summary['REMOTE_ADDR'] = TRUE;
1568 pkwk_mail_notify($notify_subject, var_export($target, TRUE), $summary, TRUE);