OSDN Git Service

e85ca0ec63ec117623e967451c80d8a5082157ed
[pukiwiki/pukiwiki_sandbox.git] / spam / spam.php
1 <?php
2 // $Id: spam.php,v 1.197 2007/07/03 14:51:07 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 // An array-leaves to a flat array
165 function array_flat_leaves($array, $unique = TRUE)
166 {
167         if (! is_array($array)) return $array;
168
169         $tmp = array();
170         foreach(array_keys($array) as $key) {
171                 if (is_array($array[$key])) {
172                         // Recurse
173                         foreach(array_flat_leaves($array[$key]) as $_value) {
174                                 $tmp[] = $_value;
175                         }
176                 } else {
177                         $tmp[] = & $array[$key];
178                 }
179         }
180
181         return $unique ? array_values(array_unique($tmp)) : $tmp;
182 }
183
184 // $array['something'] => $array['wanted']
185 function array_rename_keys(& $array, $keys = array('from' => 'to'), $force = FALSE, $default = '')
186 {
187         if (! is_array($array) || ! is_array($keys)) return FALSE;
188
189         // Nondestructive test
190         if (! $force)
191                 foreach(array_keys($keys) as $from)
192                         if (! isset($array[$from]))
193                                 return FALSE;
194
195         foreach($keys as $from => $to) {
196                 if ($from === $to) continue;
197                 if (! $force || isset($array[$from])) {
198                         $array[$to] = & $array[$from];
199                         unset($array[$from]);
200                 } else  {
201                         $array[$to] = $default;
202                 }
203         }
204
205         return TRUE;
206 }
207
208 // Remove redundant values from array()
209 function array_unique_recursive($array = array())
210 {
211         if (! is_array($array)) return $array;
212
213         $tmp = array();
214         foreach($array as $key => $value){
215                 if (is_array($value)) {
216                         $array[$key] = array_unique_recursive($value);
217                 } else {
218                         if (isset($tmp[$value])) {
219                                 unset($array[$key]);
220                         } else {
221                                 $tmp[$value] = TRUE;
222                         }
223                 }
224         }
225
226         return $array;
227 }
228
229
230 // ---------------------
231 // Part One : Checker
232
233 // Rough implementation of globbing
234 //
235 // USAGE: $regex = '/^' . generate_glob_regex('*.txt', '/') . '$/i';
236 //
237 function generate_glob_regex($string = '', $divider = '/')
238 {
239         static $from = array(
240                          1 => '*',
241                         11 => '?',
242         //              22 => '[',      // Maybe cause regex compilation error (e.g. '[]')
243         //              23 => ']',      //
244                 );
245         static $mid = array(
246                          1 => '_AST_',
247                         11 => '_QUE_',
248         //              22 => '_RBR_',
249         //              23 => '_LBR_',
250                 );
251         static $to = array(
252                          1 => '.*',
253                         11 => '.',
254         //              22 => '[',
255         //              23 => ']',
256                 );
257
258         if (! is_string($string)) return '';
259
260         $string = str_replace($from, $mid, $string); // Hide
261         $string = preg_quote($string, $divider);
262         $string = str_replace($mid, $to, $string);   // Unhide
263
264         return $string;
265 }
266
267 // Generate host (FQDN, IPv4, ...) regex
268 // 'localhost'     : Matches with 'localhost' only
269 // 'example.org'   : Matches with 'example.org' only (See host_normalize() about 'www')
270 // '.example.org'  : Matches with ALL FQDN ended with '.example.org'
271 // '*.example.org' : Almost the same of '.example.org' except 'www.example.org'
272 // '10.20.30.40'   : Matches with IPv4 address '10.20.30.40' only
273 // [TODO] '192.'   : Matches with all IPv4 hosts started with '192.'
274 // TODO: IPv4, CIDR?, IPv6
275 function generate_host_regex($string = '', $divider = '/')
276 {
277         if (! is_string($string)) return '';
278
279         if (mb_strpos($string, '.') === FALSE)
280                 return generate_glob_regex($string, $divider);
281
282         $result = '';
283         if (is_ip($string)) {
284                 // IPv4
285                 return generate_glob_regex($string, $divider);
286         } else {
287                 // FQDN or something
288                 $part = explode('.', $string, 2);
289                 if ($part[0] == '') {
290                         $part[0] = '(?:.*\.)?'; // And all related FQDN
291                 } else if ($part[0] == '*') {
292                         $part[0] = '.*\.';      // All subdomains/hosts only
293                 } else {
294                         return generate_glob_regex($string, $divider);
295                 }
296                 $part[1] = generate_glob_regex($part[1], $divider);
297                 return implode('', $part);
298         }
299 }
300
301 // Rough hostname checker
302 // [OK] 192.168.
303 // TODO: Strict digit, 0x, CIDR, IPv6
304 function is_ip($string = '')
305 {
306         if (preg_match('/^' .
307                 '(?:[0-9]{1,3}\.){3}[0-9]{1,3}' . '|' .
308                 '(?:[0-9]{1,3}\.){1,3}' . '$/',
309                 $string)) {
310                 return 4;       // Seems IPv4(dot-decimal)
311         } else {
312                 return 0;       // Seems not IP
313         }
314 }
315
316 function get_blocklist($list = '')
317 {
318         static $regexes;
319
320         if ($list === NULL) {
321                 $regexes = NULL;        // Unset
322                 return array();
323         }
324
325         if (! isset($regexes)) {
326                 $regexes = array();
327                 if (file_exists(SPAM_INI_FILE)) {
328                         $blocklist = array();
329                         include(SPAM_INI_FILE);
330                         //      $blocklist['badhost'] = array(
331                         //              '*.blogspot.com',       // Blog services's subdomains (only)
332                         //              'IANA-examples' => '#^(?:.*\.)?example\.(?:com|net|org)$#',
333                         //      );
334                         if (isset($blocklist['list'])) {
335                                 $regexes['list'] = & $blocklist['list'];
336                         } else {
337                                 // Default
338                                 $blocklist['list'] = array(
339                                         'goodhost' => FALSE,
340                                         'badhost'  => TRUE,
341                                 );
342                         }
343                         foreach(array_keys($blocklist['list']) as $_list) {
344                                 if (! isset($blocklist[$_list])) continue;
345                                 foreach ($blocklist[$_list] as $key => $value) {
346                                         if (is_array($value)) {
347                                                 $regexes[$_list][$key] = array();
348                                                 foreach($value as $_key => $_value) {
349                                                         get_blocklist_add($regexes[$_list][$key], $_key, $_value);
350                                                 }
351                                         } else {
352                                                 get_blocklist_add($regexes[$_list], $key, $value);
353                                         }
354                                 }
355                                 unset($blocklist[$_list]);
356                         }
357                 }
358         }
359
360         if ($list === '') {
361                 return $regexes;        // ALL
362         } else if (isset($regexes[$list])) {
363                 return $regexes[$list];
364         } else {
365                 return array();
366         }
367 }
368
369 // Subroutine of get_blocklist()
370 function get_blocklist_add(& $array, $key = 0, $value = '*.example.org')
371 {
372         if (is_string($key)) {
373                 $array[$key] = & $value; // Treat $value as a regex
374         } else {
375                 $array[$value] = '/^' . generate_host_regex($value, '/') . '$/i';
376         }
377 }
378
379 // Blocklist metrics: Separate $host, to $blocked and not blocked
380 function blocklist_distiller(& $hosts, $keys = array('goodhost', 'badhost'), $asap = FALSE)
381 {
382         if (! is_array($hosts)) $hosts = array($hosts);
383         if (! is_array($keys))  $keys  = array($keys);
384
385         $list = get_blocklist('list');
386         $blocked = array();
387
388         foreach($keys as $key){
389                 foreach (get_blocklist($key) as $label => $regex) {
390                         if (is_array($regex)) {
391                                 foreach($regex as $_label => $_regex) {
392                                         $group = preg_grep($_regex, $hosts);
393                                         if ($group) {
394                                                 $hosts = array_diff($hosts, $group);
395                                                 $blocked[$key][$label][$_label] = $group;
396                                                 if ($asap && $list[$key]) break;
397                                         }
398                                 }
399                         } else {
400                                 $group = preg_grep($regex, $hosts);
401                                 if ($group) {
402                                         $hosts = array_diff($hosts, $group);
403                                         $blocked[$key][$label] = $group;
404                                         if ($asap && $list[$key]) break;
405                                 }
406                         }
407                 }
408         }
409
410         return $blocked;
411 }
412
413
414 // ---------------------
415
416
417 // Default (enabled) methods and thresholds (for content insertion)
418 function check_uri_spam_method($times = 1, $t_area = 0, $rule = TRUE)
419 {
420         $times  = intval($times);
421         $t_area = intval($t_area);
422
423         $positive = array(
424                 // Thresholds
425                 'quantity'     =>  8 * $times,  // Allow N URIs
426                 'non_uniqhost' =>  3 * $times,  // Allow N duped (and normalized) Hosts
427                 //'non_uniquri'=>  3 * $times,  // Allow N duped (and normalized) URIs
428
429                 // Areas
430                 'area_anchor'  => $t_area,      // Using <a href> HTML tag
431                 'area_bbcode'  => $t_area,      // Using [url] or [link] BBCode
432                 //'uri_anchor' => $t_area,      // URI inside <a href> HTML tag
433                 //'uri_bbcode' => $t_area,      // URI inside [url] or [link] BBCode
434         );
435         if ($rule) {
436                 $bool = array(
437                         // Rules
438                         //'asap'   => TRUE,     // Quit or return As Soon As Possible
439                         'uniqhost' => TRUE,     // Show uniq host (at block notification mail)
440                         'badhost'  => TRUE,     // Check badhost
441                 );
442         } else {
443                 $bool = array();
444         }
445
446         // Remove non-$positive values
447         foreach (array_keys($positive) as $key) {
448                 if ($positive[$key] < 0) unset($positive[$key]);
449         }
450
451         return $positive + $bool;
452 }
453
454 // Simple/fast spam check
455 function check_uri_spam($target = '', $method = array())
456 {
457         // Return value
458         $progress = array(
459                 'method'  => array(
460                         // Theme to do  => Dummy, optional value, or optional array()
461                         //'quantity'    => 8,
462                         //'uniqhost'    => TRUE,
463                         //'non_uniqhost'=> 3,
464                         //'non_uniquri' => 3,
465                         //'badhost'     => TRUE,
466                         //'area_anchor' => 0,
467                         //'area_bbcode' => 0,
468                         //'uri_anchor'  => 0,
469                         //'uri_bbcode'  => 0,
470                 ),
471                 'sum' => array(
472                         // Theme        => Volume found (int)
473                 ),
474                 'is_spam' => array(
475                         // Flag. If someting defined here,
476                         // one or more spam will be included
477                         // in this report
478                 ),
479                 'blocked' => array(
480                         // Hosts blocked
481                         //'category' => array(
482                         //      'host',
483                         //)
484                 ),
485                 'hosts' => array(
486                         // Hosts not blocked
487                 ),
488         );
489
490         // Aliases
491         $sum     = & $progress['sum'];
492         $is_spam = & $progress['is_spam'];
493         $progress['method'] = & $method;        // Argument
494         $blocked = & $progress['blocked'];
495         $hosts   = & $progress['hosts'];
496         $asap    = isset($method['asap']);
497
498         // Init
499         if (! is_array($method) || empty($method)) {
500                 $method = check_uri_spam_method();
501         }
502         foreach(array_keys($method) as $key) {
503                 if (! isset($sum[$key])) $sum[$key] = 0;
504         }
505         if (! isset($sum['quantity'])) $sum['quantity'] = 0;
506
507         if (is_array($target)) {
508                 foreach($target as $str) {
509                         if (! is_string($str)) continue;
510
511                         $_progress = check_uri_spam($str, $method);     // Recurse
512
513                         // Merge $sum
514                         $_sum = & $_progress['sum'];
515                         foreach (array_keys($_sum) as $key) {
516                                 if (! isset($sum[$key])) {
517                                         $sum[$key] = & $_sum[$key];
518                                 } else {
519                                         $sum[$key] += $_sum[$key];
520                                 }
521                         }
522
523                         // Merge $is_spam
524                         $_is_spam = & $_progress['is_spam'];
525                         foreach (array_keys($_is_spam) as $key) {
526                                 $is_spam[$key] = TRUE;
527                                 if ($asap) break;
528                         }
529                         if ($asap && $is_spam) break;
530
531                         // Merge only
532                         $blocked = array_merge_recursive($blocked, $_progress['blocked']);
533                         $hosts   = array_merge_recursive($hosts,   $_progress['hosts']);
534                 }
535
536                 // Unique values
537                 $blocked = array_unique_recursive($blocked);
538                 $hosts   = array_unique_recursive($hosts);
539
540                 // Recount $sum['badhost']
541                 $sum['badhost'] = array_count_leaves($blocked);
542
543                 return $progress;
544         }
545
546         // Area: There's HTML anchor tag
547         if ((! $asap || ! $is_spam) && isset($method['area_anchor'])) {
548                 $key = 'area_anchor';
549                 $_asap = isset($method['asap']) ? array('asap' => TRUE) : array();
550                 $result = area_pickup($target, array($key => TRUE) + $_asap);
551                 if ($result) {
552                         $sum[$key] = $result[$key];
553                         if (isset($method[$key]) && $sum[$key] > $method[$key]) {
554                                 $is_spam[$key] = TRUE;
555                         }
556                 }
557         }
558
559         // Area: There's 'BBCode' linking tag
560         if ((! $asap || ! $is_spam) && isset($method['area_bbcode'])) {
561                 $key = 'area_bbcode';
562                 $_asap = isset($method['asap']) ? array('asap' => TRUE) : array();
563                 $result = area_pickup($target, array($key => TRUE) + $_asap);
564                 if ($result) {
565                         $sum[$key] = $result[$key];
566                         if (isset($method[$key]) && $sum[$key] > $method[$key]) {
567                                 $is_spam[$key] = TRUE;
568                         }
569                 }
570         }
571
572         // Return if ...
573         if ($asap && $is_spam) return $progress;
574
575         // URI: Pickup
576         $pickups = uri_pickup_normalize(spam_uri_pickup($target, $method));
577
578         // Return if ...
579         if (empty($pickups)) return $progress;
580
581         // URI: Check quantity
582         $sum['quantity'] += count($pickups);
583                 // URI quantity
584         if ((! $asap || ! $is_spam) && isset($method['quantity']) &&
585                 $sum['quantity'] > $method['quantity']) {
586                 $is_spam['quantity'] = TRUE;
587         }
588
589         // URI: used inside HTML anchor tag pair
590         if ((! $asap || ! $is_spam) && isset($method['uri_anchor'])) {
591                 $key = 'uri_anchor';
592                 foreach($pickups as $pickup) {
593                         if (isset($pickup['area'][$key])) {
594                                 $sum[$key] += $pickup['area'][$key];
595                                 if(isset($method[$key]) &&
596                                         $sum[$key] > $method[$key]) {
597                                         $is_spam[$key] = TRUE;
598                                         if ($asap && $is_spam) break;
599                                 }
600                                 if ($asap && $is_spam) break;
601                         }
602                 }
603         }
604
605         // URI: used inside 'BBCode' pair
606         if ((! $asap || ! $is_spam) && isset($method['uri_bbcode'])) {
607                 $key = 'uri_bbcode';
608                 foreach($pickups as $pickup) {
609                         if (isset($pickup['area'][$key])) {
610                                 $sum[$key] += $pickup['area'][$key];
611                                 if(isset($method[$key]) &&
612                                         $sum[$key] > $method[$key]) {
613                                         $is_spam[$key] = TRUE;
614                                         if ($asap && $is_spam) break;
615                                 }
616                                 if ($asap && $is_spam) break;
617                         }
618                 }
619         }
620
621         // URI: Uniqueness (and removing non-uniques)
622         if ((! $asap || ! $is_spam) && isset($method['non_uniquri'])) {
623
624                 $uris = array();
625                 foreach (array_keys($pickups) as $key) {
626                         $uris[$key] = uri_pickup_implode($pickups[$key]);
627                 }
628                 $count = count($uris);
629                 $uris  = array_unique($uris);
630                 $sum['non_uniquri'] += $count - count($uris);
631                 if ($sum['non_uniquri'] > $method['non_uniquri']) {
632                         $is_spam['non_uniquri'] = TRUE;
633                 }
634                 if (! $asap || ! $is_spam) {
635                         foreach (array_diff(array_keys($pickups),
636                                 array_keys($uris)) as $remove) {
637                                 unset($pickups[$remove]);
638                         }
639                 }
640                 unset($uris);
641         }
642
643         // Return if ...
644         if ($asap && $is_spam) return $progress;
645
646         // Host: Uniqueness (uniq / non-uniq)
647         foreach ($pickups as $pickup) $hosts[] = & $pickup['host'];
648         $hosts = array_unique($hosts);
649         $sum['uniqhost'] += count($hosts);
650         if ((! $asap || ! $is_spam) && isset($method['non_uniqhost'])) {
651                 $sum['non_uniqhost'] = $sum['quantity'] - $sum['uniqhost'];
652                 if ($sum['non_uniqhost'] > $method['non_uniqhost']) {
653                         $is_spam['non_uniqhost'] = TRUE;
654                 }
655         }
656
657         // Return if ...
658         if ($asap && $is_spam) return $progress;
659
660         // URI: Bad host (Separate good/bad hosts from $hosts)
661         if ((! $asap || ! $is_spam) && isset($method['badhost'])) {
662
663                 // is_badhost()
664                 $list = get_blocklist('list');
665                 $blocked = blocklist_distiller($hosts, array_keys($list), $asap);
666                 foreach($list as $key=>$type){
667                         if (! $type) unset($blocked[$key]); // Ignore goodhost etc
668                 }
669                 unset($list);
670
671                 if (! empty($blocked)) $is_spam['badhost'] = TRUE;
672         }
673
674         return $progress;
675 }
676
677 // ---------------------
678 // Reporting
679
680 // Summarize $progress (blocked only)
681 function summarize_spam_progress($progress = array(), $blockedonly = FALSE)
682 {
683         if ($blockedonly) {
684                 $tmp = array_keys($progress['is_spam']);
685         } else {
686                 $tmp = array();
687                 $method = & $progress['method'];
688                 if (isset($progress['sum'])) {
689                         foreach ($progress['sum'] as $key => $value) {
690                                 if (isset($method[$key]) && $value) {
691                                         $tmp[] = $key . '(' . $value . ')';
692                                 }
693                         }
694                 }
695         }
696
697         return implode(', ', $tmp);
698 }
699
700 function summarize_detail_badhost($progress = array())
701 {
702         if (! isset($progress['blocked']) || empty($progress['blocked'])) return '';
703
704         // Flat per group
705         $blocked = array();
706         foreach($progress['blocked'] as $list => $lvalue) {
707                 foreach($lvalue as $group => $gvalue) {
708                         $flat = implode(', ', array_flat_leaves($gvalue));
709                         if ($flat === $group) {
710                                 $blocked[$list][]       = $flat;
711                         } else {
712                                 $blocked[$list][$group] = $flat;
713                         }
714                 }
715         }
716
717         // Shrink per list
718         // From: 'A-1' => array('ie.to')
719         // To:   'A-1' => 'ie.to'
720         foreach($blocked as $list => $lvalue) {
721                 if (is_array($lvalue) &&
722                    count($lvalue) == 1 &&
723                    is_numeric(key($lvalue))) {
724                     $blocked[$list] = current($lvalue);
725                 }
726         }
727
728         return var_export_shrink($blocked, TRUE, TRUE);
729 }
730
731 function summarize_detail_newtral($progress = array())
732 {
733         if (! isset($progress['hosts'])    ||
734             ! is_array($progress['hosts']) ||
735             empty($progress['hosts'])) return '';
736
737         // Generate a responsible $trie
738         $trie = array();
739         foreach($progress['hosts'] as $value) {
740                 // 'A.foo.bar.example.com'
741                 $resp = whois_responsibility($value);   // 'example.com'
742                 if (empty($resp)) {
743                         // One or more test, or do nothing here
744                         $resp = strval($value);
745                         $rest = '';
746                 } else {
747                         $rest = rtrim(substr($value, 0, - strlen($resp)), '.'); // 'A.foo.bar'
748                 }
749                 $trie = array_merge_recursive($trie, array($resp => array($rest => NULL)));
750         }
751
752         // Format: var_export_shrink() -like output
753         $result = array();
754         ksort_by_domain($trie);
755         foreach(array_keys($trie) as $key) {
756                 ksort_by_domain($trie[$key]);
757                 if (count($trie[$key]) == 1 && key($trie[$key]) == '') {
758                         // Just one 'responsibility.example.com'
759                         $result[] = '  \'' . $key . '\',';
760                 } else {
761                         // One subdomain-or-host, or several ones
762                         $subs = array();
763                         foreach(array_keys($trie[$key]) as $sub) {
764                                 if ($sub == '') {
765                                         $subs[] = $key;
766                                 } else {
767                                         $subs[] = $sub . '.' . $key;
768                                 }
769                         }
770                         $result[] = '  \'' . $key . '\' => \'' . implode(', ', $subs) . '\',';
771                 }
772                 unset($trie[$key]);
773         }
774         return
775                 'array (' . "\n" .
776                         implode("\n", $result) . "\n" .
777                 ')';
778 }
779
780
781 // Check responsibility-root of the FQDN
782 // 'foo.bar.example.com'        => 'example.com'        (.com        has the last whois for it)
783 // 'foo.bar.example.au'         => 'example.au'         (.au         has the last whois for it)
784 // 'foo.bar.example.edu.au'     => 'example.edu.au'     (.edu.au     has the last whois for it)
785 // 'foo.bar.example.act.edu.au' => 'example.act.edu.au' (.act.edu.au has the last whois for it)
786 function whois_responsibility($fqdn = 'foo.bar.example.com', $parent = FALSE, $implicit = TRUE)
787 {
788         static $domain;
789
790         if ($fqdn === NULL) {
791                 $domain = NULL; // Unset
792                 return '';
793         }
794         if (! is_string($fqdn)) return '';
795
796         if (is_ip($fqdn)) return $fqdn;
797
798         if (! isset($domain)) {
799                 $domain = array();
800                 if (file_exists(DOMAIN_INI_FILE)) {
801                         include(DOMAIN_INI_FILE);       // Set
802                 }
803         }
804
805         $result  = array();
806         $dcursor = & $domain;
807         $array   = array_reverse(explode('.', $fqdn));
808         $i = 0;
809         while(TRUE) {
810                 if (! isset($array[$i])) break;
811                 $acursor = $array[$i];
812                 if (is_array($dcursor) && isset($dcursor[$acursor])) {
813                         $result[] = & $array[$i];
814                         $dcursor  = & $dcursor[$acursor];
815                 } else {
816                         if (! $parent && isset($acursor)) {
817                                 $result[] = & $array[$i];       // Whois servers must know this subdomain
818                         }
819                         break;
820                 }
821                 ++$i;
822         }
823
824         // Implicit responsibility: Top-Level-Domains must not be yours
825         // 'bar.foo.something' => 'foo.something'
826         if ($implicit && count($result) == 1 && count($array) > 1) {
827                 $result[] = & $array[1];
828         }
829
830         return $result ? implode('.', array_reverse($result)) : '';
831 }
832
833
834 // ---------------------
835 // Exit
836
837 // Freeing memories
838 function spam_dispose()
839 {
840         get_blocklist(NULL);
841         whois_responsibility(NULL);
842 }
843
844 // Common bahavior for blocking
845 // NOTE: Call this function from various blocking feature, to disgueise the reason 'why blocked'
846 function spam_exit($mode = '', $data = array())
847 {
848         $exit = TRUE;
849
850         switch ($mode) {
851                 case '':
852                         echo("\n");
853                         break;
854                 case 'dump':
855                         echo('<pre>' . "\n");
856                         echo htmlspecialchars(var_export($data, TRUE));
857                         echo('</pre>' . "\n");
858                         break;
859         };
860
861         if ($exit) exit;        // Force exit
862 }
863
864
865 // ---------------------
866 // Simple filtering
867
868 // TODO: Record them
869 // Simple/fast spam filter ($target: 'a string' or an array())
870 function pkwk_spamfilter($action, $page, $target = array('title' => ''), $method = array(), $exitmode = '')
871 {
872         $progress = check_uri_spam($target, $method);
873
874         if (empty($progress['is_spam'])) {
875                 spam_dispose();
876         } else {
877
878 // TODO: detect encoding from $target for mbstring functions
879 //              $tmp = array();
880 //              foreach(array_keys($target) as $key) {
881 //                      $tmp[strings($key, 0, FALSE, TRUE)] = strings($target[$key], 0, FALSE, TRUE);   // Removing "\0" etc
882 //              }
883 //              $target = & $tmp;
884
885                 pkwk_spamnotify($action, $page, $target, $progress, $method);
886                 spam_exit($exitmode, $progress);
887         }
888 }
889
890 // ---------------------
891 // PukiWiki original
892
893 // Mail to administrator(s)
894 function pkwk_spamnotify($action, $page, $target = array('title' => ''), $progress = array(), $method = array())
895 {
896         global $notify, $notify_subject;
897
898         if (! $notify) return;
899
900         $asap = isset($method['asap']);
901
902         $summary['ACTION']  = 'Blocked by: ' . summarize_spam_progress($progress, TRUE);
903         if (! $asap) {
904                 $summary['METRICS'] = summarize_spam_progress($progress);
905         }
906
907         $tmp = summarize_detail_badhost($progress);
908         if ($tmp != '') $summary['DETAIL_BADHOST'] = $tmp;
909
910         $tmp = summarize_detail_newtral($progress);
911         if (! $asap && $tmp != '') $summary['DETAIL_NEUTRAL_HOST'] = $tmp;
912
913         $summary['COMMENT'] = $action;
914         $summary['PAGE']    = '[blocked] ' . (is_pagename($page) ? $page : '');
915         $summary['URI']     = get_script_uri() . '?' . rawurlencode($page);
916         $summary['USER_AGENT']  = TRUE;
917         $summary['REMOTE_ADDR'] = TRUE;
918         pkwk_mail_notify($notify_subject,  var_export($target, TRUE), $summary, TRUE);
919 }
920
921 ?>