2 // $Id: spam.php,v 1.126 2007/03/17 06:31:24 henoheno Exp $
3 // Copyright (C) 2006-2007 PukiWiki Developers Team
4 // License: GPL v2 or (at your option) any later version
6 // Functions for Concept-work of spam-uri metrics
8 // (PHP 4 >= 4.3.0): preg_match_all(PREG_OFFSET_CAPTURE): $method['uri_XXX'] related feature
10 if (! defined('SPAM_INI_FILE')) define('SPAM_INI_FILE', 'spam.ini.php');
12 // ---------------------
15 // (PHP 4 >= 4.2.0): var_export(): mail-reporting and dump related
16 if (! function_exists('var_export')) {
17 function var_export() {
18 return 'var_export() is not found on this server' . "\n";
22 // (PHP 4 >= 4.2.0): preg_grep() enables invert option
23 function preg_grep_invert($pattern = '//', $input = array())
26 if (! isset($invert)) $invert = defined('PREG_GREP_INVERT');
29 return preg_grep($pattern, $input, PREG_GREP_INVERT);
31 $result = preg_grep($pattern, $input);
33 return array_diff($input, preg_grep($pattern, $input));
40 // ---------------------
43 // Return an array of URIs in the $string
44 // [OK] http://nasty.example.org#nasty_string
45 // [OK] http://nasty.example.org:80/foo/xxx#nasty_string/bar
46 // [OK] ftp://nasty.example.org:80/dfsdfs
47 // [OK] ftp://cnn.example.com&story=breaking_news@10.0.0.1/top_story.htm (from RFC3986)
48 function uri_pickup($string = '', $normalize = TRUE,
49 $preserve_rawuri = FALSE, $preserve_chunk = TRUE)
51 // Not available for: IDN(ignored)
54 // scheme://userinfo@host:port/path/or/pathinfo/maybefile.and?query=string#fragment
55 // Refer RFC3986 (Regex below is not strict)
56 '#(\b[a-z][a-z0-9.+-]{1,8}):/+' . // 1: Scheme
58 '([^\s<>"\'\[\]/\#?@]*)' . // 2: Userinfo (Username)
62 '\[[0-9a-f:.]+\]' . '|' . // IPv6([colon-hex and dot]): RFC2732
63 '(?:[0-9]{1,3}\.){3}[0-9]{1,3}' . '|' . // IPv4(dot-decimal): 001.22.3.44
64 '[a-z0-9.-]+' . // hostname(FQDN) : foo.example.org
66 '(?::([0-9]*))?' . // 4: Port
67 '((?:/+[^\s<>"\'\[\]/\#]+)*/+)?' . // 5: Directory path or path-info
68 '([^\s<>"\'\[\]\#?]+)?' . // 6: File?
69 '(?:\?([^\s<>"\'\[\]\#]+))?' . // 7: Query string
70 '(?:\#([a-z0-9._~%!$&\'()*+,;=:@-]*))?' . // 8: Fragment
72 $string, $array, PREG_SET_ORDER | PREG_OFFSET_CAPTURE
76 static $parts = array(
77 1 => 'scheme', 2 => 'userinfo', 3 => 'host', 4 => 'port',
78 5 => 'path', 6 => 'file', 7 => 'query', 8 => 'fragment'
81 foreach(array_keys($array) as $uri) {
82 $_uri = & $array[$uri];
83 array_rename_keys($_uri, $parts, TRUE, $default);
85 $offset = $_uri['scheme'][1]; // Scheme's offset
86 foreach(array_keys($_uri) as $part) {
87 // Remove offsets for each part
88 $_uri[$part] = & $_uri[$part][0];
92 $_uri['scheme'] = scheme_normalize($_uri['scheme']);
93 if ($_uri['scheme'] === '') {
97 $_uri['host'] = host_normalize($_uri['host']);
98 $_uri['port'] = port_normalize($_uri['port'], $_uri['scheme'], FALSE);
99 $_uri['path'] = path_normalize($_uri['path']);
100 if ($preserve_rawuri) $_uri['rawuri'] = & $_uri[0];
103 //$_uri['uri'] = uri_array_implode($_uri);
105 $_uri['uri'] = & $_uri[0]; // Raw
107 unset($_uri[0]); // Matched string itself
108 if (! $preserve_chunk) {
121 // Area offset for area_measure()
122 $_uri['area']['offset'] = $offset;
128 // Destructive normalize of URI array
129 // NOTE: Give me the uri_pickup() result with chunks
130 function uri_array_normalize(& $pickups, $preserve = TRUE)
132 if (! is_array($pickups)) return $pickups;
134 foreach (array_keys($pickups) as $key) {
135 $_key = & $pickups[$key];
136 $_key['path'] = isset($_key['path']) ? strtolower($_key['path']) : '';
137 $_key['file'] = isset($_key['file']) ? file_normalize($_key['file']) : '';
138 $_key['query'] = isset($_key['query']) ? query_normalize(strtolower($_key['query']), TRUE) : '';
139 $_key['fragment'] = (isset($_key['fragment']) && $preserve) ?
140 strtolower($_key['fragment']) : ''; // Just ignore
146 // An URI array => An URI (See uri_pickup())
147 function uri_array_implode($uri = array())
149 if (empty($uri) || ! is_array($uri)) return NULL;
152 if (isset($uri['scheme']) && $uri['scheme'] !== '') {
153 $tmp[] = & $uri['scheme'];
156 if (isset($uri['userinfo']) && $uri['userinfo'] !== '') {
157 $tmp[] = & $uri['userinfo'];
160 if (isset($uri['host']) && $uri['host'] !== '') {
161 $tmp[] = & $uri['host'];
163 if (isset($uri['port']) && $uri['port'] !== '') {
165 $tmp[] = & $uri['port'];
167 if (isset($uri['path']) && $uri['path'] !== '') {
168 $tmp[] = & $uri['path'];
170 if (isset($uri['file']) && $uri['file'] !== '') {
171 $tmp[] = & $uri['file'];
173 if (isset($uri['query']) && $uri['query'] !== '') {
175 $tmp[] = & $uri['query'];
177 if (isset($uri['fragment']) && $uri['fragment'] !== '') {
179 $tmp[] = & $uri['fragment'];
182 return implode('', $tmp);
185 // $array['something'] => $array['wanted']
186 function array_rename_keys(& $array, $keys = array('from' => 'to'), $force = FALSE, $default = '')
188 if (! is_array($array) || ! is_array($keys)) return FALSE;
190 // Nondestructive test
192 foreach(array_keys($keys) as $from)
193 if (! isset($array[$from]))
196 foreach($keys as $from => $to) {
197 if ($from === $to) continue;
198 if (! $force || isset($array[$from])) {
199 $array[$to] = & $array[$from];
200 unset($array[$from]);
202 $array[$to] = $default;
209 // ---------------------
212 // Pickup all of markup areas
213 function area_pickup($string = '', $method = array())
216 if (empty($method)) return $area;
218 // Anchor tag pair by preg_match and preg_match_all()
220 // [OK] <a href= >Good site!</a>
221 // [OK] <a href= "#" >test</a>
222 // [OK] <a href="http://nasty.example.com">visit http://nasty.example.com/</a>
223 // [OK] <a href=\'http://nasty.example.com/\' >discount foobar</a>
224 // [NG] <a href="http://ng.example.com">visit http://ng.example.com _not_ended_
225 $regex = '#<a\b[^>]*\bhref\b[^>]*>.*?</a\b[^>]*(>)#i';
226 if (isset($method['area_anchor'])) {
228 $count = isset($method['asap']) ?
229 preg_match($regex, $string) :
230 preg_match_all($regex, $string, $areas);
231 if (! empty($count)) $area['area_anchor'] = $count;
233 if (isset($method['uri_anchor'])) {
235 preg_match_all($regex, $string, $areas, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
236 foreach(array_keys($areas) as $_area) {
237 $areas[$_area] = array(
238 $areas[$_area][0][1], // Area start (<a href>)
239 $areas[$_area][1][1], // Area end (</a>)
242 if (! empty($areas)) $area['uri_anchor'] = $areas;
245 // phpBB's "BBCode" pair by preg_match and preg_match_all()
247 // [OK] [url]http://nasty.example.com/[/url]
248 // [OK] [link]http://nasty.example.com/[/link]
249 // [OK] [url=http://nasty.example.com]visit http://nasty.example.com/[/url]
250 // [OK] [link http://nasty.example.com/]buy something[/link]
251 $regex = '#\[(url|link)\b[^\]]*\].*?\[/\1\b[^\]]*(\])#i';
252 if (isset($method['area_bbcode'])) {
254 $count = isset($method['asap']) ?
255 preg_match($regex, $string) :
256 preg_match_all($regex, $string, $areas, PREG_SET_ORDER);
257 if (! empty($count)) $area['area_bbcode'] = $count;
259 if (isset($method['uri_bbcode'])) {
261 preg_match_all($regex, $string, $areas, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
262 foreach(array_keys($areas) as $_area) {
263 $areas[$_area] = array(
264 $areas[$_area][0][1], // Area start ([url])
265 $areas[$_area][2][1], // Area end ([/url])
268 if (! empty($areas)) $area['uri_bbcode'] = $areas;
271 // Various Wiki syntax
272 // [text_or_uri>text_or_uri]
273 // [text_or_uri:text_or_uri]
274 // [text_or_uri|text_or_uri]
275 // [text_or_uri->text_or_uri]
276 // [text_or_uri text_or_uri] // MediaWiki
277 // MediaWiki: [http://nasty.example.com/ visit http://nasty.example.com/]
282 // If in doubt, it's a little doubtful
283 // if (Area => inside <= Area) $brief += -1
284 function area_measure($areas, & $array, $belief = -1, $a_key = 'area', $o_key = 'offset')
286 if (! is_array($areas) || ! is_array($array)) return;
288 $areas_keys = array_keys($areas);
289 foreach(array_keys($array) as $u_index) {
290 $offset = isset($array[$u_index][$o_key]) ?
291 intval($array[$u_index][$o_key]) : 0;
292 foreach($areas_keys as $a_index) {
293 if (isset($array[$u_index][$a_key])) {
294 $offset_s = intval($areas[$a_index][0]);
295 $offset_e = intval($areas[$a_index][1]);
296 // [Area => inside <= Area]
297 if ($offset_s < $offset && $offset < $offset_e) {
298 $array[$u_index][$a_key] += $belief;
305 // ---------------------
308 // Domain exposure callback (See spam_uri_pickup_preprocess())
309 // http://victim.example.org/?foo+site:nasty.example.com+bar
310 // => http://nasty.example.com/?refer=victim.example.org
311 // NOTE: 'refer=' is not so good for (at this time).
312 // Consider about using IP address of the victim, try to avoid that.
313 function _preg_replace_callback_domain_exposure($matches = array())
317 // Preserve the victim URI as a complicity or ...
318 if (isset($matches[5])) {
320 $matches[1] . '://' . // scheme
321 $matches[2] . '/' . // victim.example.org
322 $matches[3]; // The rest of all (before victim)
326 if (isset($matches[4])) {
328 $matches[1] . '://' . // scheme
329 $matches[4] . // nasty.example.com
330 '/?refer=' . strtolower($matches[2]) . // victim.example.org
337 // Preprocess: rawurldecode() and adding space(s) and something
338 // to detect/count some URIs _if possible_
339 // NOTE: It's maybe danger to var_dump(result). [e.g. 'javascript:']
340 // [OK] http://victim.example.org/go?http%3A%2F%2Fnasty.example.org
341 // [OK] http://victim.example.org/http://nasty.example.org
342 // TODO: link.toolbot.com, urlx.org
343 function spam_uri_pickup_preprocess($string = '')
345 if (! is_string($string)) return '';
347 $string = rawurldecode($string);
349 // Domain exposure (See _preg_replace_callback_domain_exposure())
350 $string = preg_replace_callback(
354 // Something Google: http://www.google.com/supported_domains
355 '(?:[a-z0-9.]+\.)?google\.[a-z]{2,3}(?:\.[a-z]{2})?' .
358 '(?:[a-z0-9.]+\.)?altavista.com' .
362 '([a-z0-9?=&.%_/\'\\\+-]+)' . // path/?query=foo+bar+
363 '\bsite:([a-z0-9.%_-]+\.[a-z0-9.%_-]+)' . // site:nasty.example.com
364 //'()' . // Preserve or remove?
367 '_preg_replace_callback_domain_exposure',
371 // URI exposure (uriuri => uri uri)
372 $string = preg_replace(
374 '#(?<! )(?:https?|ftp):/#i',
375 // '#[a-z][a-z0-9.+-]{1,8}://#i',
376 // '#[a-z][a-z0-9.+-]{1,8}://#i'
385 // Main function of spam-uri pickup
386 function spam_uri_pickup($string = '', $method = array())
388 if (! is_array($method) || empty($method)) {
389 $method = check_uri_spam_method();
392 $string = spam_uri_pickup_preprocess($string);
394 $array = uri_pickup($string);
396 // Area elevation of URIs, for '(especially external)link' intension
397 if (! empty($array)) {
399 if (isset($method['uri_anchor'])) $_method['uri_anchor'] = & $method['uri_anchor'];
400 if (isset($method['uri_bbcode'])) $_method['uri_bbcode'] = & $method['uri_bbcode'];
401 $areas = area_pickup($string, $_method, TRUE);
402 if (! empty($areas)) {
403 $area_shadow = array();
404 foreach (array_keys($array) as $key) {
405 $area_shadow[$key] = & $array[$key]['area'];
406 foreach (array_keys($_method) as $_key) {
407 $area_shadow[$key][$_key] = 0;
410 foreach (array_keys($_method) as $_key) {
411 if (isset($areas[$_key])) {
412 area_measure($areas[$_key], $area_shadow, 1, $_key);
418 // Remove 'offset's for area_measure()
419 foreach(array_keys($array) as $key)
420 unset($array[$key]['area']['offset']);
426 // ---------------------
429 // Scheme normalization: Renaming the schemes
430 // snntp://example.org => nntps://example.org
431 // NOTE: Keep the static lists simple. See also port_normalize().
432 function scheme_normalize($scheme = '', $considerd_harmfull = TRUE)
434 // Abbreviations considerable they don't have link intension
435 static $abbrevs = array(
440 // Alias => normalized
441 static $aliases = array(
451 $scheme = strtolower(trim($scheme));
452 if (isset($abbrevs[$scheme])) {
453 if ($considerd_harmfull) {
454 $scheme = $abbrevs[$scheme];
459 if (isset($aliases[$scheme])) $scheme = $aliases[$scheme];
464 // Hostname normlization
465 // www.foo => www.foo ('foo' seems TLD)
466 // www.foo.bar => foo.bar
467 // www.10.20 => www.10.20 (Invalid hostname)
469 // 'www' is mostly used as traditional hostname of WWW server.
470 // 'www.foo.bar' may be identical with 'foo.bar'.
471 function host_normalize($host = '')
473 $host = strtolower($host);
476 if (preg_match('/^www\.(.+\.[a-z]+)$/', $host, $matches)) {
483 // Port normalization: Suppress the (redundant) default port
484 // HTTP://example.org:80/ => http://example.org/
485 // HTTP://example.org:8080/ => http://example.org:8080/
486 // HTTPS://example.org:443/ => https://example.org/
487 function port_normalize($port, $scheme, $scheme_normalize = TRUE)
489 // Schemes that users _maybe_ want to add protocol-handlers
490 // to their web browsers. (and attackers _maybe_ want to use ...)
491 // Reference: http://www.iana.org/assignments/port-numbers
492 static $array = array(
493 // scheme => default port
520 if ($port === '') return $port;
522 if ($scheme_normalize) $scheme = scheme_normalize($scheme);
523 if (isset($array[$scheme]) && $port == $array[$scheme])
524 $port = ''; // Ignore the defaults
529 // Path normalization
530 // http://example.org => http://example.org/
531 // http://example.org#hoge => http://example.org/#hoge
532 // http://example.org/path/a/b/./c////./d => http://example.org/path/a/b/c/d
533 // http://example.org/path/../../a/../back => http://example.org/back
534 function path_normalize($path = '', $divider = '/', $addroot = TRUE)
536 if (! is_string($path) || $path == '')
537 return $addroot ? $divider : '';
540 $last = ($path[strlen($path) - 1] == $divider) ? $divider : '';
541 $array = explode($divider, $path);
544 foreach(array_keys($array) as $key) {
545 if ($array[$key] == '' || $array[$key] == '.')
550 foreach($array as $value) {
551 if ($value == '..') {
554 array_push($tmp, $value);
559 $path = $addroot ? $divider : '';
560 if (! empty($array)) $path .= implode($divider, $array) . $last;
565 // DirectoryIndex normalize (Destructive and rough)
566 function file_normalize($string = 'index.html.en')
568 static $array = array(
569 'index' => TRUE, // Some system can omit the suffix
571 'index.html' => TRUE,
572 'index.shtml' => TRUE,
575 'index.php3' => TRUE,
576 'index.php4' => TRUE,
577 //'index.pl' => TRUE,
578 //'index.py' => TRUE,
579 //'index.rb' => TRUE,
581 'default.htm' => TRUE,
582 'default.html' => TRUE,
583 'default.asp' => TRUE,
584 'default.aspx' => TRUE,
587 // Content-negothiation filter:
588 // Roughly removing ISO 639 -like
589 // 2-letter suffixes (See RFC3066)
591 if (preg_match('/(.+)\.[a-z][a-z](?:-[a-z][a-z])?$/i', $string, $matches)) {
592 $_string = $matches[1];
594 $_string = & $string;
597 if (isset($array[strtolower($_string)])) {
604 // Sort query-strings if possible (Destructive and rough)
605 // [OK] &&&&f=d&b&d&c&a=0dd => a=0dd&b&c&d&f=d
606 // [OK] nothing==&eg=dummy&eg=padding&eg=foobar => eg=foobar
607 function query_normalize($string = '', $equal = FALSE, $equal_cutempty = TRUE)
609 $array = explode('&', $string);
611 // Remove '&' paddings
612 foreach(array_keys($array) as $key) {
613 if ($array[$key] == '') {
618 // Consider '='-sepalated input and paddings
620 $equals = $not_equals = array();
621 foreach ($array as $part) {
622 if (strpos($part, '=') === FALSE) {
623 $not_equals[] = $part;
625 list($key, $value) = explode('=', $part, 2);
626 $value = ltrim($value, '=');
627 if (! $equal_cutempty || $value != '') {
628 $equals[$key] = $value;
633 $array = & $not_equals;
634 foreach ($equals as $key => $value) {
635 $array[] = $key . '=' . $value;
641 return implode('&', $array);
644 // ---------------------
645 // Part One : Checker
647 // Rough implementation of globbing
649 // USAGE: $regex = '/^' . generate_glob_regex('*.txt', '/') . '$/i';
651 function generate_glob_regex($string = '', $divider = '/')
653 static $from = array(
656 // 22 => '[', // Maybe cause regex compilation error (e.g. '[]')
672 $string = str_replace($from, $mid, $string); // Hide
673 $string = preg_quote($string, $divider);
674 $string = str_replace($mid, $to, $string); // Unhide
679 // Rough hostname checker
681 // TODO: Strict digit, 0x, CIDR, IPv6
682 function is_ip($string = '')
684 if (preg_match('/^' .
685 '(?:[0-9]{1,3}\.){3}[0-9]{1,3}' . '|' .
686 '(?:[0-9]{1,3}\.){1,3}' . '$/',
688 return 4; // Seems IPv4(dot-decimal)
690 return 0; // Seems not IP
694 // Generate host (FQDN, IPv4, ...) regex
695 // 'localhost' : Matches with 'localhost' only
696 // 'example.org' : Matches with 'example.org' only (See host_normalize() about 'www')
697 // '.example.org' : Matches with ALL FQDN ended with '.example.org'
698 // '*.example.org' : Almost the same of '.example.org' except 'www.example.org'
699 // '10.20.30.40' : Matches with IPv4 address '10.20.30.40' only
700 // [TODO] '192.' : Matches with all IPv4 hosts started with '192.'
701 // TODO: IPv4, CIDR?, IPv6
702 function generate_host_regex($string = '', $divider = '/')
704 if (mb_strpos($string, '.') === FALSE)
705 return generate_glob_regex($string, $divider);
708 if (is_ip($string)) {
710 return generate_glob_regex($string, $divider);
713 $part = explode('.', $string, 2);
714 if ($part[0] == '') {
715 $part[0] = '(?:.*\.)?'; // And all related FQDN
716 } else if ($part[0] == '*') {
717 $part[0] = '.*\.'; // All subdomains/hosts only
719 return generate_glob_regex($string, $divider);
721 $part[1] = generate_glob_regex($part[1], $divider);
722 return implode('', $part);
726 function get_blocklist($list = '')
730 if (! isset($regexs)) {
732 if (file_exists(SPAM_INI_FILE)) {
733 $blocklist = array();
734 include(SPAM_INI_FILE);
735 // $blocklist['badhost'] = array(
736 // '*.blogspot.com', // Blog services's subdomains (only)
737 // 'IANA-examples' => '#^(?:.*\.)?example\.(?:com|net|org)$#',
739 foreach(array('goodhost', 'badhost') as $_list) {
740 if (! isset($blocklist[$list])) continue;
741 foreach ($blocklist[$_list] as $key => $value) {
742 if (is_array($value)) {
743 $regexs[$_list][$key] = array();
744 foreach($value as $_key => $_value) {
745 get_blocklist_add($regexs[$_list][$key], $_key, $_value);
748 get_blocklist_add($regexs[$_list], $key, $value);
756 return $regexs; // ALL
757 } else if (isset($regexs[$list])) {
758 return $regexs[$list];
764 // Subroutine of get_blocklist()
765 function get_blocklist_add(& $array, $key = 0, $value = '*.example.org')
767 if (is_string($key)) {
768 $array[$key] = & $value; // Treat $value as a regex
770 $array[$value] = '/^' . generate_host_regex($value, '/') . '$/i';
774 function is_badhost($hosts = array(), $asap = TRUE, & $remains)
777 if (! is_array($hosts)) $hosts = array($hosts);
778 foreach(array_keys($hosts) as $key) {
779 if (! is_string($hosts[$key])) unset($hosts[$key]);
781 if (empty($hosts)) return $result;
783 foreach (get_blocklist('goodhost') as $regex) {
784 $hosts = preg_grep_invert($regex, $hosts);
786 if (empty($hosts)) return $result;
789 foreach (get_blocklist('badhost') as $label => $regex) {
790 if (is_array($regex)) {
791 $result[$label] = array();
792 foreach($regex as $_label => $_regex) {
793 if (is_badhost_avail($_label, $_regex, $hosts, $result[$label]) && $asap) break;
795 if (empty($result[$label])) unset($result[$label]);
797 if (is_badhost_avail($label, $regex, $hosts, $result) && $asap) break;
806 // Subroutine for is_badhost()
807 function is_badhost_avail($label = '*.example.org', $regex = '/^.*\.example\.org$/', & $hosts, & $result)
809 $group = preg_grep($regex, $hosts);
811 $result[$label] = & $group;
812 $hosts = array_diff($hosts, $result[$label]);
819 // Default (enabled) methods and thresholds (for content insertion)
820 function check_uri_spam_method($times = 1, $t_area = 0, $rule = TRUE)
822 $times = intval($times);
823 $t_area = intval($t_area);
827 'quantity' => 8 * $times, // Allow N URIs
828 'non_uniqhost' => 3 * $times, // Allow N duped (and normalized) Hosts
829 //'non_uniquri'=> 3 * $times, // Allow N duped (and normalized) URIs
832 'area_anchor' => $t_area, // Using <a href> HTML tag
833 'area_bbcode' => $t_area, // Using [url] or [link] BBCode
834 //'uri_anchor' => $t_area, // URI inside <a href> HTML tag
835 //'uri_bbcode' => $t_area, // URI inside [url] or [link] BBCode
840 //'asap' => TRUE, // Quit or return As Soon As Possible
841 'uniqhost' => TRUE, // Show uniq host (at block notification mail)
842 'badhost' => TRUE, // Check badhost
848 // Remove non-$positive values
849 foreach (array_keys($positive) as $key) {
850 if ($positive[$key] < 0) unset($positive[$key]);
853 return $positive + $bool;
856 // Simple/fast spam check
857 function check_uri_spam($target = '', $method = array())
859 if (! is_array($method) || empty($method)) {
860 $method = check_uri_spam_method();
874 'is_spam' => array(),
875 'method' => & $method,
876 'remains' => array(),
879 $sum = & $progress['sum'];
880 $is_spam = & $progress['is_spam'];
881 $remains = & $progress['remains'];
882 $error = & $progress['error'];
883 $asap = isset($method['asap']);
886 if (is_array($target)) {
887 foreach($target as $str) {
889 $_progress = check_uri_spam($str, $method);
890 $_sum = & $_progress['sum'];
891 $_is_spam = & $_progress['is_spam'];
892 $_remains = & $_progress['remains'];
893 $_error = & $_progress['error'];
894 foreach (array_keys($_sum) as $key) {
895 $sum[$key] += $_sum[$key];
897 foreach (array_keys($_is_spam) as $key) {
898 if (is_array($_is_spam[$key])) {
899 // Marge keys (badhost)
900 foreach(array_keys($_is_spam[$key]) as $_key) {
901 if (! isset($is_spam[$key][$_key])) {
902 $is_spam[$key][$_key] = $_is_spam[$key][$_key];
904 $is_spam[$key][$_key] += $_is_spam[$key][$_key];
908 $is_spam[$key] = TRUE;
911 foreach ($_remains as $key=>$value) {
912 foreach ($value as $_key=>$_value) {
914 $remains[$key][] = $_value;
916 $remains[$key][$_key] = $_value;
920 if (! empty($_error)) $error += $_error;
921 if ($asap && $is_spam) break;
926 // Area: There's HTML anchor tag
927 if ((! $asap || ! $is_spam) && isset($method['area_anchor'])) {
928 $key = 'area_anchor';
929 $_asap = isset($method['asap']) ? array('asap' => TRUE) : array();
930 $result = area_pickup($target, array($key => TRUE) + $_asap);
932 $sum[$key] = $result[$key];
933 if (isset($method[$key]) && $sum[$key] > $method[$key]) {
934 $is_spam[$key] = TRUE;
939 // Area: There's 'BBCode' linking tag
940 if ((! $asap || ! $is_spam) && isset($method['area_bbcode'])) {
941 $key = 'area_bbcode';
942 $_asap = isset($method['asap']) ? array('asap' => TRUE) : array();
943 $result = area_pickup($target, array($key => TRUE) + $_asap);
945 $sum[$key] = $result[$key];
946 if (isset($method[$key]) && $sum[$key] > $method[$key]) {
947 $is_spam[$key] = TRUE;
953 if ($asap && $is_spam) return $progress;
956 $pickups = spam_uri_pickup($target, $method);
957 //$remains['uri_pickup'] = & $pickups;
960 if (empty($pickups)) return $progress;
962 // URI: Check quantity
963 $sum['quantity'] += count($pickups);
965 if ((! $asap || ! $is_spam) && isset($method['quantity']) &&
966 $sum['quantity'] > $method['quantity']) {
967 $is_spam['quantity'] = TRUE;
970 // URI: used inside HTML anchor tag pair
971 if ((! $asap || ! $is_spam) && isset($method['uri_anchor'])) {
973 foreach($pickups as $pickup) {
974 if (isset($pickup['area'][$key])) {
975 $sum[$key] += $pickup['area'][$key];
976 if(isset($method[$key]) &&
977 $sum[$key] > $method[$key]) {
978 $is_spam[$key] = TRUE;
979 if ($asap && $is_spam) break;
981 if ($asap && $is_spam) break;
986 // URI: used inside 'BBCode' pair
987 if ((! $asap || ! $is_spam) && isset($method['uri_bbcode'])) {
989 foreach($pickups as $pickup) {
990 if (isset($pickup['area'][$key])) {
991 $sum[$key] += $pickup['area'][$key];
992 if(isset($method[$key]) &&
993 $sum[$key] > $method[$key]) {
994 $is_spam[$key] = TRUE;
995 if ($asap && $is_spam) break;
997 if ($asap && $is_spam) break;
1002 // URI: Uniqueness (and removing non-uniques)
1003 if ((! $asap || ! $is_spam) && isset($method['non_uniquri'])) {
1005 // Destructive normalize of URIs
1006 uri_array_normalize($pickups);
1009 foreach (array_keys($pickups) as $key) {
1010 $uris[$key] = uri_array_implode($pickups[$key]);
1012 $count = count($uris);
1013 $uris = array_unique($uris);
1014 $sum['non_uniquri'] += $count - count($uris);
1015 if ($sum['non_uniquri'] > $method['non_uniquri']) {
1016 $is_spam['non_uniquri'] = TRUE;
1018 if (! $asap || ! $is_spam) {
1019 foreach (array_diff(array_keys($pickups),
1020 array_keys($uris)) as $remove) {
1021 unset($pickups[$remove]);
1028 if ($asap && $is_spam) return $progress;
1030 // Host: Uniqueness (uniq / non-uniq)
1032 foreach ($pickups as $pickup) $hosts[] = & $pickup['host'];
1033 $hosts = array_unique($hosts);
1034 //$remains['uniqhost'] = & $hosts;
1035 $sum['uniqhost'] += count($hosts);
1036 if ((! $asap || ! $is_spam) && isset($method['non_uniqhost'])) {
1037 $sum['non_uniqhost'] = $sum['quantity'] - $sum['uniqhost'];
1038 if ($sum['non_uniqhost'] > $method['non_uniqhost']) {
1039 $is_spam['non_uniqhost'] = TRUE;
1044 if ($asap && $is_spam) return $progress;
1047 if ((! $asap || ! $is_spam) && isset($method['badhost'])) {
1048 $__remains = array();
1049 $badhost = is_badhost($hosts, $asap, $__remains);
1052 $remains['badhost'] = array();
1053 foreach ($__remains as $value) {
1054 $remains['badhost'][$value] = TRUE;
1059 if (! empty($badhost)) {
1060 //var_dump($badhost); // BADHOST detail
1061 $sum['badhost'] += array_count_leaves($badhost);
1062 foreach(array_keys($badhost) as $keys) {
1063 $is_spam['badhost'][$keys] =
1064 array_count_leaves($badhost[$keys]);
1074 function array_count_leaves($array = array(), $count_empty_array = FALSE)
1076 if (! is_array($array) || (empty($array) && $count_empty_array))
1081 foreach ($array as $part) {
1082 $result += array_count_leaves($part, $count_empty_array);
1087 // ---------------------
1090 // TODO: Don't show unused $method!
1091 // Summarize $progress (blocked only)
1092 function summarize_spam_progress($progress = array(), $blockedonly = FALSE)
1095 $tmp = array_keys($progress['is_spam']);
1098 $method = & $progress['method'];
1099 if (isset($progress['sum'])) {
1100 foreach ($progress['sum'] as $key => $value) {
1101 if (isset($method[$key])) {
1102 $tmp[] = $key . '(' . $value . ')';
1108 return implode(', ', $tmp);
1111 // ---------------------
1114 // Common bahavior for blocking
1115 // NOTE: Call this function from various blocking feature, to disgueise the reason 'why blocked'
1116 function spam_exit($mode = '', $data = array())
1119 case '': echo("\n"); break;
1121 echo('<pre>' . "\n");
1122 echo htmlspecialchars(var_export($data, TRUE));
1123 echo('</pre>' . "\n");
1132 // ---------------------
1135 // TODO: Record them
1136 // Simple/fast spam filter ($target: 'a string' or an array())
1137 function pkwk_spamfilter($action, $page, $target = array('title' => ''), $method = array(), $exitmode = '')
1139 $progress = check_uri_spam($target, $method);
1141 if (! empty($progress['is_spam'])) {
1142 // Mail to administrator(s)
1143 pkwk_spamnotify($action, $page, $target, $progress, $method);
1146 spam_exit($exitmode, $progress);
1150 // ---------------------
1151 // PukiWiki original
1153 // Mail to administrator(s)
1154 function pkwk_spamnotify($action, $page, $target = array('title' => ''), $progress = array(), $method = array())
1156 global $notify, $notify_subject;
1158 if (! $notify) return;
1160 $asap = isset($method['asap']);
1162 $summary['ACTION'] = 'Blocked by: ' . summarize_spam_progress($progress, TRUE);
1164 $summary['METRICS'] = summarize_spam_progress($progress);
1166 if (isset($progress['is_spam']['badhost'])) {
1168 foreach($progress['is_spam']['badhost'] as $glob=>$number) {
1169 $badhost[] = $glob . '(' . $number . ')';
1171 $summary['DETAIL_BADHOST'] = implode(', ', $badhost);
1173 if (! $asap && $progress['remains']['badhost']) {
1174 $count = count($progress['remains']['badhost']);
1175 $summary['DETAIL_NEUTRAL_HOST'] = $count .
1178 '/[^, a-z0-9.-]/i', '',
1179 implode(', ', array_keys($progress['remains']['badhost']))
1183 $summary['COMMENT'] = $action;
1184 $summary['PAGE'] = '[blocked] ' . (is_pagename($page) ? $page : '');
1185 $summary['URI'] = get_script_uri() . '?' . rawurlencode($page);
1186 $summary['USER_AGENT'] = TRUE;
1187 $summary['REMOTE_ADDR'] = TRUE;
1188 pkwk_mail_notify($notify_subject, var_export($target, TRUE), $summary, TRUE);