OSDN Git Service

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