2 // $Id: spam.php,v 1.93 2007/01/03 08:06:58 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
7 // (PHP 4 >= 4.3.0): preg_match_all(PREG_OFFSET_CAPTURE): $method['uri_XXX'] related feature
9 if (! defined('SPAM_INI_FILE')) define('SPAM_INI_FILE', 'spam.ini.php');
11 // ---------------------
14 // (PHP 4 >= 4.2.0): var_export(): mail-reporting and dump related
15 if (! function_exists('var_export')) {
16 function var_export() {
17 return 'var_export() is not found' . "\n";
21 // (PHP 4 >= 4.2.0): preg_grep() enabels invert option
22 function preg_grep_invert($pattern = '//', $input = array())
25 if (! isset($invert)) $invert = defined('PREG_GREP_INVERT');
28 return preg_grep($pattern, $input, PREG_GREP_INVERT);
30 return array_diff($input, preg_grep($pattern, $input));
34 // ---------------------
37 // Return an array of URIs in the $string
38 // [OK] http://nasty.example.org#nasty_string
39 // [OK] http://nasty.example.org:80/foo/xxx#nasty_string/bar
40 // [OK] ftp://nasty.example.org:80/dfsdfs
41 // [OK] ftp://cnn.example.com&story=breaking_news@10.0.0.1/top_story.htm (from RFC3986)
42 function uri_pickup($string = '', $normalize = TRUE,
43 $preserve_rawuri = FALSE, $preserve_chunk = TRUE)
45 // Not available for: IDN(ignored)
48 // scheme://userinfo@host:port/path/or/pathinfo/maybefile.and?query=string#fragment
49 // Refer RFC3986 (Regex below is not strict)
50 '#(\b[a-z][a-z0-9.+-]{1,8})://' . // 1: Scheme
52 '([^\s<>"\'\[\]/\#?@]*)' . // 2: Userinfo (Username)
56 '\[[0-9a-f:.]+\]' . '|' . // IPv6([colon-hex and dot]): RFC2732
57 '(?:[0-9]{1-3}\.){3}[0-9]{1-3}' . '|' . // IPv4(dot-decimal): 001.22.3.44
58 '[^\s<>"\'\[\]:/\#?&\\\]+' . // FQDN: foo.example.org
60 '(?::([0-9]*))?' . // 4: Port
61 '((?:/+[^\s<>"\'\[\]/\#]+)*/+)?' . // 5: Directory path or path-info
62 '([^\s<>"\'\[\]\#?]+)?' . // 6: File?
63 '(?:\?([^\s<>"\'\[\]\#]+))?' . // 7: Query string
64 '(?:\#([a-z0-9._~%!$&\'()*+,;=:@-]*))?' . // 8: Fragment
66 $string, $array, PREG_SET_ORDER | PREG_OFFSET_CAPTURE
70 static $parts = array(
71 1 => 'scheme', 2 => 'userinfo', 3 => 'host', 4 => 'port',
72 5 => 'path', 6 => 'file', 7 => 'query', 8 => 'fragment'
75 foreach(array_keys($array) as $uri) {
76 $_uri = & $array[$uri];
77 array_rename_keys($_uri, $parts, TRUE, $default);
79 $offset = $_uri['scheme'][1]; // Scheme's offset
80 foreach(array_keys($_uri) as $part) {
81 // Remove offsets for each part
82 $_uri[$part] = & $_uri[$part][0];
86 $_uri['scheme'] = scheme_normalize($_uri['scheme']);
87 if ($_uri['scheme'] === '') {
91 $_uri['host'] = strtolower($_uri['host']);
92 $_uri['port'] = port_normalize($_uri['port'], $_uri['scheme'], FALSE);
93 $_uri['path'] = path_normalize($_uri['path']);
94 if ($preserve_rawuri) $_uri['rawuri'] = & $_uri[0];
97 //$_uri['uri'] = uri_array_implode($_uri);
99 $_uri['uri'] = & $_uri[0]; // Raw
101 unset($_uri[0]); // Matched string itself
102 if (! $preserve_chunk) {
115 // Area offset for area_measure()
116 $_uri['area']['offset'] = $offset;
122 // Destructive normalize of URI array
123 // NOTE: Give me the uri_pickup() result with chunks
124 function uri_array_normalize(& $pickups, $preserve = TRUE)
126 if (! is_array($pickups)) return $pickups;
128 foreach (array_keys($pickups) as $key) {
129 $_key = & $pickups[$key];
130 $_key['path'] = isset($_key['path']) ? strtolower($_key['path']) : '';
131 $_key['file'] = isset($_key['file']) ? file_normalize($_key['file']) : '';
132 $_key['query'] = isset($_key['query']) ? query_normalize(strtolower($_key['query']), TRUE) : '';
133 $_key['fragment'] = (isset($_key['fragment']) && $preserve) ?
134 strtolower($_key['fragment']) : ''; // Just ignore
140 // An URI array => An URI (See uri_pickup())
141 function uri_array_implode($uri = array())
143 if (empty($uri) || ! is_array($uri)) return NULL;
146 if (isset($uri['scheme']) && $uri['scheme'] !== '') {
147 $tmp[] = & $uri['scheme'];
150 if (isset($uri['userinfo']) && $uri['userinfo'] !== '') {
151 $tmp[] = & $uri['userinfo'];
154 if (isset($uri['host']) && $uri['host'] !== '') {
155 $tmp[] = & $uri['host'];
157 if (isset($uri['port']) && $uri['port'] !== '') {
159 $tmp[] = & $uri['port'];
161 if (isset($uri['path']) && $uri['path'] !== '') {
162 $tmp[] = & $uri['path'];
164 if (isset($uri['file']) && $uri['file'] !== '') {
165 $tmp[] = & $uri['file'];
167 if (isset($uri['query']) && $uri['query'] !== '') {
169 $tmp[] = & $uri['query'];
171 if (isset($uri['fragment']) && $uri['fragment'] !== '') {
173 $tmp[] = & $uri['fragment'];
176 return implode('', $tmp);
179 // $array['something'] => $array['wanted']
180 function array_rename_keys(& $array, $keys = array('from' => 'to'), $force = FALSE, $default = '')
182 if (! is_array($array) || ! is_array($keys)) return FALSE;
184 // Nondestructive test
186 foreach(array_keys($keys) as $from)
187 if (! isset($array[$from]))
190 foreach($keys as $from => $to) {
191 if ($from === $to) continue;
192 if (! $force || isset($array[$from])) {
193 $array[$to] = & $array[$from];
194 unset($array[$from]);
196 $array[$to] = $default;
203 // ---------------------
206 // Pickup all of markup areas
207 function area_pickup($string = '', $method = array())
210 if (empty($method)) return $area;
212 // Anchor tag pair by preg_match and preg_match_all()
214 // [OK] <a href= >Good site!</a>
215 // [OK] <a href= "#" >test</a>
216 // [OK] <a href="http://nasty.example.com">visit http://nasty.example.com/</a>
217 // [OK] <a href=\'http://nasty.example.com/\' >discount foobar</a>
218 // [NG] <a href="http://ng.example.com">visit http://ng.example.com _not_ended_
219 $regex = '#<a\b[^>]*\bhref\b[^>]*>.*?</a\b[^>]*(>)#i';
220 if (isset($method['area_anchor'])) {
222 $count = isset($method['asap']) ?
223 preg_match($regex, $string) :
224 preg_match_all($regex, $string, $areas);
225 if (! empty($count)) $area['area_anchor'] = $count;
227 if (isset($method['uri_anchor'])) {
229 preg_match_all($regex, $string, $areas, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
230 foreach(array_keys($areas) as $_area) {
231 $areas[$_area] = array(
232 $areas[$_area][0][1], // Area start (<a href>)
233 $areas[$_area][1][1], // Area end (</a>)
236 if (! empty($areas)) $area['uri_anchor'] = $areas;
239 // phpBB's "BBCode" pair by preg_match and preg_match_all()
241 // [OK] [url]http://nasty.example.com/[/url]
242 // [OK] [link]http://nasty.example.com/[/link]
243 // [OK] [url=http://nasty.example.com]visit http://nasty.example.com/[/url]
244 // [OK] [link http://nasty.example.com/]buy something[/link]
245 $regex = '#\[(url|link)\b[^\]]*\].*?\[/\1\b[^\]]*(\])#i';
246 if (isset($method['area_bbcode'])) {
248 $count = isset($method['asap']) ?
249 preg_match($regex, $string) :
250 preg_match_all($regex, $string, $areas, PREG_SET_ORDER);
251 if (! empty($count)) $area['area_bbcode'] = $count;
253 if (isset($method['uri_bbcode'])) {
255 preg_match_all($regex, $string, $areas, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
256 foreach(array_keys($areas) as $_area) {
257 $areas[$_area] = array(
258 $areas[$_area][0][1], // Area start ([url])
259 $areas[$_area][2][1], // Area end ([/url])
262 if (! empty($areas)) $area['uri_bbcode'] = $areas;
265 // Various Wiki syntax
266 // [text_or_uri>text_or_uri]
267 // [text_or_uri:text_or_uri]
268 // [text_or_uri|text_or_uri]
269 // [text_or_uri->text_or_uri]
270 // [text_or_uri text_or_uri] // MediaWiki
271 // MediaWiki: [http://nasty.example.com/ visit http://nasty.example.com/]
276 // If in doubt, it's a little doubtful
277 // if (Area => inside <= Area) $brief += -1
278 function area_measure($areas, & $array, $belief = -1, $a_key = 'area', $o_key = 'offset')
280 if (! is_array($areas) || ! is_array($array)) return;
282 $areas_keys = array_keys($areas);
283 foreach(array_keys($array) as $u_index) {
284 $offset = isset($array[$u_index][$o_key]) ?
285 intval($array[$u_index][$o_key]) : 0;
286 foreach($areas_keys as $a_index) {
287 if (isset($array[$u_index][$a_key])) {
288 $offset_s = intval($areas[$a_index][0]);
289 $offset_e = intval($areas[$a_index][1]);
290 // [Area => inside <= Area]
291 if ($offset_s < $offset && $offset < $offset_e) {
292 $array[$u_index][$a_key] += $belief;
299 // ---------------------
302 // Domain exposure callback (See spam_uri_pickup_preprocess())
303 // http://victim.example.org/?foo+site:nasty.example.com+bar
304 // => http://nasty.example.com/?refer=victim.example.org
305 // NOTE: 'refer=' is not so good for (at this time).
306 // Consider about using IP address of the victim, try to avoid that.
307 function _preg_replace_callback_domain_exposure($matches = array())
311 // Preserve the victim URI as a complicity or ...
312 if (isset($matches[5])) {
314 $matches[1] . '://' . // scheme
315 $matches[2] . '/' . // victim.example.org
316 $matches[3]; // The rest of all (before victim)
320 if (isset($matches[4])) {
322 $matches[1] . '://' . // scheme
323 $matches[4] . // nasty.example.com
324 '/?refer=' . strtolower($matches[2]) . // victim.example.org
331 // Preprocess: rawurldecode() and adding space(s) and something
332 // to detect/count some URIs _if possible_
333 // NOTE: It's maybe danger to var_dump(result). [e.g. 'javascript:']
334 // [OK] http://victim.example.org/go?http%3A%2F%2Fnasty.example.org
335 // [OK] http://victim.example.org/http://nasty.example.org
336 function spam_uri_pickup_preprocess($string = '')
338 if (! is_string($string)) return '';
340 $string = rawurldecode($string);
342 // Domain exposure (See _preg_replace_callback_domain_exposure())
343 $string = preg_replace_callback(
345 // Something Google: http://www.google.com/supported_domains
346 '#(http)://([a-z0-9.]+\.google\.[a-z]{2,3}(?:\.[a-z]{2})?)/' .
347 '([a-z0-9?=&.%_+-]+)' . // ?query=foo+
348 '\bsite:([a-z0-9.%_-]+)' . // site:nasty.example.com
349 //'()' . // Preserve or remove?
352 '_preg_replace_callback_domain_exposure',
356 // URI exposure (uriuri => uri uri)
357 $string = preg_replace(
359 '#(?<! )(?:https?|ftp):/#i',
360 // '#[a-z][a-z0-9.+-]{1,8}://#i',
361 // '#[a-z][a-z0-9.+-]{1,8}://#i'
370 // Main function of spam-uri pickup
371 function spam_uri_pickup($string = '', $method = array())
373 if (! is_array($method) || empty($method)) {
374 $method = check_uri_spam_method();
377 $string = spam_uri_pickup_preprocess($string);
379 $array = uri_pickup($string);
381 // Area elevation of URIs, for '(especially external)link' intension
382 if (! empty($array)) {
384 if (isset($method['uri_anchor'])) $_method['uri_anchor'] = & $method['uri_anchor'];
385 if (isset($method['uri_bbcode'])) $_method['uri_bbcode'] = & $method['uri_bbcode'];
386 $areas = area_pickup($string, $_method, TRUE);
387 if (! empty($areas)) {
388 $area_shadow = array();
389 foreach (array_keys($array) as $key) {
390 $area_shadow[$key] = & $array[$key]['area'];
391 foreach (array_keys($_method) as $_key) {
392 $area_shadow[$key][$_key] = 0;
395 foreach (array_keys($_method) as $_key) {
396 if (isset($areas[$_key])) {
397 area_measure($areas[$_key], $area_shadow, 1, $_key);
403 // Remove 'offset's for area_measure()
404 foreach(array_keys($array) as $key)
405 unset($array[$key]['area']['offset']);
411 // ---------------------
414 // Scheme normalization: Renaming the schemes
415 // snntp://example.org => nntps://example.org
416 // NOTE: Keep the static lists simple. See also port_normalize().
417 function scheme_normalize($scheme = '', $considerd_harmfull = TRUE)
419 // Abbreviations considerable they don't have link intension
420 static $abbrevs = array(
425 // Alias => normalized
426 static $aliases = array(
436 $scheme = strtolower(trim($scheme));
437 if (isset($abbrevs[$scheme])) {
438 if ($considerd_harmfull) {
439 $scheme = $abbrevs[$scheme];
444 if (isset($aliases[$scheme])) $scheme = $aliases[$scheme];
449 // Port normalization: Suppress the (redundant) default port
450 // HTTP://example.org:80/ => http://example.org/
451 // HTTP://example.org:8080/ => http://example.org:8080/
452 // HTTPS://example.org:443/ => https://example.org/
453 function port_normalize($port, $scheme, $scheme_normalize = TRUE)
455 // Schemes that users _maybe_ want to add protocol-handlers
456 // to their web browsers. (and attackers _maybe_ want to use ...)
457 // Reference: http://www.iana.org/assignments/port-numbers
458 static $array = array(
459 // scheme => default port
486 if ($port === '') return $port;
488 if ($scheme_normalize) $scheme = scheme_normalize($scheme);
489 if (isset($array[$scheme]) && $port == $array[$scheme])
490 $port = ''; // Ignore the defaults
495 // Path normalization
496 // http://example.org => http://example.org/
497 // http://example.org#hoge => http://example.org/#hoge
498 // http://example.org/path/a/b/./c////./d => http://example.org/path/a/b/c/d
499 // http://example.org/path/../../a/../back => http://example.org/back
500 function path_normalize($path = '', $divider = '/', $addroot = TRUE)
502 if (! is_string($path) || $path == '')
503 return $addroot ? $divider : '';
506 $last = ($path[strlen($path) - 1] == $divider) ? $divider : '';
507 $array = explode($divider, $path);
510 foreach(array_keys($array) as $key) {
511 if ($array[$key] == '' || $array[$key] == '.')
516 foreach($array as $value) {
517 if ($value == '..') {
520 array_push($tmp, $value);
525 $path = $addroot ? $divider : '';
526 if (! empty($array)) $path .= implode($divider, $array) . $last;
531 // DirectoryIndex normalize (Destructive and rough)
532 function file_normalize($string = 'index.html.en')
534 static $array = array(
535 'index' => TRUE, // Some system can omit the suffix
537 'index.html' => TRUE,
538 'index.shtml' => TRUE,
541 'index.php3' => TRUE,
542 'index.php4' => TRUE,
543 //'index.pl' => TRUE,
544 //'index.py' => TRUE,
545 //'index.rb' => TRUE,
547 'default.htm' => TRUE,
548 'default.html' => TRUE,
549 'default.asp' => TRUE,
550 'default.aspx' => TRUE,
553 // Content-negothiation filter:
554 // Roughly removing ISO 639 -like
555 // 2-letter suffixes (See RFC3066)
557 if (preg_match('/(.*)\.[a-z][a-z](?:-[a-z][a-z])?$/i', $string, $matches)) {
558 $_string = $matches[1];
560 $_string = & $string;
563 if (isset($array[strtolower($_string)])) {
570 // Sort query-strings if possible (Destructive and rough)
571 // [OK] &&&&f=d&b&d&c&a=0dd => a=0dd&b&c&d&f=d
572 // [OK] nothing==&eg=dummy&eg=padding&eg=foobar => eg=foobar
573 function query_normalize($string = '', $equal = FALSE, $equal_cutempty = TRUE)
575 $array = explode('&', $string);
577 // Remove '&' paddings
578 foreach(array_keys($array) as $key) {
579 if ($array[$key] == '') {
584 // Consider '='-sepalated input and paddings
586 $equals = $not_equals = array();
587 foreach ($array as $part) {
588 if (strpos($part, '=') === FALSE) {
589 $not_equals[] = $part;
591 list($key, $value) = explode('=', $part, 2);
592 $value = ltrim($value, '=');
593 if (! $equal_cutempty || $value != '') {
594 $equals[$key] = $value;
599 $array = & $not_equals;
600 foreach ($equals as $key => $value) {
601 $array[] = $key . '=' . $value;
607 return implode('&', $array);
610 // ---------------------
611 // Part One : Checker
613 function generate_glob_regex($string = '', $divider = '/')
615 static $from = array(
618 // 22 => '[', // Maybe cause regex compilation error (e.g. '[]')
634 if (is_array($string)) {
638 array_map('generate_glob_regex',
640 array_pad(array(), count($string), $divider)
645 $string = str_replace($from, $mid, $string); // Hide
646 $string = preg_quote($string, $divider);
647 $string = str_replace($mid, $to, $string); // Unhide
652 function get_blocklist($list = '')
656 if (! isset($regex)) {
661 $blocklist['badhost'] = array(
662 //'*', // Deny all uri
663 //'10.20.*.*', // 10.20.example.com also matches
664 //'*.blogspot.com', // Blog services subdomains
665 //array('blogspot.com', '*.blogspot.com')
667 foreach ($blocklist['badhost'] as $part) {
668 $_part = is_array($part) ? implode('/', $part) : $part;
669 $regex['badhost'][$_part] = '/^' . generate_glob_regex($part) . '$/i';
674 if (file_exists(SPAM_INI_FILE)) {
675 $blocklist = array();
676 require(SPAM_INI_FILE);
677 foreach(array('goodhost', 'badhost') as $key) {
678 if (! isset($blocklist[$key])) continue;
679 foreach ($blocklist[$key] as $part) {
680 $_part = is_array($part) ? implode('/', $part) : $part;
681 $regex[$key][$_part] = '/^' . generate_glob_regex($part) . '$/i';
689 } else if (isset($regex[$list])) {
690 return $regex[$list];
696 // TODO: preg_grep() ?
697 function is_badhost($hosts = '', $asap = TRUE)
699 $goodhost = get_blocklist('goodhost');
700 $badhost = get_blocklist('badhost');
703 if (! is_array($hosts)) $hosts = array($hosts);
705 foreach($hosts as $host) {
706 if (! is_string($host)) continue;
709 foreach ($goodhost as $_regex) {
710 if (preg_match($_regex, $host)) {
715 if ($is_good) continue;
717 foreach ($badhost as $part => $_regex) {
718 if (preg_match($_regex, $host)) {
719 if (! isset($result[$part])) $result[$part] = array();
720 $result[$part][] = $host;
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' => 0 * $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,
790 $sum = & $progress['sum'];
791 $is_spam = & $progress['is_spam'];
792 $asap = isset($method['asap']);
795 if (is_array($target)) {
796 foreach($target as $str) {
798 $_progress = check_uri_spam($str, $method);
799 $_sum = & $_progress['sum'];
800 $_is_spam = & $_progress['is_spam'];
801 foreach (array_keys($_sum) as $key) {
802 $sum[$key] += $_sum[$key];
804 foreach(array_keys($_is_spam) as $key) {
805 if (is_array($_is_spam[$key])) {
806 // Marge keys (badhost)
807 foreach(array_keys($_is_spam[$key]) as $_key) {
808 if (! isset($is_spam[$key][$_key])) {
809 $is_spam[$key][$_key] = $_is_spam[$key][$_key];
811 $is_spam[$key][$_key] += $_is_spam[$key][$_key];
815 $is_spam[$key] = TRUE;
818 if ($asap && $is_spam) break;
823 // Area: There's HTML anchor tag
824 if ((! $asap || ! $is_spam) && isset($method['area_anchor'])) {
825 $key = 'area_anchor';
826 $_asap = isset($method['asap']) ? array('asap' => TRUE) : array();
827 $result = area_pickup($target, array($key => TRUE) + $_asap);
829 $sum[$key] = $result[$key];
830 if (isset($method[$key]) && $sum[$key] > $method[$key]) {
831 $is_spam[$key] = TRUE;
836 // Area: There's 'BBCode' linking tag
837 if ((! $asap || ! $is_spam) && isset($method['area_bbcode'])) {
838 $key = 'area_bbcode';
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;
850 if ($asap && $is_spam) {
854 $pickups = spam_uri_pickup($target, $method);
855 if (empty($pickups)) {
859 // URI: Check quantity
860 $sum['quantity'] += count($pickups);
862 if ((! $asap || ! $is_spam) && isset($method['quantity']) &&
863 $sum['quantity'] > $method['quantity']) {
864 $is_spam['quantity'] = TRUE;
867 // URI: used inside HTML anchor tag pair
868 if ((! $asap || ! $is_spam) && isset($method['uri_anchor'])) {
870 foreach($pickups as $pickup) {
871 if (isset($pickup['area'][$key])) {
872 $sum[$key] += $pickup['area'][$key];
873 if(isset($method[$key]) &&
874 $sum[$key] > $method[$key]) {
875 $is_spam[$key] = TRUE;
876 if ($asap && $is_spam) break;
878 if ($asap && $is_spam) break;
883 // URI: used inside 'BBCode' pair
884 if ((! $asap || ! $is_spam) && isset($method['uri_bbcode'])) {
886 foreach($pickups as $pickup) {
887 if (isset($pickup['area'][$key])) {
888 $sum[$key] += $pickup['area'][$key];
889 if(isset($method[$key]) &&
890 $sum[$key] > $method[$key]) {
891 $is_spam[$key] = TRUE;
892 if ($asap && $is_spam) break;
894 if ($asap && $is_spam) break;
899 // URI: Uniqueness (and removing non-uniques)
900 if ((! $asap || ! $is_spam) && isset($method['non_uniquri'])) {
902 // Destructive normalize of URIs
903 uri_array_normalize($pickups);
906 foreach (array_keys($pickups) as $key) {
907 $uris[$key] = uri_array_implode($pickups[$key]);
909 $count = count($uris);
910 $uris = array_unique($uris);
911 $sum['non_uniquri'] += $count - count($uris);
912 if ($sum['non_uniquri'] > $method['non_uniquri']) {
913 $is_spam['non_uniquri'] = TRUE;
915 if (! $asap || ! $is_spam) {
916 foreach (array_diff(array_keys($pickups),
917 array_keys($uris)) as $remove) {
918 unset($pickups[$remove]);
925 if ($asap && $is_spam) {
929 // Host: Uniqueness (uniq / non-uniq)
931 foreach ($pickups as $pickup) $hosts[] = & $pickup['host'];
932 $hosts = array_unique($hosts);
933 $sum['uniqhost'] += count($hosts);
934 if ((! $asap || ! $is_spam) && isset($method['non_uniqhost'])) {
935 $sum['non_uniqhost'] = $sum['quantity'] - $sum['uniqhost'];
936 if ($sum['non_uniqhost'] > $method['non_uniqhost']) {
937 $is_spam['non_uniqhost'] = TRUE;
942 if ($asap && $is_spam) {
947 if ((! $asap || ! $is_spam) && isset($method['badhost'])) {
948 $badhost = is_badhost($hosts, $asap);
949 if (! empty($badhost)) {
950 $sum['badhost'] += array_count_leaves($badhost);
951 foreach(array_keys($badhost) as $keys) {
952 $is_spam['badhost'][$keys] =
953 array_count_leaves($badhost[$keys]);
963 function array_count_leaves($array = array(), $count_empty_array = FALSE)
965 if (! is_array($array) || (empty($array) && $count_empty_array))
970 foreach ($array as $part) {
971 $result += array_count_leaves($part, $count_empty_array);
976 // ---------------------
979 // TODO: Don't show unused $method!
980 // Summarize $progress (blocked only)
981 function summarize_spam_progress($progress = array(), $blockedonly = FALSE)
984 $tmp = array_keys($progress['is_spam']);
987 $method = & $progress['method'];
988 if (isset($progress['sum'])) {
989 foreach ($progress['sum'] as $key => $value) {
990 if (isset($method[$key])) {
991 $tmp[] = $key . '(' . $value . ')';
997 return implode(', ', $tmp);
1000 // ---------------------
1003 // Common bahavior for blocking
1004 // NOTE: Call this function from various blocking feature, to disgueise the reason 'why blocked'
1005 function spam_exit($mode = '', $data = array())
1008 case '': echo("\n"); break;
1010 echo('<pre>' . "\n");
1011 echo htmlspecialchars(var_export($data, TRUE));
1012 echo('</pre>' . "\n");
1021 // ---------------------
1024 // TODO: Record them
1025 // Simple/fast spam filter ($target: 'a string' or an array())
1026 function pkwk_spamfilter($action, $page, $target = array('title' => ''), $method = array(), $exitmode = '')
1028 $progress = check_uri_spam($target, $method);
1030 if (! empty($progress['is_spam'])) {
1031 // Mail to administrator(s)
1032 pkwk_spamnotify($action, $page, $target, $progress, $method);
1035 spam_exit($exitmode, $progress);
1039 // ---------------------
1040 // PukiWiki original
1042 // Mail to administrator(s)
1043 function pkwk_spamnotify($action, $page, $target = array('title' => ''), $progress = array(), $method = array())
1045 global $notify, $notify_subject;
1047 if (! $notify) return;
1049 $asap = isset($method['asap']);
1051 $summary['ACTION'] = 'Blocked by: ' . summarize_spam_progress($progress, TRUE);
1053 $summary['METRICS'] = summarize_spam_progress($progress);
1055 if (isset($progress['is_spam']['badhost'])) {
1057 foreach($progress['is_spam']['badhost'] as $glob=>$number) {
1058 $badhost[] = $glob . '(' . $number . ')';
1060 $summary['DETAIL_BADHOST'] = implode(', ', $badhost);
1062 $summary['COMMENT'] = $action;
1063 $summary['PAGE'] = '[blocked] ' . (is_pagename($page) ? $page : '');
1064 $summary['URI'] = get_script_uri() . '?' . rawurlencode($page);
1065 $summary['USER_AGENT'] = TRUE;
1066 $summary['REMOTE_ADDR'] = TRUE;
1067 pkwk_mail_notify($notify_subject, var_export($target, TRUE), $summary);