2 // $Id: spam.php,v 1.121 2007/03/04 03:54:55 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'] = strtolower($_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 // Port normalization: Suppress the (redundant) default port
465 // HTTP://example.org:80/ => http://example.org/
466 // HTTP://example.org:8080/ => http://example.org:8080/
467 // HTTPS://example.org:443/ => https://example.org/
468 function port_normalize($port, $scheme, $scheme_normalize = TRUE)
470 // Schemes that users _maybe_ want to add protocol-handlers
471 // to their web browsers. (and attackers _maybe_ want to use ...)
472 // Reference: http://www.iana.org/assignments/port-numbers
473 static $array = array(
474 // scheme => default port
501 if ($port === '') return $port;
503 if ($scheme_normalize) $scheme = scheme_normalize($scheme);
504 if (isset($array[$scheme]) && $port == $array[$scheme])
505 $port = ''; // Ignore the defaults
510 // Path normalization
511 // http://example.org => http://example.org/
512 // http://example.org#hoge => http://example.org/#hoge
513 // http://example.org/path/a/b/./c////./d => http://example.org/path/a/b/c/d
514 // http://example.org/path/../../a/../back => http://example.org/back
515 function path_normalize($path = '', $divider = '/', $addroot = TRUE)
517 if (! is_string($path) || $path == '')
518 return $addroot ? $divider : '';
521 $last = ($path[strlen($path) - 1] == $divider) ? $divider : '';
522 $array = explode($divider, $path);
525 foreach(array_keys($array) as $key) {
526 if ($array[$key] == '' || $array[$key] == '.')
531 foreach($array as $value) {
532 if ($value == '..') {
535 array_push($tmp, $value);
540 $path = $addroot ? $divider : '';
541 if (! empty($array)) $path .= implode($divider, $array) . $last;
546 // DirectoryIndex normalize (Destructive and rough)
547 function file_normalize($string = 'index.html.en')
549 static $array = array(
550 'index' => TRUE, // Some system can omit the suffix
552 'index.html' => TRUE,
553 'index.shtml' => TRUE,
556 'index.php3' => TRUE,
557 'index.php4' => TRUE,
558 //'index.pl' => TRUE,
559 //'index.py' => TRUE,
560 //'index.rb' => TRUE,
562 'default.htm' => TRUE,
563 'default.html' => TRUE,
564 'default.asp' => TRUE,
565 'default.aspx' => TRUE,
568 // Content-negothiation filter:
569 // Roughly removing ISO 639 -like
570 // 2-letter suffixes (See RFC3066)
572 if (preg_match('/(.*)\.[a-z][a-z](?:-[a-z][a-z])?$/i', $string, $matches)) {
573 $_string = $matches[1];
575 $_string = & $string;
578 if (isset($array[strtolower($_string)])) {
585 // Sort query-strings if possible (Destructive and rough)
586 // [OK] &&&&f=d&b&d&c&a=0dd => a=0dd&b&c&d&f=d
587 // [OK] nothing==&eg=dummy&eg=padding&eg=foobar => eg=foobar
588 function query_normalize($string = '', $equal = FALSE, $equal_cutempty = TRUE)
590 $array = explode('&', $string);
592 // Remove '&' paddings
593 foreach(array_keys($array) as $key) {
594 if ($array[$key] == '') {
599 // Consider '='-sepalated input and paddings
601 $equals = $not_equals = array();
602 foreach ($array as $part) {
603 if (strpos($part, '=') === FALSE) {
604 $not_equals[] = $part;
606 list($key, $value) = explode('=', $part, 2);
607 $value = ltrim($value, '=');
608 if (! $equal_cutempty || $value != '') {
609 $equals[$key] = $value;
614 $array = & $not_equals;
615 foreach ($equals as $key => $value) {
616 $array[] = $key . '=' . $value;
622 return implode('&', $array);
625 // ---------------------
626 // Part One : Checker
628 function generate_glob_regex($string = '', $divider = '/')
630 static $from = array(
633 // 22 => '[', // Maybe cause regex compilation error (e.g. '[]')
649 if (is_array($string)) {
653 array_map('generate_glob_regex',
655 array_pad(array(), count($string), $divider)
660 $string = str_replace($from, $mid, $string); // Hide
661 $string = preg_quote($string, $divider);
662 $string = str_replace($mid, $to, $string); // Unhide
667 function get_blocklist($list = '')
671 if (! isset($regexs)) {
673 if (file_exists(SPAM_INI_FILE)) {
674 $blocklist = array();
675 include(SPAM_INI_FILE);
676 // $blocklist['badhost'] = array(
677 // '*.blogspot.com', // Blog services's subdomains (only)
678 // 'IANA-examples' => '#^(?:.*\.)?example\.(?:com|net|org)$#',
680 foreach(array('goodhost', 'badhost') as $_list) {
681 if (! isset($blocklist[$list])) continue;
682 foreach ($blocklist[$_list] as $key => $value) {
683 if (is_string($key)) {
684 $regexs[$_list][$key] = $value;
686 $regexs[$_list][$value] =
687 '/^(?:www\.)?' . generate_glob_regex($value, '/') . '$/i';
695 return $regexs; // ALL
696 } else if (isset($regexs[$list])) {
697 return $regexs[$list];
703 function is_badhost($hosts = array(), $asap = TRUE, & $remains)
706 if (! is_array($hosts)) $hosts = array($hosts);
707 foreach(array_keys($hosts) as $key) {
708 if (! is_string($hosts[$key])) unset($hosts[$key]);
710 if (empty($hosts)) return $result;
712 foreach (get_blocklist('goodhost') as $regex) {
713 $hosts = preg_grep_invert($regex, $hosts);
715 if (empty($hosts)) return $result;
718 foreach (get_blocklist('badhost') as $label => $regex) {
719 $result[$label] = preg_grep($regex, $hosts);
720 if (empty($result[$label])) {
721 unset($result[$label]);
723 $hosts = array_diff($hosts, $result[$label]);
733 // Default (enabled) methods and thresholds (for content insertion)
734 function check_uri_spam_method($times = 1, $t_area = 0, $rule = TRUE)
736 $times = intval($times);
737 $t_area = intval($t_area);
741 'quantity' => 8 * $times, // Allow N URIs
742 'non_uniqhost' => 3 * $times, // Allow N duped (and normalized) Hosts
743 //'non_uniquri'=> 3 * $times, // Allow N duped (and normalized) URIs
746 'area_anchor' => $t_area, // Using <a href> HTML tag
747 'area_bbcode' => $t_area, // Using [url] or [link] BBCode
748 //'uri_anchor' => $t_area, // URI inside <a href> HTML tag
749 //'uri_bbcode' => $t_area, // URI inside [url] or [link] BBCode
754 //'asap' => TRUE, // Quit or return As Soon As Possible
755 'uniqhost' => TRUE, // Show uniq host (at block notification mail)
756 'badhost' => TRUE, // Check badhost
762 // Remove non-$positive values
763 foreach (array_keys($positive) as $key) {
764 if ($positive[$key] < 0) unset($positive[$key]);
767 return $positive + $bool;
770 // Simple/fast spam check
771 function check_uri_spam($target = '', $method = array())
773 if (! is_array($method) || empty($method)) {
774 $method = check_uri_spam_method();
788 'is_spam' => array(),
789 'method' => & $method,
790 'remains' => array(),
792 $sum = & $progress['sum'];
793 $is_spam = & $progress['is_spam'];
794 $remains = & $progress['remains'];
795 $asap = isset($method['asap']);
798 if (is_array($target)) {
799 foreach($target as $str) {
801 $_progress = check_uri_spam($str, $method);
802 $_sum = & $_progress['sum'];
803 $_is_spam = & $_progress['is_spam'];
804 $_remains = & $_progress['remains'];
805 foreach (array_keys($_sum) as $key) {
806 $sum[$key] += $_sum[$key];
808 foreach (array_keys($_is_spam) as $key) {
809 if (is_array($_is_spam[$key])) {
810 // Marge keys (badhost)
811 foreach(array_keys($_is_spam[$key]) as $_key) {
812 if (! isset($is_spam[$key][$_key])) {
813 $is_spam[$key][$_key] = $_is_spam[$key][$_key];
815 $is_spam[$key][$_key] += $_is_spam[$key][$_key];
819 $is_spam[$key] = TRUE;
822 foreach ($_remains as $key=>$value) {
823 foreach ($value as $_key=>$_value) {
825 $remains[$key][] = $_value;
827 $remains[$key][$_key] = $_value;
831 if ($asap && $is_spam) break;
836 // Area: There's HTML anchor tag
837 if ((! $asap || ! $is_spam) && isset($method['area_anchor'])) {
838 $key = 'area_anchor';
839 $_asap = isset($method['asap']) ? array('asap' => TRUE) : array();
840 $result = area_pickup($target, array($key => TRUE) + $_asap);
842 $sum[$key] = $result[$key];
843 if (isset($method[$key]) && $sum[$key] > $method[$key]) {
844 $is_spam[$key] = TRUE;
849 // Area: There's 'BBCode' linking tag
850 if ((! $asap || ! $is_spam) && isset($method['area_bbcode'])) {
851 $key = 'area_bbcode';
852 $_asap = isset($method['asap']) ? array('asap' => TRUE) : array();
853 $result = area_pickup($target, array($key => TRUE) + $_asap);
855 $sum[$key] = $result[$key];
856 if (isset($method[$key]) && $sum[$key] > $method[$key]) {
857 $is_spam[$key] = TRUE;
863 if ($asap && $is_spam) return $progress;
866 $pickups = spam_uri_pickup($target, $method);
867 //$remains['uri_pickup'] = & $pickups;
870 if (empty($pickups)) return $progress;
872 // URI: Check quantity
873 $sum['quantity'] += count($pickups);
875 if ((! $asap || ! $is_spam) && isset($method['quantity']) &&
876 $sum['quantity'] > $method['quantity']) {
877 $is_spam['quantity'] = TRUE;
880 // URI: used inside HTML anchor tag pair
881 if ((! $asap || ! $is_spam) && isset($method['uri_anchor'])) {
883 foreach($pickups as $pickup) {
884 if (isset($pickup['area'][$key])) {
885 $sum[$key] += $pickup['area'][$key];
886 if(isset($method[$key]) &&
887 $sum[$key] > $method[$key]) {
888 $is_spam[$key] = TRUE;
889 if ($asap && $is_spam) break;
891 if ($asap && $is_spam) break;
896 // URI: used inside 'BBCode' pair
897 if ((! $asap || ! $is_spam) && isset($method['uri_bbcode'])) {
899 foreach($pickups as $pickup) {
900 if (isset($pickup['area'][$key])) {
901 $sum[$key] += $pickup['area'][$key];
902 if(isset($method[$key]) &&
903 $sum[$key] > $method[$key]) {
904 $is_spam[$key] = TRUE;
905 if ($asap && $is_spam) break;
907 if ($asap && $is_spam) break;
912 // URI: Uniqueness (and removing non-uniques)
913 if ((! $asap || ! $is_spam) && isset($method['non_uniquri'])) {
915 // Destructive normalize of URIs
916 uri_array_normalize($pickups);
919 foreach (array_keys($pickups) as $key) {
920 $uris[$key] = uri_array_implode($pickups[$key]);
922 $count = count($uris);
923 $uris = array_unique($uris);
924 $sum['non_uniquri'] += $count - count($uris);
925 if ($sum['non_uniquri'] > $method['non_uniquri']) {
926 $is_spam['non_uniquri'] = TRUE;
928 if (! $asap || ! $is_spam) {
929 foreach (array_diff(array_keys($pickups),
930 array_keys($uris)) as $remove) {
931 unset($pickups[$remove]);
938 if ($asap && $is_spam) return $progress;
940 // Host: Uniqueness (uniq / non-uniq)
942 foreach ($pickups as $pickup) $hosts[] = & $pickup['host'];
943 $hosts = array_unique($hosts);
944 //$remains['uniqhost'] = & $hosts;
945 $sum['uniqhost'] += count($hosts);
946 if ((! $asap || ! $is_spam) && isset($method['non_uniqhost'])) {
947 $sum['non_uniqhost'] = $sum['quantity'] - $sum['uniqhost'];
948 if ($sum['non_uniqhost'] > $method['non_uniqhost']) {
949 $is_spam['non_uniqhost'] = TRUE;
954 if ($asap && $is_spam) return $progress;
957 if ((! $asap || ! $is_spam) && isset($method['badhost'])) {
958 $__remains = array();
960 $badhost = is_badhost($hosts, $asap, $__remains);
962 $badhost = is_badhost($hosts, $asap, $__remains);
964 $remains['badhost'] = array();
965 foreach ($__remains as $value) {
966 $remains['badhost'][$value] = TRUE;
971 if (! empty($badhost)) {
972 $sum['badhost'] += array_count_leaves($badhost);
973 foreach(array_keys($badhost) as $keys) {
974 $is_spam['badhost'][$keys] =
975 array_count_leaves($badhost[$keys]);
985 function array_count_leaves($array = array(), $count_empty_array = FALSE)
987 if (! is_array($array) || (empty($array) && $count_empty_array))
992 foreach ($array as $part) {
993 $result += array_count_leaves($part, $count_empty_array);
998 // ---------------------
1001 // TODO: Don't show unused $method!
1002 // Summarize $progress (blocked only)
1003 function summarize_spam_progress($progress = array(), $blockedonly = FALSE)
1006 $tmp = array_keys($progress['is_spam']);
1009 $method = & $progress['method'];
1010 if (isset($progress['sum'])) {
1011 foreach ($progress['sum'] as $key => $value) {
1012 if (isset($method[$key])) {
1013 $tmp[] = $key . '(' . $value . ')';
1019 return implode(', ', $tmp);
1022 // ---------------------
1025 // Common bahavior for blocking
1026 // NOTE: Call this function from various blocking feature, to disgueise the reason 'why blocked'
1027 function spam_exit($mode = '', $data = array())
1030 case '': echo("\n"); break;
1032 echo('<pre>' . "\n");
1033 echo htmlspecialchars(var_export($data, TRUE));
1034 echo('</pre>' . "\n");
1043 // ---------------------
1046 // TODO: Record them
1047 // Simple/fast spam filter ($target: 'a string' or an array())
1048 function pkwk_spamfilter($action, $page, $target = array('title' => ''), $method = array(), $exitmode = '')
1050 $progress = check_uri_spam($target, $method);
1052 if (! empty($progress['is_spam'])) {
1053 // Mail to administrator(s)
1054 pkwk_spamnotify($action, $page, $target, $progress, $method);
1057 spam_exit($exitmode, $progress);
1061 // ---------------------
1062 // PukiWiki original
1064 // Mail to administrator(s)
1065 function pkwk_spamnotify($action, $page, $target = array('title' => ''), $progress = array(), $method = array())
1067 global $notify, $notify_subject;
1069 if (! $notify) return;
1071 $asap = isset($method['asap']);
1073 $summary['ACTION'] = 'Blocked by: ' . summarize_spam_progress($progress, TRUE);
1075 $summary['METRICS'] = summarize_spam_progress($progress);
1077 if (isset($progress['is_spam']['badhost'])) {
1079 foreach($progress['is_spam']['badhost'] as $glob=>$number) {
1080 $badhost[] = $glob . '(' . $number . ')';
1082 $summary['DETAIL_BADHOST'] = implode(', ', $badhost);
1084 if (! $asap && $progress['remains']['badhost']) {
1085 $count = count($progress['remains']['badhost']);
1086 $summary['DETAIL_NEUTRAL_HOST'] = $count .
1089 '/[^, a-z0-9.-]/i', '',
1090 implode(', ', array_keys($progress['remains']['badhost']))
1094 $summary['COMMENT'] = $action;
1095 $summary['PAGE'] = '[blocked] ' . (is_pagename($page) ? $page : '');
1096 $summary['URI'] = get_script_uri() . '?' . rawurlencode($page);
1097 $summary['USER_AGENT'] = TRUE;
1098 $summary['REMOTE_ADDR'] = TRUE;
1099 pkwk_mail_notify($notify_subject, var_export($target, TRUE), $summary, TRUE);