2 // $Id: spam.php,v 1.83 2006/12/30 07:44:07 henoheno Exp $
3 // Copyright (C) 2006 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
8 // (PHP 4 >= 4.2.0): var_export(): mail-reporting and dump related
10 if (! defined('SPAM_INI_FILE')) define('SPAM_INI_FILE', 'spam.ini.php');
12 // ---------------------
15 // Return an array of URIs in the $string
16 // [OK] http://nasty.example.org#nasty_string
17 // [OK] http://nasty.example.org:80/foo/xxx#nasty_string/bar
18 // [OK] ftp://nasty.example.org:80/dfsdfs
19 // [OK] ftp://cnn.example.com&story=breaking_news@10.0.0.1/top_story.htm (from RFC3986)
20 function uri_pickup($string = '', $normalize = TRUE,
21 $preserve_rawuri = FALSE, $preserve_chunk = TRUE)
23 // Not available for: IDN(ignored)
26 // scheme://userinfo@host:port/path/or/pathinfo/maybefile.and?query=string#fragment
27 // Refer RFC3986 (Regex below is not strict)
28 '#(\b[a-z][a-z0-9.+-]{1,8})://' . // 1: Scheme
30 '([^\s<>"\'\[\]/\#?@]*)' . // 2: Userinfo (Username)
34 '\[[0-9a-f:.]+\]' . '|' . // IPv6([colon-hex and dot]): RFC2732
35 '(?:[0-9]{1-3}\.){3}[0-9]{1-3}' . '|' . // IPv4(dot-decimal): 001.22.3.44
36 '[^\s<>"\'\[\]:/\#?]+' . // FQDN: foo.example.org
38 '(?::([0-9]*))?' . // 4: Port
39 '((?:/+[^\s<>"\'\[\]/\#]+)*/+)?' . // 5: Directory path or path-info
40 '([^\s<>"\'\[\]\#?]+)?' . // 6: File?
41 '(?:\?([^\s<>"\'\[\]\#]+))?' . // 7: Query string
42 '(?:\#([a-z0-9._~%!$&\'()*+,;=:@-]*))?' . // 8: Fragment
44 $string, $array, PREG_SET_ORDER | PREG_OFFSET_CAPTURE
48 static $parts = array(
49 1 => 'scheme', 2 => 'userinfo', 3 => 'host', 4 => 'port',
50 5 => 'path', 6 => 'file', 7 => 'query', 8 => 'fragment'
53 foreach(array_keys($array) as $uri) {
54 $_uri = & $array[$uri];
55 array_rename_keys($_uri, $parts, TRUE, $default);
57 $offset = $_uri['scheme'][1]; // Scheme's offset
58 foreach(array_keys($_uri) as $part) {
59 // Remove offsets for each part
60 $_uri[$part] = & $_uri[$part][0];
64 $_uri['scheme'] = scheme_normalize($_uri['scheme']);
65 if ($_uri['scheme'] === '') {
69 $_uri['host'] = strtolower($_uri['host']);
70 $_uri['port'] = port_normalize($_uri['port'], $_uri['scheme'], FALSE);
71 $_uri['path'] = path_normalize($_uri['path']);
72 if ($preserve_rawuri) $_uri['rawuri'] = & $_uri[0];
75 //$_uri['uri'] = uri_array_implode($_uri);
77 $_uri['uri'] = & $_uri[0]; // Raw
79 unset($_uri[0]); // Matched string itself
80 if (! $preserve_chunk) {
93 // Area offset for area_measure()
94 $_uri['area']['offset'] = $offset;
100 // Destructive normalize of URI array
101 // NOTE: Give me the uri_pickup() result with chunks
102 function uri_array_normalize(& $pickups, $preserve = TRUE)
104 if (! is_array($pickups)) return $pickups;
106 foreach (array_keys($pickups) as $key) {
107 $_key = & $pickups[$key];
108 $_key['path'] = isset($_key['path']) ? strtolower($_key['path']) : '';
109 $_key['file'] = isset($_key['file']) ? file_normalize($_key['file']) : '';
110 $_key['query'] = isset($_key['query']) ? query_normalize(strtolower($_key['query']), TRUE) : '';
111 $_key['fragment'] = (isset($_key['fragment']) && $preserve) ?
112 strtolower($_key['fragment']) : ''; // Just ignore
118 // An URI array => An URI (See uri_pickup())
119 function uri_array_implode($uri = array())
121 if (empty($uri) || ! is_array($uri)) return NULL;
124 if (isset($uri['scheme']) && $uri['scheme'] !== '') {
125 $tmp[] = & $uri['scheme'];
128 if (isset($uri['userinfo']) && $uri['userinfo'] !== '') {
129 $tmp[] = & $uri['userinfo'];
132 if (isset($uri['host']) && $uri['host'] !== '') {
133 $tmp[] = & $uri['host'];
135 if (isset($uri['port']) && $uri['port'] !== '') {
137 $tmp[] = & $uri['port'];
139 if (isset($uri['path']) && $uri['path'] !== '') {
140 $tmp[] = & $uri['path'];
142 if (isset($uri['file']) && $uri['file'] !== '') {
143 $tmp[] = & $uri['file'];
145 if (isset($uri['query']) && $uri['query'] !== '') {
147 $tmp[] = & $uri['query'];
149 if (isset($uri['fragment']) && $uri['fragment'] !== '') {
151 $tmp[] = & $uri['fragment'];
154 return implode('', $tmp);
157 // $array['something'] => $array['wanted']
158 function array_rename_keys(& $array, $keys = array('from' => 'to'), $force = FALSE, $default = '')
160 if (! is_array($array) || ! is_array($keys)) return FALSE;
162 // Nondestructive test
164 foreach(array_keys($keys) as $from)
165 if (! isset($array[$from]))
168 foreach($keys as $from => $to) {
169 if ($from === $to) continue;
170 if (! $force || isset($array[$from])) {
171 $array[$to] = & $array[$from];
172 unset($array[$from]);
174 $array[$to] = $default;
181 // ---------------------
184 // Pickup all of markup areas
185 function area_pickup($string = '', $method = array())
188 if (empty($method)) return $area;
190 // Anchor tag pair by preg_match and preg_match_all()
192 // [OK] <a href= >Good site!</a>
193 // [OK] <a href= "#" >test</a>
194 // [OK] <a href="http://nasty.example.com">visit http://nasty.example.com/</a>
195 // [OK] <a href=\'http://nasty.example.com/\' >discount foobar</a>
196 // [NG] <a href="http://ng.example.com">visit http://ng.example.com _not_ended_
197 $regex = '#<a\b[^>]*\bhref\b[^>]*>.*?</a\b[^>]*(>)#i';
198 if (isset($method['area_anchor'])) {
200 $count = isset($method['asap']) ?
201 preg_match($regex, $string) :
202 preg_match_all($regex, $string, $areas);
203 if (! empty($count)) $area['area_anchor'] = $count;
205 if (isset($method['uri_anchor'])) {
207 preg_match_all($regex, $string, $areas, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
208 foreach(array_keys($areas) as $_area) {
209 $areas[$_area] = array(
210 $areas[$_area][0][1], // Area start (<a href>)
211 $areas[$_area][1][1], // Area end (</a>)
214 if (! empty($areas)) $area['uri_anchor'] = $areas;
217 // phpBB's "BBCode" pair by preg_match and preg_match_all()
219 // [OK] [url]http://nasty.example.com/[/url]
220 // [OK] [link]http://nasty.example.com/[/link]
221 // [OK] [url=http://nasty.example.com]visit http://nasty.example.com/[/url]
222 // [OK] [link http://nasty.example.com/]buy something[/link]
223 $regex = '#\[(url|link)\b[^\]]*\].*?\[/\1\b[^\]]*(\])#i';
224 if (isset($method['area_bbcode'])) {
226 $count = isset($method['asap']) ?
227 preg_match($regex, $string) :
228 preg_match_all($regex, $string, $areas, PREG_SET_ORDER);
229 if (! empty($count)) $area['area_bbcode'] = $count;
231 if (isset($method['uri_bbcode'])) {
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 ([url])
237 $areas[$_area][2][1], // Area end ([/url])
240 if (! empty($areas)) $area['uri_bbcode'] = $areas;
243 // Various Wiki syntax
244 // [text_or_uri>text_or_uri]
245 // [text_or_uri:text_or_uri]
246 // [text_or_uri|text_or_uri]
247 // [text_or_uri->text_or_uri]
248 // [text_or_uri text_or_uri] // MediaWiki
249 // MediaWiki: [http://nasty.example.com/ visit http://nasty.example.com/]
254 // If in doubt, it's a little doubtful
255 // if (Area => inside <= Area) $brief += -1
256 function area_measure($areas, & $array, $belief = -1, $a_key = 'area', $o_key = 'offset')
258 if (! is_array($areas) || ! is_array($array)) return;
260 $areas_keys = array_keys($areas);
261 foreach(array_keys($array) as $u_index) {
262 $offset = isset($array[$u_index][$o_key]) ?
263 intval($array[$u_index][$o_key]) : 0;
264 foreach($areas_keys as $a_index) {
265 if (isset($array[$u_index][$a_key])) {
266 $offset_s = intval($areas[$a_index][0]);
267 $offset_e = intval($areas[$a_index][1]);
268 // [Area => inside <= Area]
269 if ($offset_s < $offset && $offset < $offset_e) {
270 $array[$u_index][$a_key] += $belief;
277 // ---------------------
280 // Domain exposure callback (See spam_uri_pickup_preprocess())
281 // http://victim.example.org/?foo+site:nasty.example.com+bar
282 // => http://nasty.example.com/?refer=victim.example.org
283 // NOTE: 'refer=' is not so good for (at this time).
284 // Consider about using IP address of the victim, try to avoid that.
285 function _preg_replace_callback_domain_exposure($matches = array())
289 // Preserve the victim URI as a complicity or ...
290 if (isset($matches[5])) {
292 $matches[1] . '://' . // scheme
293 $matches[2] . '/' . // victim.example.org
294 $matches[3]; // The rest of all (before victim)
298 if (isset($matches[4])) {
300 $matches[1] . '://' . // scheme
301 $matches[4] . // nasty.example.com
302 '/?refer=' . strtolower($matches[2]) . // victim.example.org
309 // Preprocess: rawurldecode() and adding space(s) and something
310 // to detect/count some URIs _if possible_
311 // NOTE: It's maybe danger to var_dump(result). [e.g. 'javascript:']
312 // [OK] http://victim.example.org/go?http%3A%2F%2Fnasty.example.org
313 // [OK] http://victim.example.org/http://nasty.example.org
314 function spam_uri_pickup_preprocess($string = '')
316 if (! is_string($string)) return '';
318 $string = rawurldecode($string);
320 // Domain exposure (See _preg_replace_callback_domain_exposure())
321 $string = preg_replace_callback(
323 // Something Google: http://www.google.com/supported_domains
324 '#(http)://([a-z0-9.]+\.google\.[a-z]{2,3}(?:\.[a-z]{2})?)/' .
325 '([a-z0-9?=&.%_+-]+)' . // ?query=foo+
326 '\bsite:([a-z0-9.%_-]+)' . // site:nasty.example.com
327 //'()' . // Preserve or remove?
330 '_preg_replace_callback_domain_exposure',
334 // URI exposure (uriuri => uri uri)
335 $string = preg_replace(
337 '#(?<! )(?:https?|ftp):/#i',
338 // '#[a-z][a-z0-9.+-]{1,8}://#i',
339 // '#[a-z][a-z0-9.+-]{1,8}://#i'
348 // Main function of spam-uri pickup
349 function spam_uri_pickup($string = '', $method = array())
351 if (! is_array($method) || empty($method)) {
352 $method = check_uri_spam_method();
355 $string = spam_uri_pickup_preprocess($string);
357 $array = uri_pickup($string);
359 // Area elevation of URIs, for '(especially external)link' intension
360 if (! empty($array)) {
362 if (isset($method['uri_anchor'])) $_method['uri_anchor'] = & $method['uri_anchor'];
363 if (isset($method['uri_bbcode'])) $_method['uri_bbcode'] = & $method['uri_bbcode'];
364 $areas = area_pickup($string, $_method, TRUE);
365 if (! empty($areas)) {
366 $area_shadow = array();
367 foreach (array_keys($array) as $key) {
368 $area_shadow[$key] = & $array[$key]['area'];
369 foreach (array_keys($_method) as $_key) {
370 $area_shadow[$key][$_key] = 0;
373 foreach (array_keys($_method) as $_key) {
374 if (isset($areas[$_key])) {
375 area_measure($areas[$_key], $area_shadow, 1, $_key);
381 // Remove 'offset's for area_measure()
382 foreach(array_keys($array) as $key)
383 unset($array[$key]['area']['offset']);
389 // ---------------------
392 // Scheme normalization: Renaming the schemes
393 // snntp://example.org => nntps://example.org
394 // NOTE: Keep the static lists simple. See also port_normalize().
395 function scheme_normalize($scheme = '', $considerd_harmfull = TRUE)
397 // Abbreviations considerable they don't have link intension
398 static $abbrevs = array(
403 // Alias => normalized
404 static $aliases = array(
414 $scheme = strtolower(trim($scheme));
415 if (isset($abbrevs[$scheme])) {
416 if ($considerd_harmfull) {
417 $scheme = $abbrevs[$scheme];
422 if (isset($aliases[$scheme])) $scheme = $aliases[$scheme];
427 // Port normalization: Suppress the (redundant) default port
428 // HTTP://example.org:80/ => http://example.org/
429 // HTTP://example.org:8080/ => http://example.org:8080/
430 // HTTPS://example.org:443/ => https://example.org/
431 function port_normalize($port, $scheme, $scheme_normalize = TRUE)
433 // Schemes that users _maybe_ want to add protocol-handlers
434 // to their web browsers. (and attackers _maybe_ want to use ...)
435 // Reference: http://www.iana.org/assignments/port-numbers
436 static $array = array(
437 // scheme => default port
464 if ($port === '') return $port;
466 if ($scheme_normalize) $scheme = scheme_normalize($scheme);
467 if (isset($array[$scheme]) && $port == $array[$scheme])
468 $port = ''; // Ignore the defaults
473 // Path normalization
474 // http://example.org => http://example.org/
475 // http://example.org#hoge => http://example.org/#hoge
476 // http://example.org/path/a/b/./c////./d => http://example.org/path/a/b/c/d
477 // http://example.org/path/../../a/../back => http://example.org/back
478 function path_normalize($path = '', $divider = '/', $addroot = TRUE)
480 if (! is_string($path) || $path == '')
481 return $addroot ? $divider : '';
484 $last = ($path[strlen($path) - 1] == $divider) ? $divider : '';
485 $array = explode($divider, $path);
488 foreach(array_keys($array) as $key) {
489 if ($array[$key] == '' || $array[$key] == '.')
494 foreach($array as $value) {
495 if ($value == '..') {
498 array_push($tmp, $value);
503 $path = $addroot ? $divider : '';
504 if (! empty($array)) $path .= implode($divider, $array) . $last;
509 // DirectoryIndex normalize (Destructive and rough)
510 function file_normalize($string = 'index.html.en')
512 static $array = array(
513 'index' => TRUE, // Some system can omit the suffix
515 'index.html' => TRUE,
516 'index.shtml' => TRUE,
519 'index.php3' => TRUE,
520 'index.php4' => TRUE,
521 //'index.pl' => TRUE,
522 //'index.py' => TRUE,
523 //'index.rb' => TRUE,
525 'default.htm' => TRUE,
526 'default.html' => TRUE,
527 'default.asp' => TRUE,
528 'default.aspx' => TRUE,
531 // Content-negothiation filter:
532 // Roughly removing ISO 639 -like
533 // 2-letter suffixes (See RFC3066)
535 if (preg_match('/(.*)\.[a-z][a-z](?:-[a-z][a-z])?$/i', $string, $matches)) {
536 $_string = $matches[1];
538 $_string = & $string;
541 if (isset($array[strtolower($_string)])) {
548 // Sort query-strings if possible (Destructive and rough)
549 // [OK] &&&&f=d&b&d&c&a=0dd => a=0dd&b&c&d&f=d
550 // [OK] nothing==&eg=dummy&eg=padding&eg=foobar => eg=foobar
551 function query_normalize($string = '', $equal = FALSE, $equal_cutempty = TRUE)
553 $array = explode('&', $string);
555 // Remove '&' paddings
556 foreach(array_keys($array) as $key) {
557 if ($array[$key] == '') {
562 // Consider '='-sepalated input and paddings
564 $equals = $not_equals = array();
565 foreach ($array as $part) {
566 if (strpos($part, '=') === FALSE) {
567 $not_equals[] = $part;
569 list($key, $value) = explode('=', $part, 2);
570 $value = ltrim($value, '=');
571 if (! $equal_cutempty || $value != '') {
572 $equals[$key] = $value;
577 $array = & $not_equals;
578 foreach ($equals as $key => $value) {
579 $array[] = $key . '=' . $value;
585 return implode('&', $array);
588 // ---------------------
589 // Part One : Checker
591 function generate_glob_regex($string = '', $divider = '/')
593 static $from = array(
596 // 22 => '[', // Maybe cause regex compilation error (e.g. '[]')
612 if (is_array($string)) {
616 array_map('generate_glob_regex',
618 array_pad(array(), count($string), $divider)
623 $string = str_replace($from, $mid, $string); // Hide
624 $string = preg_quote($string, $divider);
625 $string = str_replace($mid, $to, $string); // Unhide
631 // TODO: preg_grep() ?
633 function is_badhost($hosts = '', $asap = TRUE)
637 if (! isset($regex)) {
639 $regex['badhost'] = array();
643 $blocklist['badhost'] = array(
644 //'*', // Deny all uri
645 //'10.20.*.*', // 10.20.example.com also matches
646 //'*.blogspot.com', // Blog services subdomains
647 //array('blogspot.com', '*.blogspot.com')
649 // Viral/Buzz marketers' site, trying to make people
650 // as commercial Wiki spammers
651 // http://pukiwiki.sourceforge.jp/image/2006-12-16_wikiviral_pressblog.gif
652 array('pressblog.jp', '*.pressblog.jp'),
654 foreach ($blocklist['badhost'] as $part) {
655 $_part = is_array($part) ? implode('/', $part) : $part;
656 $regex['badhost'][$_part] = '/^' . generate_glob_regex($part) . '$/i';
661 if (file_exists(SPAM_INI_FILE)) {
662 $blocklist = array();
663 require(SPAM_INI_FILE);
664 foreach ($blocklist['badhost'] as $part) {
665 $_part = is_array($part) ? implode('/', $part) : $part;
666 $regex['badhost'][$_part] = '/^' . generate_glob_regex($part) . '$/i';
672 if (! is_array($hosts)) $hosts = array($hosts);
674 foreach($hosts as $host) {
675 if (! is_string($host)) $host = '';
676 foreach ($regex['badhost'] as $part => $_regex) {
677 if (preg_match($_regex, $host)) {
678 if (! isset($result[$part])) $result[$part] = array();
679 $result[$part][] = $host;
692 // Default (enabled) methods and thresholds
693 function check_uri_spam_method($times = 1, $t_area = 0, $rule = TRUE)
695 $times = intval($times);
696 $t_area = intval($t_area);
700 'quantity' => 8 * $times, // Allow N URIs
701 'non_uniquri' => 3 * $times, // Allow N duped (and normalized) URIs
704 'area_anchor' => $t_area, // Using <a href> HTML tag
705 'area_bbcode' => $t_area, // Using [url] or [link] BBCode
706 //'uri_anchor' => $t_area, // URI inside <a href> HTML tag
707 //'uri_bbcode' => $t_area, // URI inside [url] or [link] BBCode
712 //'asap' => TRUE, // Quit or return As Soon As Possible
713 'uniqhost' => TRUE, // Show uniq host (at block notification mail)
714 'badhost' => TRUE, // Check badhost
720 // Remove non-$positive values
721 foreach (array_keys($positive) as $key) {
722 if ($positive[$key] < 0) unset($positive[$key]);
725 return $positive + $bool;
728 // Simple/fast spam check
729 function check_uri_spam($target = '', $method = array())
731 if (! is_array($method) || empty($method)) {
732 $method = check_uri_spam_method();
745 'is_spam' => array(),
746 'method' => & $method,
748 $sum = & $progress['sum'];
749 $is_spam = & $progress['is_spam'];
750 $asap = isset($method['asap']);
753 if (is_array($target)) {
754 foreach($target as $str) {
756 $_progress = check_uri_spam($str, $method);
757 foreach (array_keys($_progress['sum']) as $key) {
758 $sum[$key] += $_progress['sum'][$key];
760 foreach(array_keys($_progress['is_spam']) as $key) {
761 if (is_array($_progress['is_spam'][$key])) {
763 foreach(array_keys($_progress['is_spam'][$key]) as $_key) {
764 $is_spam[$key][$_key] = TRUE;
767 $is_spam[$key] = TRUE;
770 if ($asap && $is_spam) break;
775 // Area: There's HTML anchor tag
776 if ((! $asap || ! $is_spam) && isset($method['area_anchor'])) {
777 $key = 'area_anchor';
778 $_asap = isset($method['asap']) ? array('asap' => TRUE) : array();
779 $result = area_pickup($target, array($key => TRUE) + $_asap);
781 $sum[$key] = $result[$key];
782 if (isset($method[$key]) && $sum[$key] > $method[$key]) {
783 $is_spam[$key] = TRUE;
788 // Area: There's 'BBCode' linking tag
789 if ((! $asap || ! $is_spam) && isset($method['area_bbcode'])) {
790 $key = 'area_bbcode';
791 $_asap = isset($method['asap']) ? array('asap' => TRUE) : array();
792 $result = area_pickup($target, array($key => TRUE) + $_asap);
794 $sum[$key] = $result[$key];
795 if (isset($method[$key]) && $sum[$key] > $method[$key]) {
796 $is_spam[$key] = TRUE;
802 if ($asap && $is_spam) {
806 $pickups = spam_uri_pickup($target, $method);
807 if (empty($pickups)) {
811 // URI: Check quantity
812 $sum['quantity'] += count($pickups);
814 if ((! $asap || ! $is_spam) && isset($method['quantity']) &&
815 $sum['quantity'] > $method['quantity']) {
816 $is_spam['quantity'] = TRUE;
819 // URI: used inside HTML anchor tag pair
820 if ((! $asap || ! $is_spam) && isset($method['uri_anchor'])) {
822 foreach($pickups as $pickup) {
823 if (isset($pickup['area'][$key])) {
824 $sum[$key] += $pickup['area'][$key];
825 if(isset($method[$key]) &&
826 $sum[$key] > $method[$key]) {
827 $is_spam[$key] = TRUE;
828 if ($asap && $is_spam) break;
830 if ($asap && $is_spam) break;
835 // URI: used inside 'BBCode' pair
836 if ((! $asap || ! $is_spam) && isset($method['uri_bbcode'])) {
838 foreach($pickups as $pickup) {
839 if (isset($pickup['area'][$key])) {
840 $sum[$key] += $pickup['area'][$key];
841 if(isset($method[$key]) &&
842 $sum[$key] > $method[$key]) {
843 $is_spam[$key] = TRUE;
844 if ($asap && $is_spam) break;
846 if ($asap && $is_spam) break;
851 // URI: Uniqueness (and removing non-uniques)
852 if ((! $asap || ! $is_spam) && isset($method['non_uniquri'])) {
854 // Destructive normalize of URIs
855 uri_array_normalize($pickups);
858 foreach (array_keys($pickups) as $key) {
859 $uris[$key] = uri_array_implode($pickups[$key]);
861 $count = count($uris);
862 $uris = array_unique($uris);
863 $sum['non_uniquri'] += $count - count($uris);
864 if ($sum['non_uniquri'] > $method['non_uniquri']) {
865 $is_spam['non_uniquri'] = TRUE;
867 if (! $asap || ! $is_spam) {
868 foreach (array_diff(array_keys($pickups),
869 array_keys($uris)) as $remove) {
870 unset($pickups[$remove]);
877 if ($asap && $is_spam) {
883 foreach ($pickups as $pickup) $hosts[] = & $pickup['host'];
884 $hosts = array_unique($hosts);
885 $sum['uniqhost'] += count($hosts);
888 if ((! $asap || ! $is_spam) && isset($method['badhost'])) {
889 $badhost = is_badhost($hosts, $asap);
890 if (! empty($badhost)) {
891 $sum['badhost'] += array_count_leaves($badhost);
892 foreach(array_keys($badhost) as $keys) {
893 $is_spam['badhost'][$keys] = TRUE;
903 function array_count_leaves($array = array(), $count_empty_array = FALSE)
905 if (! is_array($array) || (empty($array) && $count_empty_array))
910 foreach ($array as $part) {
911 $result += array_count_leaves($part, $count_empty_array);
916 // ---------------------
919 // TODO: Don't show unused $method!
920 // Summarize $progress (blocked only)
921 function summarize_spam_progress($progress = array(), $blockedonly = FALSE)
924 $tmp = array_keys($progress['is_spam']);
927 $method = & $progress['method'];
928 if (isset($progress['sum'])) {
929 foreach ($progress['sum'] as $key => $value) {
930 if (isset($method[$key])) {
931 $tmp[] = $key . '(' . $value . ')';
937 return implode(', ', $tmp);
940 // ---------------------
943 // Common bahavior for blocking
944 // NOTE: Call this function from various blocking feature, to disgueise the reason 'why blocked'
945 function spam_exit($mode = '', $data = array())
948 case '': echo("\n"); break;
950 echo('<pre>' . "\n");
951 echo htmlspecialchars(var_export($data, TRUE));
952 echo('</pre>' . "\n");
961 // ---------------------
965 // Simple/fast spam filter ($target: 'a string' or an array())
966 function pkwk_spamfilter($action, $page, $target = array('title' => ''), $method = array(), $exitmode = '')
968 $progress = check_uri_spam($target, $method);
970 if (! empty($progress['is_spam'])) {
971 // Mail to administrator(s)
972 pkwk_spamnotify($action, $page, $target, $progress, $method);
975 spam_exit($exitmode, $progress);
979 // ---------------------
982 // Mail to administrator(s)
983 function pkwk_spamnotify($action, $page, $target = array('title' => ''), $progress = array(), $method = array())
985 global $notify, $notify_subject;
987 if (! $notify) return;
989 $asap = isset($method['asap']);
991 $summary['ACTION'] = 'Blocked by: ' . summarize_spam_progress($progress, TRUE);
993 $summary['METRICS'] = summarize_spam_progress($progress);
995 if (isset($progress['is_spam']['badhost'])) {
996 $summary['BADHOST'] =
997 implode(', ', array_keys($progress['is_spam']['badhost']));
999 $summary['COMMENT'] = $action;
1000 $summary['PAGE'] = '[blocked] ' . (is_pagename($page) ? $page : '');
1001 $summary['URI'] = get_script_uri() . '?' . rawurlencode($page);
1002 $summary['USER_AGENT'] = TRUE;
1003 $summary['REMOTE_ADDR'] = TRUE;
1004 pkwk_mail_notify($notify_subject, var_export($target, TRUE), $summary);