OSDN Git Service

Ignorance of 'quantity'/'non_uniqXXX'/etc checks for 'goodhost' (kindly commented...
[pukiwiki/pukiwiki_sandbox.git] / spam / spam.php
1 <?php
2 // $Id: spam.php,v 1.202 2007/08/18 09:10:58 henoheno Exp $
3 // Copyright (C) 2006-2007 PukiWiki Developers Team
4 // License: GPL v2 or (at your option) any later version
5 //
6 // Functions for Concept-work of spam-uri metrics
7 //
8 // (PHP 4 >= 4.3.0): preg_match_all(PREG_OFFSET_CAPTURE): $method['uri_XXX'] related feature
9
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');
12
13 // ---------------------
14 // Compat etc
15
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";
20         }
21 }
22
23 // (PHP 4 >= 4.2.0): preg_grep() enables invert option
24 function preg_grep_invert($pattern = '//', $input = array())
25 {
26         static $invert;
27         if (! isset($invert)) $invert = defined('PREG_GREP_INVERT');
28
29         if ($invert) {
30                 return preg_grep($pattern, $input, PREG_GREP_INVERT);
31         } else {
32                 $result = preg_grep($pattern, $input);
33                 if ($result) {
34                         return array_diff($input, preg_grep($pattern, $input));
35                 } else {
36                         return $input;
37                 }
38         }
39 }
40
41
42 // ---------------------
43 // Utilities
44
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)
48 {
49         $result = var_export($expression, TRUE);
50
51         $result = preg_replace(
52                 // Remove a newline and spaces
53                 '# => \n *array \(#', ' => array (',
54                 $result
55         );
56
57         if ($ignore_numeric_keys) {
58                 $result =preg_replace(
59                         // Remove numeric keys
60                         '#^( *)[0-9]+ => #m', '$1',
61                         $result
62                 );
63         }
64
65         if ($return) {
66                 return $result;
67         } else {
68                 echo   $result;
69                 return NULL;
70         }
71 }
72
73 // Reverse $string with specified delimiter
74 function delimiter_reverse($string = 'foo.bar.example.com', $from_delim = '.', $to_delim = '.')
75 {
76         if (! is_string($string) || ! is_string($from_delim) || ! is_string($to_delim))
77                 return $string;
78
79         // com.example.bar.foo
80         return implode($to_delim, array_reverse(explode($from_delim, $string)));
81 }
82
83 // ksort() by domain
84 function ksort_by_domain(& $array)
85 {
86         $sort = array();
87         foreach(array_keys($array) as $key) {
88                 $sort[delimiter_reverse($key)] = $key;
89         }
90         ksort($sort, SORT_STRING);
91         $result = array();
92         foreach($sort as $key) {
93                 $result[$key] = & $array[$key];
94         }
95         $array = $result;
96 }
97
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
102 // References:
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)
108 {
109         // String only
110         $binary = (is_array($binary) || $binary === TRUE) ? '' : strval($binary);
111
112         $regex = $ignore_space ?
113                 '[^[:graph:] \t\n]+' :          // Remove "\0" etc, and readable spaces
114                 '[^[:graph:][:space:]]+';       // Preserve readable spaces if possible
115
116         $binary = $multibyte ?
117                 mb_ereg_replace($regex,           "\n",  $binary) :
118                 preg_replace('/' . $regex . '/s', "\n",  $binary);
119
120         if ($ignore_space) {
121                 $binary = preg_replace(
122                         array(
123                                 '/[ \t]{2,}/',
124                                 '/^[ \t]/m',
125                                 '/[ \t]$/m',
126                         ),
127                         array(
128                                 ' ',
129                                 '',
130                                 ''
131                         ),
132                          $binary);
133         }
134
135         if ($min_len > 1) {
136                 // The last character seems "\n" or not
137                 $br = (! empty($binary) && $binary[strlen($binary) - 1] == "\n") ? "\n" : '';
138
139                 $min_len = min(1024, intval($min_len));
140                 $regex = '/^.{' . $min_len . ',}/S';
141                 $binary = implode("\n", preg_grep($regex, explode("\n", $binary))) . $br;
142         }
143
144         return $binary;
145 }
146
147
148 // ---------------------
149 // Utilities: Arrays
150
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)
153 {
154         if (! is_array($array) || (empty($array) && $count_empty)) return 1;
155
156         // Recurse
157         $count = 0;
158         foreach ($array as $part) {
159                 $count += array_count_leaves($part, $count_empty);
160         }
161         return $count;
162 }
163
164 // Merge two leaves
165 // Similar to PHP array_merge_leaves(), except strictly preserving keys as string
166 function array_merge_leaves($array1, $array2, $sort_keys = TRUE)
167 {
168         // Array(s) only 
169         $is_array1 = is_array($array1);
170         $is_array2 = is_array($array2);
171         if ($is_array1) {
172                 if ($is_array2) {
173                         ;       // Pass
174                 } else {
175                         return $array1;
176                 }
177         } else if ($is_array2) {
178                 return $array2;
179         } else {
180                 return $array2; // Not array ($array1 is overwritten)
181         }
182
183         $keys_all = array_merge(array_keys($array1), array_keys($array2));
184         if ($sort_keys) sort($keys_all, SORT_STRING);
185
186         $result = array();
187         foreach($keys_all as $key) {
188                 $isset1 = isset($array1[$key]);
189                 $isset2 = isset($array2[$key]);
190                 if ($isset1 && $isset2) {
191                         // Recurse
192                         $result[$key] = array_merge_leaves($array1[$key], $array2[$key], $sort_keys);
193                 } else if ($isset1) {
194                         $result[$key] = & $array1[$key];
195                 } else {
196                         $result[$key] = & $array2[$key];
197                 }
198         }
199         return $result;
200 }
201
202 // An array-leaves to a flat array
203 function array_flat_leaves($array, $unique = TRUE)
204 {
205         if (! is_array($array)) return $array;
206
207         $tmp = array();
208         foreach(array_keys($array) as $key) {
209                 if (is_array($array[$key])) {
210                         // Recurse
211                         foreach(array_flat_leaves($array[$key]) as $_value) {
212                                 $tmp[] = $_value;
213                         }
214                 } else {
215                         $tmp[] = & $array[$key];
216                 }
217         }
218
219         return $unique ? array_values(array_unique($tmp)) : $tmp;
220 }
221
222 // $array['something'] => $array['wanted']
223 function array_rename_keys(& $array, $keys = array('from' => 'to'), $force = FALSE, $default = '')
224 {
225         if (! is_array($array) || ! is_array($keys)) return FALSE;
226
227         // Nondestructive test
228         if (! $force) {
229                 foreach(array_keys($keys) as $from) {
230                         if (! isset($array[$from])) {
231                                 return FALSE;
232                         }
233                 }
234         }
235
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]);
241                 } else  {
242                         $array[$to] = $default;
243                 }
244         }
245
246         return TRUE;
247 }
248
249 // Remove redundant values from array()
250 function array_unique_recursive($array = array())
251 {
252         if (! is_array($array)) return $array;
253
254         $tmp = array();
255         foreach($array as $key => $value){
256                 if (is_array($value)) {
257                         $array[$key] = array_unique_recursive($value);
258                 } else {
259                         if (isset($tmp[$value])) {
260                                 unset($array[$key]);
261                         } else {
262                                 $tmp[$value] = TRUE;
263                         }
264                 }
265         }
266
267         return $array;
268 }
269
270
271 // ---------------------
272 // Part One : Checker
273
274 // Rough implementation of globbing
275 //
276 // USAGE: $regex = '/^' . generate_glob_regex('*.txt', '/') . '$/i';
277 //
278 function generate_glob_regex($string = '', $divider = '/')
279 {
280         static $from = array(
281                          1 => '*',
282                         11 => '?',
283         //              22 => '[',      // Maybe cause regex compilation error (e.g. '[]')
284         //              23 => ']',      //
285                 );
286         static $mid = array(
287                          1 => '_AST_',
288                         11 => '_QUE_',
289         //              22 => '_RBR_',
290         //              23 => '_LBR_',
291                 );
292         static $to = array(
293                          1 => '.*',
294                         11 => '.',
295         //              22 => '[',
296         //              23 => ']',
297                 );
298
299         if (! is_string($string)) return '';
300
301         $string = str_replace($from, $mid, $string); // Hide
302         $string = preg_quote($string, $divider);
303         $string = str_replace($mid, $to, $string);   // Unhide
304
305         return $string;
306 }
307
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 = '/')
317 {
318         if (! is_string($string)) return '';
319
320         if (mb_strpos($string, '.') === FALSE)
321                 return generate_glob_regex($string, $divider);
322
323         if (is_ip($string)) {
324                 // IPv4
325                 return generate_glob_regex($string, $divider);
326         } else {
327                 // FQDN or something
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
333                 } else {
334                         return generate_glob_regex($string, $divider);
335                 }
336                 $part[1] = generate_glob_regex($part[1], $divider);
337                 return implode('', $part);
338         }
339 }
340
341 // Rough hostname checker
342 // [OK] 192.168.
343 // TODO: Strict digit, 0x, CIDR, IPv6
344 function is_ip($string = '')
345 {
346         if (preg_match('/^' .
347                 '(?:[0-9]{1,3}\.){3}[0-9]{1,3}' . '|' .
348                 '(?:[0-9]{1,3}\.){1,3}' . '$/',
349                 $string)) {
350                 return 4;       // Seems IPv4(dot-decimal)
351         } else {
352                 return 0;       // Seems not IP
353         }
354 }
355
356 function get_blocklist($list = '')
357 {
358         static $regexes;
359
360         if ($list === NULL) {
361                 $regexes = NULL;        // Unset
362                 return array();
363         }
364
365         if (! isset($regexes)) {
366                 $regexes = array();
367                 if (file_exists(SPAM_INI_FILE)) {
368                         $blocklist = array();
369                         include(SPAM_INI_FILE);
370                         //      $blocklist['list'] = array(
371                         //      //'goodhost' => FALSE;
372                         //      'badhost' => TRUE;
373                         // );
374                         //      $blocklist['badhost'] = array(
375                         //              '*.blogspot.com',       // Blog services's subdomains (only)
376                         //              'IANA-examples' => '#^(?:.*\.)?example\.(?:com|net|org)$#',
377                         //      );
378                         foreach(array('pre', 'list') as $special) {
379                                 if (! isset($blocklist[$special])) continue;
380                                 $regexes[$special] = $blocklist[$special];
381                                 foreach(array_keys($blocklist[$special]) as $_list) {
382                                         if (! isset($blocklist[$_list])) continue;
383                                         foreach ($blocklist[$_list] as $key => $value) {
384                                                 if (is_array($value)) {
385                                                         $regexes[$_list][$key] = array();
386                                                         foreach($value as $_key => $_value) {
387                                                                 get_blocklist_add($regexes[$_list][$key], $_key, $_value);
388                                                         }
389                                                 } else {
390                                                         get_blocklist_add($regexes[$_list], $key, $value);
391                                                 }
392                                         }
393                                         unset($blocklist[$_list]);
394                                 }
395                         }
396                 }
397         }
398
399         if ($list === '') {
400                 return $regexes;        // ALL
401         } else if (isset($regexes[$list])) {
402                 return $regexes[$list];
403         } else {
404                 return array();
405         }
406 }
407
408 // Subroutine of get_blocklist()
409 function get_blocklist_add(& $array, $key = 0, $value = '*.example.org')
410 {
411         if (is_string($key)) {
412                 $array[$key] = & $value; // Treat $value as a regex
413         } else {
414                 $array[$value] = '/^' . generate_host_regex($value, '/') . '$/i';
415         }
416 }
417
418 // Blocklist metrics: Separate $host, to $blocked and not blocked
419 function blocklist_distiller(& $hosts, $keys = array('goodhost', 'badhost'), $asap = FALSE)
420 {
421         if (! is_array($hosts)) $hosts = array($hosts);
422         if (! is_array($keys))  $keys  = array($keys);
423
424         $list = get_blocklist('list');
425         $blocked = array();
426
427         foreach($keys as $key){
428                 foreach (get_blocklist($key) as $label => $regex) {
429                         if (is_array($regex)) {
430                                 foreach($regex as $_label => $_regex) {
431                                         $group = preg_grep($_regex, $hosts);
432                                         if ($group) {
433                                                 $hosts = array_diff($hosts, $group);
434                                                 $blocked[$key][$label][$_label] = $group;
435                                                 if ($asap && $list[$key]) break;
436                                         }
437                                 }
438                         } else {
439                                 $group = preg_grep($regex, $hosts);
440                                 if ($group) {
441                                         $hosts = array_diff($hosts, $group);
442                                         $blocked[$key][$label] = $group;
443                                         if ($asap && $list[$key]) break;
444                                 }
445                         }
446                 }
447         }
448
449         return $blocked;
450 }
451
452
453 // ---------------------
454
455
456 // Default (enabled) methods and thresholds (for content insertion)
457 function check_uri_spam_method($times = 1, $t_area = 0, $rule = TRUE)
458 {
459         $times  = intval($times);
460         $t_area = intval($t_area);
461
462         $positive = array(
463                 // Thresholds
464                 'quantity'     =>  8 * $times,  // Allow N URIs
465                 'non_uniqhost' =>  3 * $times,  // Allow N duped (and normalized) Hosts
466                 //'non_uniquri'=>  3 * $times,  // Allow N duped (and normalized) URIs
467
468                 // Areas
469                 'area_anchor'  => $t_area,      // Using <a href> HTML tag
470                 'area_bbcode'  => $t_area,      // Using [url] or [link] BBCode
471                 //'uri_anchor' => $t_area,      // URI inside <a href> HTML tag
472                 //'uri_bbcode' => $t_area,      // URI inside [url] or [link] BBCode
473         );
474         if ($rule) {
475                 $bool = array(
476                         // Rules
477                         //'asap'   => TRUE,     // Quit or return As Soon As Possible
478                         'uniqhost' => TRUE,     // Show uniq host (at block notification mail)
479                         'badhost'  => TRUE,     // Check badhost
480                 );
481         } else {
482                 $bool = array();
483         }
484
485         // Remove non-$positive values
486         foreach (array_keys($positive) as $key) {
487                 if ($positive[$key] < 0) unset($positive[$key]);
488         }
489
490         return $positive + $bool;
491 }
492
493 // Simple/fast spam check
494 function check_uri_spam($target = '', $method = array())
495 {
496         // Return value
497         $progress = array(
498                 'method'  => array(
499                         // Theme to do  => Dummy, optional value, or optional array()
500                         //'quantity'    => 8,
501                         //'uniqhost'    => TRUE,
502                         //'non_uniqhost'=> 3,
503                         //'non_uniquri' => 3,
504                         //'badhost'     => TRUE,
505                         //'area_anchor' => 0,
506                         //'area_bbcode' => 0,
507                         //'uri_anchor'  => 0,
508                         //'uri_bbcode'  => 0,
509                 ),
510                 'sum' => array(
511                         // Theme        => Volume found (int)
512                 ),
513                 'is_spam' => array(
514                         // Flag. If someting defined here,
515                         // one or more spam will be included
516                         // in this report
517                 ),
518                 'blocked' => array(
519                         // Hosts blocked
520                         //'category' => array(
521                         //      'host',
522                         //)
523                 ),
524                 'hosts' => array(
525                         // Hosts not blocked
526                 ),
527         );
528
529         // ----------------------------------------
530         // Aliases
531
532         $sum     = & $progress['sum'];
533         $is_spam = & $progress['is_spam'];
534         $progress['method'] = & $method;        // Argument
535         $blocked = & $progress['blocked'];
536         $hosts   = & $progress['hosts'];
537         $asap    = isset($method['asap']);
538
539         // ----------------------------------------
540         // Init
541
542         if (! is_array($method) || empty($method)) {
543                 $method = check_uri_spam_method();
544         }
545         foreach(array_keys($method) as $key) {
546                 if (! isset($sum[$key])) $sum[$key] = 0;
547         }
548         if (! isset($sum['quantity'])) $sum['quantity'] = 0;
549
550         // ----------------------------------------
551         // Recurse
552
553         if (is_array($target)) {
554                 foreach($target as $str) {
555                         if (! is_string($str)) continue;
556
557                         $_progress = check_uri_spam($str, $method);     // Recurse
558
559                         // Merge $sum
560                         $_sum = & $_progress['sum'];
561                         foreach (array_keys($_sum) as $key) {
562                                 if (! isset($sum[$key])) {
563                                         $sum[$key] = & $_sum[$key];
564                                 } else {
565                                         $sum[$key] += $_sum[$key];
566                                 }
567                         }
568
569                         // Merge $is_spam
570                         $_is_spam = & $_progress['is_spam'];
571                         foreach (array_keys($_is_spam) as $key) {
572                                 $is_spam[$key] = TRUE;
573                                 if ($asap) break;
574                         }
575                         if ($asap && $is_spam) break;
576
577                         // Merge only
578                         $blocked = array_merge_leaves($blocked, $_progress['blocked'], FALSE);
579                         $hosts   = array_merge_leaves($hosts,   $_progress['hosts'],   FALSE);
580                 }
581
582                 // Unique values
583                 $blocked = array_unique_recursive($blocked);
584                 $hosts   = array_unique_recursive($hosts);
585
586                 // Recount $sum['badhost']
587                 $sum['badhost'] = array_count_leaves($blocked);
588
589                 return $progress;
590         }
591
592         // ----------------------------------------
593         // Area measure
594
595         // Area: There's HTML anchor tag
596         if ((! $asap || ! $is_spam) && isset($method['area_anchor'])) {
597                 $key = 'area_anchor';
598                 $_asap = isset($method['asap']) ? array('asap' => TRUE) : array();
599                 $result = area_pickup($target, array($key => TRUE) + $_asap);
600                 if ($result) {
601                         $sum[$key] = $result[$key];
602                         if (isset($method[$key]) && $sum[$key] > $method[$key]) {
603                                 $is_spam[$key] = TRUE;
604                         }
605                 }
606         }
607
608         // Area: There's 'BBCode' linking tag
609         if ((! $asap || ! $is_spam) && isset($method['area_bbcode'])) {
610                 $key = 'area_bbcode';
611                 $_asap = isset($method['asap']) ? array('asap' => TRUE) : array();
612                 $result = area_pickup($target, array($key => TRUE) + $_asap);
613                 if ($result) {
614                         $sum[$key] = $result[$key];
615                         if (isset($method[$key]) && $sum[$key] > $method[$key]) {
616                                 $is_spam[$key] = TRUE;
617                         }
618                 }
619         }
620
621         // Return if ...
622         if ($asap && $is_spam) return $progress;
623
624         // ----------------------------------------
625         // URI: Pickup
626
627         $pickups = uri_pickup_normalize(spam_uri_pickup($target, $method));
628         $hosts = array();
629         foreach ($pickups as $key => $pickup) {
630                 $hosts[$key] = & $pickup['host'];
631         }
632
633         // Return if ...
634         if (empty($pickups)) return $progress;
635
636         // ----------------------------------------
637         // URI: Bad host <pre-filter> (Separate good/bad hosts from $hosts)
638
639         if ((! $asap || ! $is_spam) && isset($method['badhost'])) {
640                 $list    = get_blocklist('pre');
641                 $blocked = blocklist_distiller($hosts, array_keys($list), $asap);
642                 foreach($list as $key=>$type){
643                         if (! $type) unset($blocked[$key]); // Ignore goodhost etc
644                 }
645                 unset($list);
646                 if (! empty($blocked)) $is_spam['badhost'] = TRUE;
647         }
648
649         // Return if ...
650         if ($asap && $is_spam) return $progress;
651
652         // Remove blocked from $pickups
653         foreach(array_keys($pickups) as $key) {
654                 if (! isset($hosts[$key])) {
655                         unset($pickups[$key]);
656                 }
657         }
658
659         // ----------------------------------------
660         // URI: Check quantity
661
662         $sum['quantity'] += count($pickups);
663                 // URI quantity
664         if ((! $asap || ! $is_spam) && isset($method['quantity']) &&
665                 $sum['quantity'] > $method['quantity']) {
666                 $is_spam['quantity'] = TRUE;
667         }
668
669         // ----------------------------------------
670         // URI: used inside HTML anchor tag pair
671
672         if ((! $asap || ! $is_spam) && isset($method['uri_anchor'])) {
673                 $key = 'uri_anchor';
674                 foreach($pickups as $pickup) {
675                         if (isset($pickup['area'][$key])) {
676                                 $sum[$key] += $pickup['area'][$key];
677                                 if(isset($method[$key]) &&
678                                         $sum[$key] > $method[$key]) {
679                                         $is_spam[$key] = TRUE;
680                                         if ($asap && $is_spam) break;
681                                 }
682                                 if ($asap && $is_spam) break;
683                         }
684                 }
685         }
686
687         // ----------------------------------------
688         // URI: used inside 'BBCode' pair
689
690         if ((! $asap || ! $is_spam) && isset($method['uri_bbcode'])) {
691                 $key = 'uri_bbcode';
692                 foreach($pickups as $pickup) {
693                         if (isset($pickup['area'][$key])) {
694                                 $sum[$key] += $pickup['area'][$key];
695                                 if(isset($method[$key]) &&
696                                         $sum[$key] > $method[$key]) {
697                                         $is_spam[$key] = TRUE;
698                                         if ($asap && $is_spam) break;
699                                 }
700                                 if ($asap && $is_spam) break;
701                         }
702                 }
703         }
704
705         // ----------------------------------------
706         // URI: Uniqueness (and removing non-uniques)
707
708         if ((! $asap || ! $is_spam) && isset($method['non_uniquri'])) {
709
710                 $uris = array();
711                 foreach (array_keys($pickups) as $key) {
712                         $uris[$key] = uri_pickup_implode($pickups[$key]);
713                 }
714                 $count = count($uris);
715                 $uris  = array_unique($uris);
716                 $sum['non_uniquri'] += $count - count($uris);
717                 if ($sum['non_uniquri'] > $method['non_uniquri']) {
718                         $is_spam['non_uniquri'] = TRUE;
719                 }
720                 if (! $asap || ! $is_spam) {
721                         foreach (array_diff(array_keys($pickups),
722                                 array_keys($uris)) as $remove) {
723                                 unset($pickups[$remove]);
724                         }
725                 }
726                 unset($uris);
727         }
728
729         // Return if ...
730         if ($asap && $is_spam) return $progress;
731
732         // ----------------------------------------
733         // Host: Uniqueness (uniq / non-uniq)
734
735         $hosts = array_unique($hosts);
736
737         if (isset($sum['uniqhost'])) $sum['uniqhost'] += count($hosts);
738         if ((! $asap || ! $is_spam) && isset($method['non_uniqhost'])) {
739                 $sum['non_uniqhost'] = $sum['quantity'] - $sum['uniqhost'];
740                 if ($sum['non_uniqhost'] > $method['non_uniqhost']) {
741                         $is_spam['non_uniqhost'] = TRUE;
742                 }
743         }
744
745         // Return if ...
746         if ($asap && $is_spam) return $progress;
747
748         // ----------------------------------------
749         // URI: Bad host (Separate good/bad hosts from $hosts)
750
751         if ((! $asap || ! $is_spam) && isset($method['badhost'])) {
752                 $list    = get_blocklist('list');
753                 $blocked = array_merge_leaves(
754                         $blocked,
755                         blocklist_distiller($hosts, array_keys($list), $asap),
756                         FALSE
757                 );
758                 foreach($list as $key=>$type){
759                         if (! $type) unset($blocked[$key]); // Ignore goodhost etc
760                 }
761                 unset($list);
762                 if (! empty($blocked)) $is_spam['badhost'] = TRUE;
763         }
764
765         // Return if ...
766         //if ($asap && $is_spam) return $progress;
767
768         // ----------------------------------------
769         // End
770
771         return $progress;
772 }
773
774 // ---------------------
775 // Reporting
776
777 // Summarize $progress (blocked only)
778 function summarize_spam_progress($progress = array(), $blockedonly = FALSE)
779 {
780         if ($blockedonly) {
781                 $tmp = array_keys($progress['is_spam']);
782         } else {
783                 $tmp = array();
784                 $method = & $progress['method'];
785                 if (isset($progress['sum'])) {
786                         foreach ($progress['sum'] as $key => $value) {
787                                 if (isset($method[$key]) && $value) {
788                                         $tmp[] = $key . '(' . $value . ')';
789                                 }
790                         }
791                 }
792         }
793
794         return implode(', ', $tmp);
795 }
796
797 function summarize_detail_badhost($progress = array())
798 {
799         if (! isset($progress['blocked']) || empty($progress['blocked'])) return '';
800
801         // Flat per group
802         $blocked = array();
803         foreach($progress['blocked'] as $list => $lvalue) {
804                 foreach($lvalue as $group => $gvalue) {
805                         $flat = implode(', ', array_flat_leaves($gvalue));
806                         if ($flat === $group) {
807                                 $blocked[$list][]       = $flat;
808                         } else {
809                                 $blocked[$list][$group] = $flat;
810                         }
811                 }
812         }
813
814         // Shrink per list
815         // From: 'A-1' => array('ie.to')
816         // To:   'A-1' => 'ie.to'
817         foreach($blocked as $list => $lvalue) {
818                 if (is_array($lvalue) &&
819                    count($lvalue) == 1 &&
820                    is_numeric(key($lvalue))) {
821                     $blocked[$list] = current($lvalue);
822                 }
823         }
824
825         return var_export_shrink($blocked, TRUE, TRUE);
826 }
827
828 function summarize_detail_newtral($progress = array())
829 {
830         if (! isset($progress['hosts'])    ||
831             ! is_array($progress['hosts']) ||
832             empty($progress['hosts'])) return '';
833
834         // Generate a responsible $trie
835         $trie = array();
836         foreach($progress['hosts'] as $value) {
837                 // 'A.foo.bar.example.com'
838                 $resp = whois_responsibility($value);   // 'example.com'
839                 if (empty($resp)) {
840                         // One or more test, or do nothing here
841                         $resp = strval($value);
842                         $rest = '';
843                 } else {
844                         $rest = rtrim(substr($value, 0, - strlen($resp)), '.'); // 'A.foo.bar'
845                 }
846                 $trie = array_merge_leaves($trie, array($resp => array($rest => NULL)), FALSE);
847         }
848
849         // Format: var_export_shrink() -like output
850         $result = array();
851         ksort_by_domain($trie);
852         foreach(array_keys($trie) as $key) {
853                 ksort_by_domain($trie[$key]);
854                 if (count($trie[$key]) == 1 && key($trie[$key]) == '') {
855                         // Just one 'responsibility.example.com'
856                         $result[] = '  \'' . $key . '\',';
857                 } else {
858                         // One subdomain-or-host, or several ones
859                         $subs = array();
860                         foreach(array_keys($trie[$key]) as $sub) {
861                                 if ($sub == '') {
862                                         $subs[] = $key;
863                                 } else {
864                                         $subs[] = $sub . '.' . $key;
865                                 }
866                         }
867                         $result[] = '  \'' . $key . '\' => \'' . implode(', ', $subs) . '\',';
868                 }
869                 unset($trie[$key]);
870         }
871         return
872                 'array (' . "\n" .
873                         implode("\n", $result) . "\n" .
874                 ')';
875 }
876
877
878 // Check responsibility-root of the FQDN
879 // 'foo.bar.example.com'        => 'example.com'        (.com        has the last whois for it)
880 // 'foo.bar.example.au'         => 'example.au'         (.au         has the last whois for it)
881 // 'foo.bar.example.edu.au'     => 'example.edu.au'     (.edu.au     has the last whois for it)
882 // 'foo.bar.example.act.edu.au' => 'example.act.edu.au' (.act.edu.au has the last whois for it)
883 function whois_responsibility($fqdn = 'foo.bar.example.com', $parent = FALSE, $implicit = TRUE)
884 {
885         static $domain;
886
887         if ($fqdn === NULL) {
888                 $domain = NULL; // Unset
889                 return '';
890         }
891         if (! is_string($fqdn)) return '';
892
893         if (is_ip($fqdn)) return $fqdn;
894
895         if (! isset($domain)) {
896                 $domain = array();
897                 if (file_exists(DOMAIN_INI_FILE)) {
898                         include(DOMAIN_INI_FILE);       // Set
899                 }
900         }
901
902         $result  = array();
903         $dcursor = & $domain;
904         $array   = array_reverse(explode('.', $fqdn));
905         $i = 0;
906         while(TRUE) {
907                 if (! isset($array[$i])) break;
908                 $acursor = $array[$i];
909                 if (is_array($dcursor) && isset($dcursor[$acursor])) {
910                         $result[] = & $array[$i];
911                         $dcursor  = & $dcursor[$acursor];
912                 } else {
913                         if (! $parent && isset($acursor)) {
914                                 $result[] = & $array[$i];       // Whois servers must know this subdomain
915                         }
916                         break;
917                 }
918                 ++$i;
919         }
920
921         // Implicit responsibility: Top-Level-Domains must not be yours
922         // 'bar.foo.something' => 'foo.something'
923         if ($implicit && count($result) == 1 && count($array) > 1) {
924                 $result[] = & $array[1];
925         }
926
927         return $result ? implode('.', array_reverse($result)) : '';
928 }
929
930
931 // ---------------------
932 // Exit
933
934 // Freeing memories
935 function spam_dispose()
936 {
937         get_blocklist(NULL);
938         whois_responsibility(NULL);
939 }
940
941 // Common bahavior for blocking
942 // NOTE: Call this function from various blocking feature, to disgueise the reason 'why blocked'
943 function spam_exit($mode = '', $data = array())
944 {
945         $exit = TRUE;
946
947         switch ($mode) {
948                 case '':
949                         echo("\n");
950                         break;
951                 case 'dump':
952                         echo('<pre>' . "\n");
953                         echo htmlspecialchars(var_export($data, TRUE));
954                         echo('</pre>' . "\n");
955                         break;
956         };
957
958         if ($exit) exit;        // Force exit
959 }
960
961
962 // ---------------------
963 // Simple filtering
964
965 // TODO: Record them
966 // Simple/fast spam filter ($target: 'a string' or an array())
967 function pkwk_spamfilter($action, $page, $target = array('title' => ''), $method = array(), $exitmode = '')
968 {
969         $progress = check_uri_spam($target, $method);
970
971         if (empty($progress['is_spam'])) {
972                 spam_dispose();
973         } else {
974
975 // TODO: detect encoding from $target for mbstring functions
976 //              $tmp = array();
977 //              foreach(array_keys($target) as $key) {
978 //                      $tmp[strings($key, 0, FALSE, TRUE)] = strings($target[$key], 0, FALSE, TRUE);   // Removing "\0" etc
979 //              }
980 //              $target = & $tmp;
981
982                 pkwk_spamnotify($action, $page, $target, $progress, $method);
983                 spam_exit($exitmode, $progress);
984         }
985 }
986
987 // ---------------------
988 // PukiWiki original
989
990 // Mail to administrator(s)
991 function pkwk_spamnotify($action, $page, $target = array('title' => ''), $progress = array(), $method = array())
992 {
993         global $notify, $notify_subject;
994
995         if (! $notify) return;
996
997         $asap = isset($method['asap']);
998
999         $summary['ACTION']  = 'Blocked by: ' . summarize_spam_progress($progress, TRUE);
1000         if (! $asap) {
1001                 $summary['METRICS'] = summarize_spam_progress($progress);
1002         }
1003
1004         $tmp = summarize_detail_badhost($progress);
1005         if ($tmp != '') $summary['DETAIL_BADHOST'] = $tmp;
1006
1007         $tmp = summarize_detail_newtral($progress);
1008         if (! $asap && $tmp != '') $summary['DETAIL_NEUTRAL_HOST'] = $tmp;
1009
1010         $summary['COMMENT'] = $action;
1011         $summary['PAGE']    = '[blocked] ' . (is_pagename($page) ? $page : '');
1012         $summary['URI']     = get_script_uri() . '?' . rawurlencode($page);
1013         $summary['USER_AGENT']  = TRUE;
1014         $summary['REMOTE_ADDR'] = TRUE;
1015         pkwk_mail_notify($notify_subject,  var_export($target, TRUE), $summary, TRUE);
1016 }
1017
1018 ?>