2 // $Id: spam.php,v 1.120 2007/02/21 14:19:58 henoheno Exp $
3 // Copyright (C) 2006-2007 PukiWiki Developers Team
4 // License: GPL v2 or (at your option) any later version
5 // Functions for Concept-work of spam-uri metrics
6 // (PHP 4 >= 4.3.0): preg_match_all(PREG_OFFSET_CAPTURE): $method['uri_XXX'] related feature
8 if (! defined('SPAM_INI_FILE')) define('SPAM_INI_FILE', 'spam.ini.php');
10 // ---------------------
13 // (PHP 4 >= 4.2.0): var_export(): mail-reporting and dump related
14 if (! function_exists('var_export')) {
15 function var_export() {
16 return 'var_export() is not found on this server' . "\n";
20 // (PHP 4 >= 4.2.0): preg_grep() enables invert option
21 function preg_grep_invert($pattern = '//', $input = array())
24 if (! isset($invert)) $invert = defined('PREG_GREP_INVERT');
27 return preg_grep($pattern, $input, PREG_GREP_INVERT);
29 $result = preg_grep($pattern, $input);
31 return array_diff($input, preg_grep($pattern, $input));
38 // ---------------------
41 // Return an array of URIs in the $string
42 // [OK] http://nasty.example.org#nasty_string
43 // [OK] http://nasty.example.org:80/foo/xxx#nasty_string/bar
44 // [OK] ftp://nasty.example.org:80/dfsdfs
45 // [OK] ftp://cnn.example.com&story=breaking_news@10.0.0.1/top_story.htm (from RFC3986)
46 function uri_pickup($string = '', $normalize = TRUE,
47 $preserve_rawuri = FALSE, $preserve_chunk = TRUE)
49 // Not available for: IDN(ignored)
52 // scheme://userinfo@host:port/path/or/pathinfo/maybefile.and?query=string#fragment
53 // Refer RFC3986 (Regex below is not strict)
54 '#(\b[a-z][a-z0-9.+-]{1,8}):/+' . // 1: Scheme
56 '([^\s<>"\'\[\]/\#?@]*)' . // 2: Userinfo (Username)
60 '\[[0-9a-f:.]+\]' . '|' . // IPv6([colon-hex and dot]): RFC2732
61 '(?:[0-9]{1-3}\.){3}[0-9]{1-3}' . '|' . // IPv4(dot-decimal): 001.22.3.44
62 '[a-z0-9.-]+' . // hostname(FQDN) : foo.example.org
64 '(?::([0-9]*))?' . // 4: Port
65 '((?:/+[^\s<>"\'\[\]/\#]+)*/+)?' . // 5: Directory path or path-info
66 '([^\s<>"\'\[\]\#?]+)?' . // 6: File?
67 '(?:\?([^\s<>"\'\[\]\#]+))?' . // 7: Query string
68 '(?:\#([a-z0-9._~%!$&\'()*+,;=:@-]*))?' . // 8: Fragment
70 $string, $array, PREG_SET_ORDER | PREG_OFFSET_CAPTURE
74 static $parts = array(
75 1 => 'scheme', 2 => 'userinfo', 3 => 'host', 4 => 'port',
76 5 => 'path', 6 => 'file', 7 => 'query', 8 => 'fragment'
79 foreach(array_keys($array) as $uri) {
80 $_uri = & $array[$uri];
81 array_rename_keys($_uri, $parts, TRUE, $default);
83 $offset = $_uri['scheme'][1]; // Scheme's offset
84 foreach(array_keys($_uri) as $part) {
85 // Remove offsets for each part
86 $_uri[$part] = & $_uri[$part][0];
90 $_uri['scheme'] = scheme_normalize($_uri['scheme']);
91 if ($_uri['scheme'] === '') {
95 $_uri['host'] = strtolower($_uri['host']);
96 $_uri['port'] = port_normalize($_uri['port'], $_uri['scheme'], FALSE);
97 $_uri['path'] = path_normalize($_uri['path']);
98 if ($preserve_rawuri) $_uri['rawuri'] = & $_uri[0];
101 //$_uri['uri'] = uri_array_implode($_uri);
103 $_uri['uri'] = & $_uri[0]; // Raw
105 unset($_uri[0]); // Matched string itself
106 if (! $preserve_chunk) {
119 // Area offset for area_measure()
120 $_uri['area']['offset'] = $offset;
126 // Destructive normalize of URI array
127 // NOTE: Give me the uri_pickup() result with chunks
128 function uri_array_normalize(& $pickups, $preserve = TRUE)
130 if (! is_array($pickups)) return $pickups;
132 foreach (array_keys($pickups) as $key) {
133 $_key = & $pickups[$key];
134 $_key['path'] = isset($_key['path']) ? strtolower($_key['path']) : '';
135 $_key['file'] = isset($_key['file']) ? file_normalize($_key['file']) : '';
136 $_key['query'] = isset($_key['query']) ? query_normalize(strtolower($_key['query']), TRUE) : '';
137 $_key['fragment'] = (isset($_key['fragment']) && $preserve) ?
138 strtolower($_key['fragment']) : ''; // Just ignore
144 // An URI array => An URI (See uri_pickup())
145 function uri_array_implode($uri = array())
147 if (empty($uri) || ! is_array($uri)) return NULL;
150 if (isset($uri['scheme']) && $uri['scheme'] !== '') {
151 $tmp[] = & $uri['scheme'];
154 if (isset($uri['userinfo']) && $uri['userinfo'] !== '') {
155 $tmp[] = & $uri['userinfo'];
158 if (isset($uri['host']) && $uri['host'] !== '') {
159 $tmp[] = & $uri['host'];
161 if (isset($uri['port']) && $uri['port'] !== '') {
163 $tmp[] = & $uri['port'];
165 if (isset($uri['path']) && $uri['path'] !== '') {
166 $tmp[] = & $uri['path'];
168 if (isset($uri['file']) && $uri['file'] !== '') {
169 $tmp[] = & $uri['file'];
171 if (isset($uri['query']) && $uri['query'] !== '') {
173 $tmp[] = & $uri['query'];
175 if (isset($uri['fragment']) && $uri['fragment'] !== '') {
177 $tmp[] = & $uri['fragment'];
180 return implode('', $tmp);
183 // $array['something'] => $array['wanted']
184 function array_rename_keys(& $array, $keys = array('from' => 'to'), $force = FALSE, $default = '')
186 if (! is_array($array) || ! is_array($keys)) return FALSE;
188 // Nondestructive test
190 foreach(array_keys($keys) as $from)
191 if (! isset($array[$from]))
194 foreach($keys as $from => $to) {
195 if ($from === $to) continue;
196 if (! $force || isset($array[$from])) {
197 $array[$to] = & $array[$from];
198 unset($array[$from]);
200 $array[$to] = $default;
207 // ---------------------
210 // Pickup all of markup areas
211 function area_pickup($string = '', $method = array())
214 if (empty($method)) return $area;
216 // Anchor tag pair by preg_match and preg_match_all()
218 // [OK] <a href= >Good site!</a>
219 // [OK] <a href= "#" >test</a>
220 // [OK] <a href="http://nasty.example.com">visit http://nasty.example.com/</a>
221 // [OK] <a href=\'http://nasty.example.com/\' >discount foobar</a>
222 // [NG] <a href="http://ng.example.com">visit http://ng.example.com _not_ended_
223 $regex = '#<a\b[^>]*\bhref\b[^>]*>.*?</a\b[^>]*(>)#i';
224 if (isset($method['area_anchor'])) {
226 $count = isset($method['asap']) ?
227 preg_match($regex, $string) :
228 preg_match_all($regex, $string, $areas);
229 if (! empty($count)) $area['area_anchor'] = $count;
231 if (isset($method['uri_anchor'])) {
233 preg_match_all($regex, $string, $areas, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
234 foreach(array_keys($areas) as $_area) {
235 $areas[$_area] = array(
236 $areas[$_area][0][1], // Area start (<a href>)
237 $areas[$_area][1][1], // Area end (</a>)
240 if (! empty($areas)) $area['uri_anchor'] = $areas;
243 // phpBB's "BBCode" pair by preg_match and preg_match_all()
245 // [OK] [url]http://nasty.example.com/[/url]
246 // [OK] [link]http://nasty.example.com/[/link]
247 // [OK] [url=http://nasty.example.com]visit http://nasty.example.com/[/url]
248 // [OK] [link http://nasty.example.com/]buy something[/link]
249 $regex = '#\[(url|link)\b[^\]]*\].*?\[/\1\b[^\]]*(\])#i';
250 if (isset($method['area_bbcode'])) {
252 $count = isset($method['asap']) ?
253 preg_match($regex, $string) :
254 preg_match_all($regex, $string, $areas, PREG_SET_ORDER);
255 if (! empty($count)) $area['area_bbcode'] = $count;
257 if (isset($method['uri_bbcode'])) {
259 preg_match_all($regex, $string, $areas, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
260 foreach(array_keys($areas) as $_area) {
261 $areas[$_area] = array(
262 $areas[$_area][0][1], // Area start ([url])
263 $areas[$_area][2][1], // Area end ([/url])
266 if (! empty($areas)) $area['uri_bbcode'] = $areas;
269 // Various Wiki syntax
270 // [text_or_uri>text_or_uri]
271 // [text_or_uri:text_or_uri]
272 // [text_or_uri|text_or_uri]
273 // [text_or_uri->text_or_uri]
274 // [text_or_uri text_or_uri] // MediaWiki
275 // MediaWiki: [http://nasty.example.com/ visit http://nasty.example.com/]
280 // If in doubt, it's a little doubtful
281 // if (Area => inside <= Area) $brief += -1
282 function area_measure($areas, & $array, $belief = -1, $a_key = 'area', $o_key = 'offset')
284 if (! is_array($areas) || ! is_array($array)) return;
286 $areas_keys = array_keys($areas);
287 foreach(array_keys($array) as $u_index) {
288 $offset = isset($array[$u_index][$o_key]) ?
289 intval($array[$u_index][$o_key]) : 0;
290 foreach($areas_keys as $a_index) {
291 if (isset($array[$u_index][$a_key])) {
292 $offset_s = intval($areas[$a_index][0]);
293 $offset_e = intval($areas[$a_index][1]);
294 // [Area => inside <= Area]
295 if ($offset_s < $offset && $offset < $offset_e) {
296 $array[$u_index][$a_key] += $belief;
303 // ---------------------
306 // Domain exposure callback (See spam_uri_pickup_preprocess())
307 // http://victim.example.org/?foo+site:nasty.example.com+bar
308 // => http://nasty.example.com/?refer=victim.example.org
309 // NOTE: 'refer=' is not so good for (at this time).
310 // Consider about using IP address of the victim, try to avoid that.
311 function _preg_replace_callback_domain_exposure($matches = array())
315 // Preserve the victim URI as a complicity or ...
316 if (isset($matches[5])) {
318 $matches[1] . '://' . // scheme
319 $matches[2] . '/' . // victim.example.org
320 $matches[3]; // The rest of all (before victim)
324 if (isset($matches[4])) {
326 $matches[1] . '://' . // scheme
327 $matches[4] . // nasty.example.com
328 '/?refer=' . strtolower($matches[2]) . // victim.example.org
335 // Preprocess: rawurldecode() and adding space(s) and something
336 // to detect/count some URIs _if possible_
337 // NOTE: It's maybe danger to var_dump(result). [e.g. 'javascript:']
338 // [OK] http://victim.example.org/go?http%3A%2F%2Fnasty.example.org
339 // [OK] http://victim.example.org/http://nasty.example.org
340 function spam_uri_pickup_preprocess($string = '')
342 if (! is_string($string)) return '';
344 $string = rawurldecode($string);
346 // Domain exposure (See _preg_replace_callback_domain_exposure())
347 $string = preg_replace_callback(
351 // Something Google: http://www.google.com/supported_domains
352 '(?:[a-z0-9.]+\.)?google\.[a-z]{2,3}(?:\.[a-z]{2})?' .
355 '(?:[a-z0-9.]+\.)?altavista.com' .
359 '([a-z0-9?=&.%_/\'\\\+-]+)' . // path/?query=foo+bar+
360 '\bsite:([a-z0-9.%_-]+\.[a-z0-9.%_-]+)' . // site:nasty.example.com
361 //'()' . // Preserve or remove?
364 '_preg_replace_callback_domain_exposure',
370 // URI exposure (uriuri => uri uri)
371 $string = preg_replace(
373 '#(?<! )(?:https?|ftp):/#i',
374 // '#[a-z][a-z0-9.+-]{1,8}://#i',
375 // '#[a-z][a-z0-9.+-]{1,8}://#i'
384 // Main function of spam-uri pickup
385 function spam_uri_pickup($string = '', $method = array())
387 if (! is_array($method) || empty($method)) {
388 $method = check_uri_spam_method();
391 $string = spam_uri_pickup_preprocess($string);
393 $array = uri_pickup($string);
395 // Area elevation of URIs, for '(especially external)link' intension
396 if (! empty($array)) {
398 if (isset($method['uri_anchor'])) $_method['uri_anchor'] = & $method['uri_anchor'];
399 if (isset($method['uri_bbcode'])) $_method['uri_bbcode'] = & $method['uri_bbcode'];
400 $areas = area_pickup($string, $_method, TRUE);
401 if (! empty($areas)) {
402 $area_shadow = array();
403 foreach (array_keys($array) as $key) {
404 $area_shadow[$key] = & $array[$key]['area'];
405 foreach (array_keys($_method) as $_key) {
406 $area_shadow[$key][$_key] = 0;
409 foreach (array_keys($_method) as $_key) {
410 if (isset($areas[$_key])) {
411 area_measure($areas[$_key], $area_shadow, 1, $_key);
417 // Remove 'offset's for area_measure()
418 foreach(array_keys($array) as $key)
419 unset($array[$key]['area']['offset']);
425 // ---------------------
428 // Scheme normalization: Renaming the schemes
429 // snntp://example.org => nntps://example.org
430 // NOTE: Keep the static lists simple. See also port_normalize().
431 function scheme_normalize($scheme = '', $considerd_harmfull = TRUE)
433 // Abbreviations considerable they don't have link intension
434 static $abbrevs = array(
439 // Alias => normalized
440 static $aliases = array(
450 $scheme = strtolower(trim($scheme));
451 if (isset($abbrevs[$scheme])) {
452 if ($considerd_harmfull) {
453 $scheme = $abbrevs[$scheme];
458 if (isset($aliases[$scheme])) $scheme = $aliases[$scheme];
463 // Port normalization: Suppress the (redundant) default port
464 // HTTP://example.org:80/ => http://example.org/
465 // HTTP://example.org:8080/ => http://example.org:8080/
466 // HTTPS://example.org:443/ => https://example.org/
467 function port_normalize($port, $scheme, $scheme_normalize = TRUE)
469 // Schemes that users _maybe_ want to add protocol-handlers
470 // to their web browsers. (and attackers _maybe_ want to use ...)
471 // Reference: http://www.iana.org/assignments/port-numbers
472 static $array = array(
473 // scheme => default port
500 if ($port === '') return $port;
502 if ($scheme_normalize) $scheme = scheme_normalize($scheme);
503 if (isset($array[$scheme]) && $port == $array[$scheme])
504 $port = ''; // Ignore the defaults
509 // Path normalization
510 // http://example.org => http://example.org/
511 // http://example.org#hoge => http://example.org/#hoge
512 // http://example.org/path/a/b/./c////./d => http://example.org/path/a/b/c/d
513 // http://example.org/path/../../a/../back => http://example.org/back
514 function path_normalize($path = '', $divider = '/', $addroot = TRUE)
516 if (! is_string($path) || $path == '')
517 return $addroot ? $divider : '';
520 $last = ($path[strlen($path) - 1] == $divider) ? $divider : '';
521 $array = explode($divider, $path);
524 foreach(array_keys($array) as $key) {
525 if ($array[$key] == '' || $array[$key] == '.')
530 foreach($array as $value) {
531 if ($value == '..') {
534 array_push($tmp, $value);
539 $path = $addroot ? $divider : '';
540 if (! empty($array)) $path .= implode($divider, $array) . $last;
545 // DirectoryIndex normalize (Destructive and rough)
546 function file_normalize($string = 'index.html.en')
548 static $array = array(
549 'index' => TRUE, // Some system can omit the suffix
551 'index.html' => TRUE,
552 'index.shtml' => TRUE,
555 'index.php3' => TRUE,
556 'index.php4' => TRUE,
557 //'index.pl' => TRUE,
558 //'index.py' => TRUE,
559 //'index.rb' => TRUE,
561 'default.htm' => TRUE,
562 'default.html' => TRUE,
563 'default.asp' => TRUE,
564 'default.aspx' => TRUE,
567 // Content-negothiation filter:
568 // Roughly removing ISO 639 -like
569 // 2-letter suffixes (See RFC3066)
571 if (preg_match('/(.*)\.[a-z][a-z](?:-[a-z][a-z])?$/i', $string, $matches)) {
572 $_string = $matches[1];
574 $_string = & $string;
577 if (isset($array[strtolower($_string)])) {
584 // Sort query-strings if possible (Destructive and rough)
585 // [OK] &&&&f=d&b&d&c&a=0dd => a=0dd&b&c&d&f=d
586 // [OK] nothing==&eg=dummy&eg=padding&eg=foobar => eg=foobar
587 function query_normalize($string = '', $equal = FALSE, $equal_cutempty = TRUE)
589 $array = explode('&', $string);
591 // Remove '&' paddings
592 foreach(array_keys($array) as $key) {
593 if ($array[$key] == '') {
598 // Consider '='-sepalated input and paddings
600 $equals = $not_equals = array();
601 foreach ($array as $part) {
602 if (strpos($part, '=') === FALSE) {
603 $not_equals[] = $part;
605 list($key, $value) = explode('=', $part, 2);
606 $value = ltrim($value, '=');
607 if (! $equal_cutempty || $value != '') {
608 $equals[$key] = $value;
613 $array = & $not_equals;
614 foreach ($equals as $key => $value) {
615 $array[] = $key . '=' . $value;
621 return implode('&', $array);
624 // ---------------------
625 // Part One : Checker
627 function generate_glob_regex($string = '', $divider = '/')
629 static $from = array(
632 // 22 => '[', // Maybe cause regex compilation error (e.g. '[]')
648 if (is_array($string)) {
652 array_map('generate_glob_regex',
654 array_pad(array(), count($string), $divider)
659 $string = str_replace($from, $mid, $string); // Hide
660 $string = preg_quote($string, $divider);
661 $string = str_replace($mid, $to, $string); // Unhide
666 function get_blocklist($list = '')
670 if (! isset($regexs)) {
672 if (file_exists(SPAM_INI_FILE)) {
673 $blocklist = array();
674 include(SPAM_INI_FILE);
675 // $blocklist['badhost'] = array(
676 // '*.blogspot.com', // Blog services's subdomains (only)
677 // 'IANA-examples' => '#^(?:.*\.)?example\.(?:com|net|org)$#',
679 foreach(array('goodhost', 'badhost') as $_list) {
680 if (! isset($blocklist[$list])) continue;
681 foreach ($blocklist[$_list] as $key => $value) {
682 if (is_string($key)) {
683 $regexs[$_list][$key] = $value;
685 $regexs[$_list][$value] =
686 '/^(?:www\.)?' . generate_glob_regex($value, '/') . '$/i';
694 return $regexs; // ALL
695 } else if (isset($regexs[$list])) {
696 return $regexs[$list];
702 function is_badhost($hosts = array(), $asap = TRUE, & $remains)
705 if (! is_array($hosts)) $hosts = array($hosts);
706 foreach(array_keys($hosts) as $key) {
707 if (! is_string($hosts[$key])) unset($hosts[$key]);
709 if (empty($hosts)) return $result;
711 foreach (get_blocklist('goodhost') as $regex) {
712 $hosts = preg_grep_invert($regex, $hosts);
714 if (empty($hosts)) return $result;
717 foreach (get_blocklist('badhost') as $label => $regex) {
718 $result[$label] = preg_grep($regex, $hosts);
719 if (empty($result[$label])) {
720 unset($result[$label]);
722 $hosts = array_diff($hosts, $result[$label]);
732 // Default (enabled) methods and thresholds (for content insertion)
733 function check_uri_spam_method($times = 1, $t_area = 0, $rule = TRUE)
735 $times = intval($times);
736 $t_area = intval($t_area);
740 'quantity' => 8 * $times, // Allow N URIs
741 'non_uniqhost' => 3 * $times, // Allow N duped (and normalized) Hosts
742 //'non_uniquri'=> 3 * $times, // Allow N duped (and normalized) URIs
745 'area_anchor' => $t_area, // Using <a href> HTML tag
746 'area_bbcode' => $t_area, // Using [url] or [link] BBCode
747 //'uri_anchor' => $t_area, // URI inside <a href> HTML tag
748 //'uri_bbcode' => $t_area, // URI inside [url] or [link] BBCode
753 //'asap' => TRUE, // Quit or return As Soon As Possible
754 'uniqhost' => TRUE, // Show uniq host (at block notification mail)
755 'badhost' => TRUE, // Check badhost
761 // Remove non-$positive values
762 foreach (array_keys($positive) as $key) {
763 if ($positive[$key] < 0) unset($positive[$key]);
766 return $positive + $bool;
769 // Simple/fast spam check
770 function check_uri_spam($target = '', $method = array())
772 if (! is_array($method) || empty($method)) {
773 $method = check_uri_spam_method();
787 'is_spam' => array(),
788 'method' => & $method,
789 'remains' => array(),
791 $sum = & $progress['sum'];
792 $is_spam = & $progress['is_spam'];
793 $remains = & $progress['remains'];
794 $asap = isset($method['asap']);
797 if (is_array($target)) {
798 foreach($target as $str) {
800 $_progress = check_uri_spam($str, $method);
801 $_sum = & $_progress['sum'];
802 $_is_spam = & $_progress['is_spam'];
803 $_remains = & $_progress['remains'];
804 foreach (array_keys($_sum) as $key) {
805 $sum[$key] += $_sum[$key];
807 foreach (array_keys($_is_spam) as $key) {
808 if (is_array($_is_spam[$key])) {
809 // Marge keys (badhost)
810 foreach(array_keys($_is_spam[$key]) as $_key) {
811 if (! isset($is_spam[$key][$_key])) {
812 $is_spam[$key][$_key] = $_is_spam[$key][$_key];
814 $is_spam[$key][$_key] += $_is_spam[$key][$_key];
818 $is_spam[$key] = TRUE;
821 foreach ($_remains as $key=>$value) {
822 foreach ($value as $_key=>$_value) {
824 $remains[$key][] = $_value;
826 $remains[$key][$_key] = $_value;
830 if ($asap && $is_spam) break;
835 // Area: There's HTML anchor tag
836 if ((! $asap || ! $is_spam) && isset($method['area_anchor'])) {
837 $key = 'area_anchor';
838 $_asap = isset($method['asap']) ? array('asap' => TRUE) : array();
839 $result = area_pickup($target, array($key => TRUE) + $_asap);
841 $sum[$key] = $result[$key];
842 if (isset($method[$key]) && $sum[$key] > $method[$key]) {
843 $is_spam[$key] = TRUE;
848 // Area: There's 'BBCode' linking tag
849 if ((! $asap || ! $is_spam) && isset($method['area_bbcode'])) {
850 $key = 'area_bbcode';
851 $_asap = isset($method['asap']) ? array('asap' => TRUE) : array();
852 $result = area_pickup($target, array($key => TRUE) + $_asap);
854 $sum[$key] = $result[$key];
855 if (isset($method[$key]) && $sum[$key] > $method[$key]) {
856 $is_spam[$key] = TRUE;
862 if ($asap && $is_spam) return $progress;
865 $pickups = spam_uri_pickup($target, $method);
866 //$remains['uri_pickup'] = & $pickups;
869 if (empty($pickups)) return $progress;
871 // URI: Check quantity
872 $sum['quantity'] += count($pickups);
874 if ((! $asap || ! $is_spam) && isset($method['quantity']) &&
875 $sum['quantity'] > $method['quantity']) {
876 $is_spam['quantity'] = TRUE;
879 // URI: used inside HTML anchor tag pair
880 if ((! $asap || ! $is_spam) && isset($method['uri_anchor'])) {
882 foreach($pickups as $pickup) {
883 if (isset($pickup['area'][$key])) {
884 $sum[$key] += $pickup['area'][$key];
885 if(isset($method[$key]) &&
886 $sum[$key] > $method[$key]) {
887 $is_spam[$key] = TRUE;
888 if ($asap && $is_spam) break;
890 if ($asap && $is_spam) break;
895 // URI: used inside 'BBCode' pair
896 if ((! $asap || ! $is_spam) && isset($method['uri_bbcode'])) {
898 foreach($pickups as $pickup) {
899 if (isset($pickup['area'][$key])) {
900 $sum[$key] += $pickup['area'][$key];
901 if(isset($method[$key]) &&
902 $sum[$key] > $method[$key]) {
903 $is_spam[$key] = TRUE;
904 if ($asap && $is_spam) break;
906 if ($asap && $is_spam) break;
911 // URI: Uniqueness (and removing non-uniques)
912 if ((! $asap || ! $is_spam) && isset($method['non_uniquri'])) {
914 // Destructive normalize of URIs
915 uri_array_normalize($pickups);
918 foreach (array_keys($pickups) as $key) {
919 $uris[$key] = uri_array_implode($pickups[$key]);
921 $count = count($uris);
922 $uris = array_unique($uris);
923 $sum['non_uniquri'] += $count - count($uris);
924 if ($sum['non_uniquri'] > $method['non_uniquri']) {
925 $is_spam['non_uniquri'] = TRUE;
927 if (! $asap || ! $is_spam) {
928 foreach (array_diff(array_keys($pickups),
929 array_keys($uris)) as $remove) {
930 unset($pickups[$remove]);
937 if ($asap && $is_spam) return $progress;
939 // Host: Uniqueness (uniq / non-uniq)
941 foreach ($pickups as $pickup) $hosts[] = & $pickup['host'];
942 $hosts = array_unique($hosts);
943 //$remains['uniqhost'] = & $hosts;
944 $sum['uniqhost'] += count($hosts);
945 if ((! $asap || ! $is_spam) && isset($method['non_uniqhost'])) {
946 $sum['non_uniqhost'] = $sum['quantity'] - $sum['uniqhost'];
947 if ($sum['non_uniqhost'] > $method['non_uniqhost']) {
948 $is_spam['non_uniqhost'] = TRUE;
953 if ($asap && $is_spam) return $progress;
956 if ((! $asap || ! $is_spam) && isset($method['badhost'])) {
957 $__remains = array();
959 $badhost = is_badhost($hosts, $asap, $__remains);
961 $badhost = is_badhost($hosts, $asap, $__remains);
963 $remains['badhost'] = array();
964 foreach ($__remains as $value) {
965 $remains['badhost'][$value] = TRUE;
970 if (! empty($badhost)) {
971 $sum['badhost'] += array_count_leaves($badhost);
972 foreach(array_keys($badhost) as $keys) {
973 $is_spam['badhost'][$keys] =
974 array_count_leaves($badhost[$keys]);
984 function array_count_leaves($array = array(), $count_empty_array = FALSE)
986 if (! is_array($array) || (empty($array) && $count_empty_array))
991 foreach ($array as $part) {
992 $result += array_count_leaves($part, $count_empty_array);
997 // ---------------------
1000 // TODO: Don't show unused $method!
1001 // Summarize $progress (blocked only)
1002 function summarize_spam_progress($progress = array(), $blockedonly = FALSE)
1005 $tmp = array_keys($progress['is_spam']);
1008 $method = & $progress['method'];
1009 if (isset($progress['sum'])) {
1010 foreach ($progress['sum'] as $key => $value) {
1011 if (isset($method[$key])) {
1012 $tmp[] = $key . '(' . $value . ')';
1018 return implode(', ', $tmp);
1021 // ---------------------
1024 // Common bahavior for blocking
1025 // NOTE: Call this function from various blocking feature, to disgueise the reason 'why blocked'
1026 function spam_exit($mode = '', $data = array())
1029 case '': echo("\n"); break;
1031 echo('<pre>' . "\n");
1032 echo htmlspecialchars(var_export($data, TRUE));
1033 echo('</pre>' . "\n");
1042 // ---------------------
1045 // TODO: Record them
1046 // Simple/fast spam filter ($target: 'a string' or an array())
1047 function pkwk_spamfilter($action, $page, $target = array('title' => ''), $method = array(), $exitmode = '')
1049 $progress = check_uri_spam($target, $method);
1051 if (! empty($progress['is_spam'])) {
1052 // Mail to administrator(s)
1053 pkwk_spamnotify($action, $page, $target, $progress, $method);
1056 spam_exit($exitmode, $progress);
1060 // ---------------------
1061 // PukiWiki original
1063 // Mail to administrator(s)
1064 function pkwk_spamnotify($action, $page, $target = array('title' => ''), $progress = array(), $method = array())
1066 global $notify, $notify_subject;
1068 if (! $notify) return;
1070 $asap = isset($method['asap']);
1072 $summary['ACTION'] = 'Blocked by: ' . summarize_spam_progress($progress, TRUE);
1074 $summary['METRICS'] = summarize_spam_progress($progress);
1076 if (isset($progress['is_spam']['badhost'])) {
1078 foreach($progress['is_spam']['badhost'] as $glob=>$number) {
1079 $badhost[] = $glob . '(' . $number . ')';
1081 $summary['DETAIL_BADHOST'] = implode(', ', $badhost);
1083 if (! $asap && $progress['remains']['badhost']) {
1084 $count = count($progress['remains']['badhost']);
1085 $summary['DETAIL_NEUTRAL_HOST'] = $count .
1088 '/[^, a-z0-9.-]/i', '',
1089 implode(', ', array_keys($progress['remains']['badhost']))
1093 $summary['COMMENT'] = $action;
1094 $summary['PAGE'] = '[blocked] ' . (is_pagename($page) ? $page : '');
1095 $summary['URI'] = get_script_uri() . '?' . rawurlencode($page);
1096 $summary['USER_AGENT'] = TRUE;
1097 $summary['REMOTE_ADDR'] = TRUE;
1098 pkwk_mail_notify($notify_subject, var_export($target, TRUE), $summary, TRUE);