2 // $Id: spam.php,v 1.201 2007/08/17 14:33:32 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');
11 if (! defined('DOMAIN_INI_FILE')) define('DOMAIN_INI_FILE', 'domain.ini.php');
13 // ---------------------
16 // (PHP 4 >= 4.2.0): var_export(): mail-reporting and dump related
17 if (! function_exists('var_export')) {
18 function var_export() {
19 return 'var_export() is not found on this server' . "\n";
23 // (PHP 4 >= 4.2.0): preg_grep() enables invert option
24 function preg_grep_invert($pattern = '//', $input = array())
27 if (! isset($invert)) $invert = defined('PREG_GREP_INVERT');
30 return preg_grep($pattern, $input, PREG_GREP_INVERT);
32 $result = preg_grep($pattern, $input);
34 return array_diff($input, preg_grep($pattern, $input));
42 // ---------------------
45 // Very roughly, shrink the lines of var_export()
46 // NOTE: If the same data exists, it must be corrupted.
47 function var_export_shrink($expression, $return = FALSE, $ignore_numeric_keys = FALSE)
49 $result = var_export($expression, TRUE);
51 $result = preg_replace(
52 // Remove a newline and spaces
53 '# => \n *array \(#', ' => array (',
57 if ($ignore_numeric_keys) {
58 $result =preg_replace(
59 // Remove numeric keys
60 '#^( *)[0-9]+ => #m', '$1',
73 // Reverse $string with specified delimiter
74 function delimiter_reverse($string = 'foo.bar.example.com', $from_delim = '.', $to_delim = '.')
76 if (! is_string($string) || ! is_string($from_delim) || ! is_string($to_delim))
79 // com.example.bar.foo
80 return implode($to_delim, array_reverse(explode($from_delim, $string)));
84 function ksort_by_domain(& $array)
87 foreach(array_keys($array) as $key) {
88 $sort[delimiter_reverse($key)] = $key;
90 ksort($sort, SORT_STRING);
92 foreach($sort as $key) {
93 $result[$key] = & $array[$key];
98 // Roughly strings(1) using PCRE
99 // This function is useful to:
100 // * Reduce the size of data, from removing unprintable binary data
101 // * Detect _bare_strings_ from binary data
103 // http://www.freebsd.org/cgi/man.cgi?query=strings (Man-page of GNU strings)
104 // http://www.pcre.org/pcre.txt
105 // Note: mb_ereg_replace() is one of mbstring extension's functions
106 // and need to init its encoding.
107 function strings($binary = '', $min_len = 4, $ignore_space = FALSE, $multibyte = FALSE)
110 $binary = (is_array($binary) || $binary === TRUE) ? '' : strval($binary);
112 $regex = $ignore_space ?
113 '[^[:graph:] \t\n]+' : // Remove "\0" etc, and readable spaces
114 '[^[:graph:][:space:]]+'; // Preserve readable spaces if possible
116 $binary = $multibyte ?
117 mb_ereg_replace($regex, "\n", $binary) :
118 preg_replace('/' . $regex . '/s', "\n", $binary);
121 $binary = preg_replace(
136 // The last character seems "\n" or not
137 $br = (! empty($binary) && $binary[strlen($binary) - 1] == "\n") ? "\n" : '';
139 $min_len = min(1024, intval($min_len));
140 $regex = '/^.{' . $min_len . ',}/S';
141 $binary = implode("\n", preg_grep($regex, explode("\n", $binary))) . $br;
148 // ---------------------
151 // Count leaves (A leaf = value that is not an array, or an empty array)
152 function array_count_leaves($array = array(), $count_empty = FALSE)
154 if (! is_array($array) || (empty($array) && $count_empty)) return 1;
158 foreach ($array as $part) {
159 $count += array_count_leaves($part, $count_empty);
165 // Similar to PHP array_merge_leaves(), except strictly preserving keys as string
166 function array_merge_leaves($array1, $array2, $sort_keys = TRUE)
169 $is_array1 = is_array($array1);
170 $is_array2 = is_array($array2);
177 } else if ($is_array2) {
180 return $array2; // Not array ($array1 is overwritten)
183 $keys_all = array_merge(array_keys($array1), array_keys($array2));
184 if ($sort_keys) sort($keys_all, SORT_STRING);
187 foreach($keys_all as $key) {
188 $isset1 = isset($array1[$key]);
189 $isset2 = isset($array2[$key]);
190 if ($isset1 && $isset2) {
192 $result[$key] = array_merge_leaves($array1[$key], $array2[$key], $sort_keys);
193 } else if ($isset1) {
194 $result[$key] = & $array1[$key];
196 $result[$key] = & $array2[$key];
202 // An array-leaves to a flat array
203 function array_flat_leaves($array, $unique = TRUE)
205 if (! is_array($array)) return $array;
208 foreach(array_keys($array) as $key) {
209 if (is_array($array[$key])) {
211 foreach(array_flat_leaves($array[$key]) as $_value) {
215 $tmp[] = & $array[$key];
219 return $unique ? array_values(array_unique($tmp)) : $tmp;
222 // $array['something'] => $array['wanted']
223 function array_rename_keys(& $array, $keys = array('from' => 'to'), $force = FALSE, $default = '')
225 if (! is_array($array) || ! is_array($keys)) return FALSE;
227 // Nondestructive test
229 foreach(array_keys($keys) as $from) {
230 if (! isset($array[$from])) {
236 foreach($keys as $from => $to) {
237 if ($from === $to) continue;
238 if (! $force || isset($array[$from])) {
239 $array[$to] = & $array[$from];
240 unset($array[$from]);
242 $array[$to] = $default;
249 // Remove redundant values from array()
250 function array_unique_recursive($array = array())
252 if (! is_array($array)) return $array;
255 foreach($array as $key => $value){
256 if (is_array($value)) {
257 $array[$key] = array_unique_recursive($value);
259 if (isset($tmp[$value])) {
271 // ---------------------
272 // Part One : Checker
274 // Rough implementation of globbing
276 // USAGE: $regex = '/^' . generate_glob_regex('*.txt', '/') . '$/i';
278 function generate_glob_regex($string = '', $divider = '/')
280 static $from = array(
283 // 22 => '[', // Maybe cause regex compilation error (e.g. '[]')
299 if (! is_string($string)) return '';
301 $string = str_replace($from, $mid, $string); // Hide
302 $string = preg_quote($string, $divider);
303 $string = str_replace($mid, $to, $string); // Unhide
308 // Generate host (FQDN, IPv4, ...) regex
309 // 'localhost' : Matches with 'localhost' only
310 // 'example.org' : Matches with 'example.org' only (See host_normalize() about 'www')
311 // '.example.org' : Matches with ALL FQDN ended with '.example.org'
312 // '*.example.org' : Almost the same of '.example.org' except 'www.example.org'
313 // '10.20.30.40' : Matches with IPv4 address '10.20.30.40' only
314 // [TODO] '192.' : Matches with all IPv4 hosts started with '192.'
315 // TODO: IPv4, CIDR?, IPv6
316 function generate_host_regex($string = '', $divider = '/')
318 if (! is_string($string)) return '';
320 if (mb_strpos($string, '.') === FALSE)
321 return generate_glob_regex($string, $divider);
323 if (is_ip($string)) {
325 return generate_glob_regex($string, $divider);
328 $part = explode('.', $string, 2);
329 if ($part[0] == '') {
330 $part[0] = '(?:.*\.)?'; // And all related FQDN
331 } else if ($part[0] == '*') {
332 $part[0] = '.*\.'; // All subdomains/hosts only
334 return generate_glob_regex($string, $divider);
336 $part[1] = generate_glob_regex($part[1], $divider);
337 return implode('', $part);
341 // Rough hostname checker
343 // TODO: Strict digit, 0x, CIDR, IPv6
344 function is_ip($string = '')
346 if (preg_match('/^' .
347 '(?:[0-9]{1,3}\.){3}[0-9]{1,3}' . '|' .
348 '(?:[0-9]{1,3}\.){1,3}' . '$/',
350 return 4; // Seems IPv4(dot-decimal)
352 return 0; // Seems not IP
356 function get_blocklist($list = '')
360 if ($list === NULL) {
361 $regexes = NULL; // Unset
365 if (! isset($regexes)) {
367 if (file_exists(SPAM_INI_FILE)) {
368 $blocklist = array();
369 include(SPAM_INI_FILE);
370 // $blocklist['badhost'] = array(
371 // '*.blogspot.com', // Blog services's subdomains (only)
372 // 'IANA-examples' => '#^(?:.*\.)?example\.(?:com|net|org)$#',
374 if (isset($blocklist['list'])) {
375 $regexes['list'] = & $blocklist['list'];
378 $blocklist['list'] = array(
383 foreach(array_keys($blocklist['list']) as $_list) {
384 if (! isset($blocklist[$_list])) continue;
385 foreach ($blocklist[$_list] as $key => $value) {
386 if (is_array($value)) {
387 $regexes[$_list][$key] = array();
388 foreach($value as $_key => $_value) {
389 get_blocklist_add($regexes[$_list][$key], $_key, $_value);
392 get_blocklist_add($regexes[$_list], $key, $value);
395 unset($blocklist[$_list]);
401 return $regexes; // ALL
402 } else if (isset($regexes[$list])) {
403 return $regexes[$list];
409 // Subroutine of get_blocklist()
410 function get_blocklist_add(& $array, $key = 0, $value = '*.example.org')
412 if (is_string($key)) {
413 $array[$key] = & $value; // Treat $value as a regex
415 $array[$value] = '/^' . generate_host_regex($value, '/') . '$/i';
419 // Blocklist metrics: Separate $host, to $blocked and not blocked
420 function blocklist_distiller(& $hosts, $keys = array('goodhost', 'badhost'), $asap = FALSE)
422 if (! is_array($hosts)) $hosts = array($hosts);
423 if (! is_array($keys)) $keys = array($keys);
425 $list = get_blocklist('list');
428 foreach($keys as $key){
429 foreach (get_blocklist($key) as $label => $regex) {
430 if (is_array($regex)) {
431 foreach($regex as $_label => $_regex) {
432 $group = preg_grep($_regex, $hosts);
434 $hosts = array_diff($hosts, $group);
435 $blocked[$key][$label][$_label] = $group;
436 if ($asap && $list[$key]) break;
440 $group = preg_grep($regex, $hosts);
442 $hosts = array_diff($hosts, $group);
443 $blocked[$key][$label] = $group;
444 if ($asap && $list[$key]) break;
454 // ---------------------
457 // Default (enabled) methods and thresholds (for content insertion)
458 function check_uri_spam_method($times = 1, $t_area = 0, $rule = TRUE)
460 $times = intval($times);
461 $t_area = intval($t_area);
465 'quantity' => 8 * $times, // Allow N URIs
466 'non_uniqhost' => 3 * $times, // Allow N duped (and normalized) Hosts
467 //'non_uniquri'=> 3 * $times, // Allow N duped (and normalized) URIs
470 'area_anchor' => $t_area, // Using <a href> HTML tag
471 'area_bbcode' => $t_area, // Using [url] or [link] BBCode
472 //'uri_anchor' => $t_area, // URI inside <a href> HTML tag
473 //'uri_bbcode' => $t_area, // URI inside [url] or [link] BBCode
478 //'asap' => TRUE, // Quit or return As Soon As Possible
479 'uniqhost' => TRUE, // Show uniq host (at block notification mail)
480 'badhost' => TRUE, // Check badhost
486 // Remove non-$positive values
487 foreach (array_keys($positive) as $key) {
488 if ($positive[$key] < 0) unset($positive[$key]);
491 return $positive + $bool;
494 // Simple/fast spam check
495 function check_uri_spam($target = '', $method = array())
500 // Theme to do => Dummy, optional value, or optional array()
502 //'uniqhost' => TRUE,
503 //'non_uniqhost'=> 3,
504 //'non_uniquri' => 3,
506 //'area_anchor' => 0,
507 //'area_bbcode' => 0,
512 // Theme => Volume found (int)
515 // Flag. If someting defined here,
516 // one or more spam will be included
521 //'category' => array(
531 $sum = & $progress['sum'];
532 $is_spam = & $progress['is_spam'];
533 $progress['method'] = & $method; // Argument
534 $blocked = & $progress['blocked'];
535 $hosts = & $progress['hosts'];
536 $asap = isset($method['asap']);
539 if (! is_array($method) || empty($method)) {
540 $method = check_uri_spam_method();
542 foreach(array_keys($method) as $key) {
543 if (! isset($sum[$key])) $sum[$key] = 0;
545 if (! isset($sum['quantity'])) $sum['quantity'] = 0;
547 if (is_array($target)) {
548 foreach($target as $str) {
549 if (! is_string($str)) continue;
551 $_progress = check_uri_spam($str, $method); // Recurse
554 $_sum = & $_progress['sum'];
555 foreach (array_keys($_sum) as $key) {
556 if (! isset($sum[$key])) {
557 $sum[$key] = & $_sum[$key];
559 $sum[$key] += $_sum[$key];
564 $_is_spam = & $_progress['is_spam'];
565 foreach (array_keys($_is_spam) as $key) {
566 $is_spam[$key] = TRUE;
569 if ($asap && $is_spam) break;
572 $blocked = array_merge_leaves($blocked, $_progress['blocked'], FALSE);
573 $hosts = array_merge_leaves($hosts, $_progress['hosts'], FALSE);
577 $blocked = array_unique_recursive($blocked);
578 $hosts = array_unique_recursive($hosts);
580 // Recount $sum['badhost']
581 $sum['badhost'] = array_count_leaves($blocked);
586 // Area: There's HTML anchor tag
587 if ((! $asap || ! $is_spam) && isset($method['area_anchor'])) {
588 $key = 'area_anchor';
589 $_asap = isset($method['asap']) ? array('asap' => TRUE) : array();
590 $result = area_pickup($target, array($key => TRUE) + $_asap);
592 $sum[$key] = $result[$key];
593 if (isset($method[$key]) && $sum[$key] > $method[$key]) {
594 $is_spam[$key] = TRUE;
599 // Area: There's 'BBCode' linking tag
600 if ((! $asap || ! $is_spam) && isset($method['area_bbcode'])) {
601 $key = 'area_bbcode';
602 $_asap = isset($method['asap']) ? array('asap' => TRUE) : array();
603 $result = area_pickup($target, array($key => TRUE) + $_asap);
605 $sum[$key] = $result[$key];
606 if (isset($method[$key]) && $sum[$key] > $method[$key]) {
607 $is_spam[$key] = TRUE;
613 if ($asap && $is_spam) return $progress;
616 $pickups = uri_pickup_normalize(spam_uri_pickup($target, $method));
619 if (empty($pickups)) return $progress;
621 // URI: Check quantity
622 $sum['quantity'] += count($pickups);
624 if ((! $asap || ! $is_spam) && isset($method['quantity']) &&
625 $sum['quantity'] > $method['quantity']) {
626 $is_spam['quantity'] = TRUE;
629 // URI: used inside HTML anchor tag pair
630 if ((! $asap || ! $is_spam) && isset($method['uri_anchor'])) {
632 foreach($pickups as $pickup) {
633 if (isset($pickup['area'][$key])) {
634 $sum[$key] += $pickup['area'][$key];
635 if(isset($method[$key]) &&
636 $sum[$key] > $method[$key]) {
637 $is_spam[$key] = TRUE;
638 if ($asap && $is_spam) break;
640 if ($asap && $is_spam) break;
645 // URI: used inside 'BBCode' pair
646 if ((! $asap || ! $is_spam) && isset($method['uri_bbcode'])) {
648 foreach($pickups as $pickup) {
649 if (isset($pickup['area'][$key])) {
650 $sum[$key] += $pickup['area'][$key];
651 if(isset($method[$key]) &&
652 $sum[$key] > $method[$key]) {
653 $is_spam[$key] = TRUE;
654 if ($asap && $is_spam) break;
656 if ($asap && $is_spam) break;
661 // URI: Uniqueness (and removing non-uniques)
662 if ((! $asap || ! $is_spam) && isset($method['non_uniquri'])) {
665 foreach (array_keys($pickups) as $key) {
666 $uris[$key] = uri_pickup_implode($pickups[$key]);
668 $count = count($uris);
669 $uris = array_unique($uris);
670 $sum['non_uniquri'] += $count - count($uris);
671 if ($sum['non_uniquri'] > $method['non_uniquri']) {
672 $is_spam['non_uniquri'] = TRUE;
674 if (! $asap || ! $is_spam) {
675 foreach (array_diff(array_keys($pickups),
676 array_keys($uris)) as $remove) {
677 unset($pickups[$remove]);
684 if ($asap && $is_spam) return $progress;
686 // Host: Uniqueness (uniq / non-uniq)
687 foreach ($pickups as $pickup) $hosts[] = & $pickup['host'];
688 $hosts = array_unique($hosts);
689 if (isset($sum['uniqhost'])) $sum['uniqhost'] += count($hosts);
690 if ((! $asap || ! $is_spam) && isset($method['non_uniqhost'])) {
691 $sum['non_uniqhost'] = $sum['quantity'] - $sum['uniqhost'];
692 if ($sum['non_uniqhost'] > $method['non_uniqhost']) {
693 $is_spam['non_uniqhost'] = TRUE;
698 if ($asap && $is_spam) return $progress;
700 // URI: Bad host (Separate good/bad hosts from $hosts)
701 if ((! $asap || ! $is_spam) && isset($method['badhost'])) {
704 $list = get_blocklist('list');
705 $blocked = blocklist_distiller($hosts, array_keys($list), $asap);
706 foreach($list as $key=>$type){
707 if (! $type) unset($blocked[$key]); // Ignore goodhost etc
711 if (! empty($blocked)) $is_spam['badhost'] = TRUE;
717 // ---------------------
720 // Summarize $progress (blocked only)
721 function summarize_spam_progress($progress = array(), $blockedonly = FALSE)
724 $tmp = array_keys($progress['is_spam']);
727 $method = & $progress['method'];
728 if (isset($progress['sum'])) {
729 foreach ($progress['sum'] as $key => $value) {
730 if (isset($method[$key]) && $value) {
731 $tmp[] = $key . '(' . $value . ')';
737 return implode(', ', $tmp);
740 function summarize_detail_badhost($progress = array())
742 if (! isset($progress['blocked']) || empty($progress['blocked'])) return '';
746 foreach($progress['blocked'] as $list => $lvalue) {
747 foreach($lvalue as $group => $gvalue) {
748 $flat = implode(', ', array_flat_leaves($gvalue));
749 if ($flat === $group) {
750 $blocked[$list][] = $flat;
752 $blocked[$list][$group] = $flat;
758 // From: 'A-1' => array('ie.to')
759 // To: 'A-1' => 'ie.to'
760 foreach($blocked as $list => $lvalue) {
761 if (is_array($lvalue) &&
762 count($lvalue) == 1 &&
763 is_numeric(key($lvalue))) {
764 $blocked[$list] = current($lvalue);
768 return var_export_shrink($blocked, TRUE, TRUE);
771 function summarize_detail_newtral($progress = array())
773 if (! isset($progress['hosts']) ||
774 ! is_array($progress['hosts']) ||
775 empty($progress['hosts'])) return '';
777 // Generate a responsible $trie
779 foreach($progress['hosts'] as $value) {
780 // 'A.foo.bar.example.com'
781 $resp = whois_responsibility($value); // 'example.com'
783 // One or more test, or do nothing here
784 $resp = strval($value);
787 $rest = rtrim(substr($value, 0, - strlen($resp)), '.'); // 'A.foo.bar'
789 $trie = array_merge_leaves($trie, array($resp => array($rest => NULL)), FALSE);
792 // Format: var_export_shrink() -like output
794 ksort_by_domain($trie);
795 foreach(array_keys($trie) as $key) {
796 ksort_by_domain($trie[$key]);
797 if (count($trie[$key]) == 1 && key($trie[$key]) == '') {
798 // Just one 'responsibility.example.com'
799 $result[] = ' \'' . $key . '\',';
801 // One subdomain-or-host, or several ones
803 foreach(array_keys($trie[$key]) as $sub) {
807 $subs[] = $sub . '.' . $key;
810 $result[] = ' \'' . $key . '\' => \'' . implode(', ', $subs) . '\',';
816 implode("\n", $result) . "\n" .
821 // Check responsibility-root of the FQDN
822 // 'foo.bar.example.com' => 'example.com' (.com has the last whois for it)
823 // 'foo.bar.example.au' => 'example.au' (.au has the last whois for it)
824 // 'foo.bar.example.edu.au' => 'example.edu.au' (.edu.au has the last whois for it)
825 // 'foo.bar.example.act.edu.au' => 'example.act.edu.au' (.act.edu.au has the last whois for it)
826 function whois_responsibility($fqdn = 'foo.bar.example.com', $parent = FALSE, $implicit = TRUE)
830 if ($fqdn === NULL) {
831 $domain = NULL; // Unset
834 if (! is_string($fqdn)) return '';
836 if (is_ip($fqdn)) return $fqdn;
838 if (! isset($domain)) {
840 if (file_exists(DOMAIN_INI_FILE)) {
841 include(DOMAIN_INI_FILE); // Set
846 $dcursor = & $domain;
847 $array = array_reverse(explode('.', $fqdn));
850 if (! isset($array[$i])) break;
851 $acursor = $array[$i];
852 if (is_array($dcursor) && isset($dcursor[$acursor])) {
853 $result[] = & $array[$i];
854 $dcursor = & $dcursor[$acursor];
856 if (! $parent && isset($acursor)) {
857 $result[] = & $array[$i]; // Whois servers must know this subdomain
864 // Implicit responsibility: Top-Level-Domains must not be yours
865 // 'bar.foo.something' => 'foo.something'
866 if ($implicit && count($result) == 1 && count($array) > 1) {
867 $result[] = & $array[1];
870 return $result ? implode('.', array_reverse($result)) : '';
874 // ---------------------
878 function spam_dispose()
881 whois_responsibility(NULL);
884 // Common bahavior for blocking
885 // NOTE: Call this function from various blocking feature, to disgueise the reason 'why blocked'
886 function spam_exit($mode = '', $data = array())
895 echo('<pre>' . "\n");
896 echo htmlspecialchars(var_export($data, TRUE));
897 echo('</pre>' . "\n");
901 if ($exit) exit; // Force exit
905 // ---------------------
909 // Simple/fast spam filter ($target: 'a string' or an array())
910 function pkwk_spamfilter($action, $page, $target = array('title' => ''), $method = array(), $exitmode = '')
912 $progress = check_uri_spam($target, $method);
914 if (empty($progress['is_spam'])) {
918 // TODO: detect encoding from $target for mbstring functions
920 // foreach(array_keys($target) as $key) {
921 // $tmp[strings($key, 0, FALSE, TRUE)] = strings($target[$key], 0, FALSE, TRUE); // Removing "\0" etc
925 pkwk_spamnotify($action, $page, $target, $progress, $method);
926 spam_exit($exitmode, $progress);
930 // ---------------------
933 // Mail to administrator(s)
934 function pkwk_spamnotify($action, $page, $target = array('title' => ''), $progress = array(), $method = array())
936 global $notify, $notify_subject;
938 if (! $notify) return;
940 $asap = isset($method['asap']);
942 $summary['ACTION'] = 'Blocked by: ' . summarize_spam_progress($progress, TRUE);
944 $summary['METRICS'] = summarize_spam_progress($progress);
947 $tmp = summarize_detail_badhost($progress);
948 if ($tmp != '') $summary['DETAIL_BADHOST'] = $tmp;
950 $tmp = summarize_detail_newtral($progress);
951 if (! $asap && $tmp != '') $summary['DETAIL_NEUTRAL_HOST'] = $tmp;
953 $summary['COMMENT'] = $action;
954 $summary['PAGE'] = '[blocked] ' . (is_pagename($page) ? $page : '');
955 $summary['URI'] = get_script_uri() . '?' . rawurlencode($page);
956 $summary['USER_AGENT'] = TRUE;
957 $summary['REMOTE_ADDR'] = TRUE;
958 pkwk_mail_notify($notify_subject, var_export($target, TRUE), $summary, TRUE);