OSDN Git Service

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