OSDN Git Service

0a0fb6faa5b2f07c6f759093d53b2b150da44b50
[pukiwiki/pukiwiki_sandbox.git] / spam / spam.php
1 <?php
2 // $Id: spam.php,v 1.205 2008/12/27 14:50: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                 // localhost
360                 return generate_glob_regex($string, $divider);
361         }
362
363         if (is_ip($string)) {
364                 // IPv4
365                 return generate_glob_regex($string, $divider);
366         } else {
367                 // FQDN or something
368                 $part = explode('.', $string, 2);
369                 if ($part[0] == '') {
370                         // .example.org
371                         $part[0] = '(?:.*\.)?';
372                 } else if ($part[0] == '*') {
373                         // *.example.org
374                         $part[0] = '.*\.';
375                 } else {
376                         // example.org, etc
377                         return generate_glob_regex($string, $divider);
378                 }
379                 $part[1] = generate_glob_regex($part[1], $divider);
380                 return implode('', $part);
381         }
382 }
383
384 // Rough hostname checker
385 // TODO: Strict digit, 0x, CIDR, '999.999.999.999', ':', '::G'
386 function is_ip($string = '')
387 {
388         if (! is_string($string)) return FALSE;
389
390         if (strpos($string, ':') !== FALSE) {
391                 return 6;       // Seems IPv6
392         }
393
394         if (preg_match('/^' .
395                 '(?:[0-9]{1,3}\.){3}[0-9]{1,3}' . '|' .
396                 '(?:[0-9]{1,3}\.){1,3}'         . '$/',
397                 $string)) {
398                 return 4;       // Seems IPv4(dot-decimal)
399         }
400
401         return FALSE;   // Seems not IP
402 }
403
404 function get_blocklist($list = '')
405 {
406         static $regexes;
407
408         if ($list === NULL) {
409                 $regexes = NULL;        // Unset
410                 return array();
411         }
412
413         if (! isset($regexes)) {
414                 $regexes = array();
415                 if (file_exists(SPAM_INI_FILE)) {
416                         $blocklist = array();
417                         include(SPAM_INI_FILE);
418                         //      $blocklist['list'] = array(
419                         //      //'goodhost' => FALSE;
420                         //      'badhost' => TRUE;
421                         // );
422                         //      $blocklist['badhost'] = array(
423                         //              '*.blogspot.com',       // Blog services's subdomains (only)
424                         //              'IANA-examples' => '#^(?:.*\.)?example\.(?:com|net|org)$#',
425                         //      );
426                         foreach(array('pre', 'list') as $special) {
427                                 if (! isset($blocklist[$special])) continue;
428                                 $regexes[$special] = $blocklist[$special];
429                                 foreach(array_keys($blocklist[$special]) as $_list) {
430                                         if (! isset($blocklist[$_list])) continue;
431                                         foreach ($blocklist[$_list] as $key => $value) {
432                                                 if (is_array($value)) {
433                                                         $regexes[$_list][$key] = array();
434                                                         foreach($value as $_key => $_value) {
435                                                                 get_blocklist_add($regexes[$_list][$key], $_key, $_value);
436                                                         }
437                                                 } else {
438                                                         get_blocklist_add($regexes[$_list], $key, $value);
439                                                 }
440                                         }
441                                         unset($blocklist[$_list]);
442                                 }
443                         }
444                 }
445         }
446
447         if ($list === '') {
448                 return $regexes;        // ALL
449         } else if (isset($regexes[$list])) {
450                 return $regexes[$list];
451         } else {
452                 return array();
453         }
454 }
455
456 // Subroutine of get_blocklist()
457 function get_blocklist_add(& $array, $key = 0, $value = '*.example.org')
458 {
459         if (is_string($key)) {
460                 $array[$key] = & $value; // Treat $value as a regex
461         } else {
462                 $array[$value] = '/^' . generate_host_regex($value, '/') . '$/i';
463         }
464 }
465
466 // Blocklist metrics: Separate $host, to $blocked and not blocked
467 function blocklist_distiller(& $hosts, $keys = array('goodhost', 'badhost'), $asap = FALSE)
468 {
469         if (! is_array($hosts)) $hosts = array($hosts);
470         if (! is_array($keys))  $keys  = array($keys);
471
472         $list = get_blocklist('list');
473         $blocked = array();
474
475         foreach($keys as $key){
476                 foreach (get_blocklist($key) as $label => $regex) {
477                         if (is_array($regex)) {
478                                 foreach($regex as $_label => $_regex) {
479                                         $group = preg_grep($_regex, $hosts);
480                                         if ($group) {
481                                                 $hosts = array_diff($hosts, $group);
482                                                 $blocked[$key][$label][$_label] = $group;
483                                                 if ($asap && $list[$key]) break;
484                                         }
485                                 }
486                         } else {
487                                 $group = preg_grep($regex, $hosts);
488                                 if ($group) {
489                                         $hosts = array_diff($hosts, $group);
490                                         $blocked[$key][$label] = $group;
491                                         if ($asap && $list[$key]) break;
492                                 }
493                         }
494                 }
495         }
496
497         return $blocked;
498 }
499
500
501 // ---------------------
502
503
504 // Default (enabled) methods and thresholds (for content insertion)
505 function check_uri_spam_method($times = 1, $t_area = 0, $rule = TRUE)
506 {
507         $times  = intval($times);
508         $t_area = intval($t_area);
509
510         $positive = array(
511                 // Thresholds
512                 'quantity'     =>  8 * $times,  // Allow N URIs
513                 'non_uniqhost' =>  3 * $times,  // Allow N duped (and normalized) Hosts
514                 //'non_uniquri'=>  3 * $times,  // Allow N duped (and normalized) URIs
515
516                 // Areas
517                 'area_anchor'  => $t_area,      // Using <a href> HTML tag
518                 'area_bbcode'  => $t_area,      // Using [url] or [link] BBCode
519                 //'uri_anchor' => $t_area,      // URI inside <a href> HTML tag
520                 //'uri_bbcode' => $t_area,      // URI inside [url] or [link] BBCode
521         );
522         if ($rule) {
523                 $bool = array(
524                         // Rules
525                         //'asap'   => TRUE,     // Quit or return As Soon As Possible
526                         'uniqhost' => TRUE,     // Show uniq host (at block notification mail)
527                         'badhost'  => TRUE,     // Check badhost
528                 );
529         } else {
530                 $bool = array();
531         }
532
533         // Remove non-$positive values
534         foreach (array_keys($positive) as $key) {
535                 if ($positive[$key] < 0) unset($positive[$key]);
536         }
537
538         return $positive + $bool;
539 }
540
541 // Simple/fast spam check
542 function check_uri_spam($target = '', $method = array())
543 {
544         // Return value
545         $progress = array(
546                 'method'  => array(
547                         // Theme to do  => Dummy, optional value, or optional array()
548                         //'quantity'    => 8,
549                         //'uniqhost'    => TRUE,
550                         //'non_uniqhost'=> 3,
551                         //'non_uniquri' => 3,
552                         //'badhost'     => TRUE,
553                         //'area_anchor' => 0,
554                         //'area_bbcode' => 0,
555                         //'uri_anchor'  => 0,
556                         //'uri_bbcode'  => 0,
557                 ),
558                 'sum' => array(
559                         // Theme        => Volume found (int)
560                 ),
561                 'is_spam' => array(
562                         // Flag. If someting defined here,
563                         // one or more spam will be included
564                         // in this report
565                 ),
566                 'blocked' => array(
567                         // Hosts blocked
568                         //'category' => array(
569                         //      'host',
570                         //)
571                 ),
572                 'hosts' => array(
573                         // Hosts not blocked
574                 ),
575         );
576
577         // ----------------------------------------
578         // Aliases
579
580         $sum     = & $progress['sum'];
581         $is_spam = & $progress['is_spam'];
582         $progress['method'] = & $method;        // Argument
583         $blocked = & $progress['blocked'];
584         $hosts   = & $progress['hosts'];
585         $asap    = isset($method['asap']);
586
587         // ----------------------------------------
588         // Init
589
590         if (! is_array($method) || empty($method)) {
591                 $method = check_uri_spam_method();
592         }
593         foreach(array_keys($method) as $key) {
594                 if (! isset($sum[$key])) $sum[$key] = 0;
595         }
596         if (! isset($sum['quantity'])) $sum['quantity'] = 0;
597
598         // ----------------------------------------
599         // Recurse
600
601         if (is_array($target)) {
602                 foreach($target as $str) {
603                         if (! is_string($str)) continue;
604
605                         $_progress = check_uri_spam($str, $method);     // Recurse
606
607                         // Merge $sum
608                         $_sum = & $_progress['sum'];
609                         foreach (array_keys($_sum) as $key) {
610                                 if (! isset($sum[$key])) {
611                                         $sum[$key] = & $_sum[$key];
612                                 } else {
613                                         $sum[$key] += $_sum[$key];
614                                 }
615                         }
616
617                         // Merge $is_spam
618                         $_is_spam = & $_progress['is_spam'];
619                         foreach (array_keys($_is_spam) as $key) {
620                                 $is_spam[$key] = TRUE;
621                                 if ($asap) break;
622                         }
623                         if ($asap && $is_spam) break;
624
625                         // Merge only
626                         $blocked = array_merge_leaves($blocked, $_progress['blocked'], FALSE);
627                         $hosts   = array_merge_leaves($hosts,   $_progress['hosts'],   FALSE);
628                 }
629
630                 // Unique values
631                 $blocked = array_unique_recursive($blocked);
632                 $hosts   = array_unique_recursive($hosts);
633
634                 // Recount $sum['badhost']
635                 $sum['badhost'] = array_count_leaves($blocked);
636
637                 return $progress;
638         }
639
640         // ----------------------------------------
641         // Area measure
642
643         // Area: There's HTML anchor tag
644         if ((! $asap || ! $is_spam) && isset($method['area_anchor'])) {
645                 $key = 'area_anchor';
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         // Area: There's 'BBCode' linking tag
657         if ((! $asap || ! $is_spam) && isset($method['area_bbcode'])) {
658                 $key = 'area_bbcode';
659                 $_asap = isset($method['asap']) ? array('asap' => TRUE) : array();
660                 $result = area_pickup($target, array($key => TRUE) + $_asap);
661                 if ($result) {
662                         $sum[$key] = $result[$key];
663                         if (isset($method[$key]) && $sum[$key] > $method[$key]) {
664                                 $is_spam[$key] = TRUE;
665                         }
666                 }
667         }
668
669         // Return if ...
670         if ($asap && $is_spam) return $progress;
671
672         // ----------------------------------------
673         // URI: Pickup
674
675         $pickups = uri_pickup_normalize(spam_uri_pickup($target, $method));
676         $hosts = array();
677         foreach ($pickups as $key => $pickup) {
678                 $hosts[$key] = & $pickup['host'];
679         }
680
681         // Return if ...
682         if (empty($pickups)) return $progress;
683
684         // ----------------------------------------
685         // URI: Bad host <pre-filter> (Separate good/bad hosts from $hosts)
686
687         if ((! $asap || ! $is_spam) && isset($method['badhost'])) {
688                 $list    = get_blocklist('pre');
689                 $blocked = blocklist_distiller($hosts, array_keys($list), $asap);
690                 foreach($list as $key=>$type){
691                         if (! $type) unset($blocked[$key]); // Ignore goodhost etc
692                 }
693                 unset($list);
694                 if (! empty($blocked)) $is_spam['badhost'] = TRUE;
695         }
696
697         // Return if ...
698         if ($asap && $is_spam) return $progress;
699
700         // Remove blocked from $pickups
701         foreach(array_keys($pickups) as $key) {
702                 if (! isset($hosts[$key])) {
703                         unset($pickups[$key]);
704                 }
705         }
706
707         // ----------------------------------------
708         // URI: Check quantity
709
710         $sum['quantity'] += count($pickups);
711                 // URI quantity
712         if ((! $asap || ! $is_spam) && isset($method['quantity']) &&
713                 $sum['quantity'] > $method['quantity']) {
714                 $is_spam['quantity'] = TRUE;
715         }
716
717         // ----------------------------------------
718         // URI: used inside HTML anchor tag pair
719
720         if ((! $asap || ! $is_spam) && isset($method['uri_anchor'])) {
721                 $key = 'uri_anchor';
722                 foreach($pickups as $pickup) {
723                         if (isset($pickup['area'][$key])) {
724                                 $sum[$key] += $pickup['area'][$key];
725                                 if(isset($method[$key]) &&
726                                         $sum[$key] > $method[$key]) {
727                                         $is_spam[$key] = TRUE;
728                                         if ($asap && $is_spam) break;
729                                 }
730                                 if ($asap && $is_spam) break;
731                         }
732                 }
733         }
734
735         // ----------------------------------------
736         // URI: used inside 'BBCode' pair
737
738         if ((! $asap || ! $is_spam) && isset($method['uri_bbcode'])) {
739                 $key = 'uri_bbcode';
740                 foreach($pickups as $pickup) {
741                         if (isset($pickup['area'][$key])) {
742                                 $sum[$key] += $pickup['area'][$key];
743                                 if(isset($method[$key]) &&
744                                         $sum[$key] > $method[$key]) {
745                                         $is_spam[$key] = TRUE;
746                                         if ($asap && $is_spam) break;
747                                 }
748                                 if ($asap && $is_spam) break;
749                         }
750                 }
751         }
752
753         // ----------------------------------------
754         // URI: Uniqueness (and removing non-uniques)
755
756         if ((! $asap || ! $is_spam) && isset($method['non_uniquri'])) {
757
758                 $uris = array();
759                 foreach (array_keys($pickups) as $key) {
760                         $uris[$key] = uri_pickup_implode($pickups[$key]);
761                 }
762                 $count = count($uris);
763                 $uris  = array_unique($uris);
764                 $sum['non_uniquri'] += $count - count($uris);
765                 if ($sum['non_uniquri'] > $method['non_uniquri']) {
766                         $is_spam['non_uniquri'] = TRUE;
767                 }
768                 if (! $asap || ! $is_spam) {
769                         foreach (array_diff(array_keys($pickups),
770                                 array_keys($uris)) as $remove) {
771                                 unset($pickups[$remove]);
772                         }
773                 }
774                 unset($uris);
775         }
776
777         // Return if ...
778         if ($asap && $is_spam) return $progress;
779
780         // ----------------------------------------
781         // Host: Uniqueness (uniq / non-uniq)
782
783         $hosts = array_unique($hosts);
784
785         if (isset($sum['uniqhost'])) $sum['uniqhost'] += count($hosts);
786         if ((! $asap || ! $is_spam) && isset($method['non_uniqhost'])) {
787                 $sum['non_uniqhost'] = $sum['quantity'] - $sum['uniqhost'];
788                 if ($sum['non_uniqhost'] > $method['non_uniqhost']) {
789                         $is_spam['non_uniqhost'] = TRUE;
790                 }
791         }
792
793         // Return if ...
794         if ($asap && $is_spam) return $progress;
795
796         // ----------------------------------------
797         // URI: Bad host (Separate good/bad hosts from $hosts)
798
799         if ((! $asap || ! $is_spam) && isset($method['badhost'])) {
800                 $list    = get_blocklist('list');
801                 $blocked = array_merge_leaves(
802                         $blocked,
803                         blocklist_distiller($hosts, array_keys($list), $asap),
804                         FALSE
805                 );
806                 foreach($list as $key=>$type){
807                         if (! $type) unset($blocked[$key]); // Ignore goodhost etc
808                 }
809                 unset($list);
810                 if (! empty($blocked)) $is_spam['badhost'] = TRUE;
811         }
812
813         // Return if ...
814         //if ($asap && $is_spam) return $progress;
815
816         // ----------------------------------------
817         // End
818
819         return $progress;
820 }
821
822 // ---------------------
823 // Reporting
824
825 // Summarize $progress (blocked only)
826 function summarize_spam_progress($progress = array(), $blockedonly = FALSE)
827 {
828         if ($blockedonly) {
829                 $tmp = array_keys($progress['is_spam']);
830         } else {
831                 $tmp = array();
832                 $method = & $progress['method'];
833                 if (isset($progress['sum'])) {
834                         foreach ($progress['sum'] as $key => $value) {
835                                 if (isset($method[$key]) && $value) {
836                                         $tmp[] = $key . '(' . $value . ')';
837                                 }
838                         }
839                 }
840         }
841
842         return implode(', ', $tmp);
843 }
844
845 function summarize_detail_badhost($progress = array())
846 {
847         if (! isset($progress['blocked']) || empty($progress['blocked'])) return '';
848
849         // Flat per group
850         $blocked = array();
851         foreach($progress['blocked'] as $list => $lvalue) {
852                 foreach($lvalue as $group => $gvalue) {
853                         $flat = implode(', ', array_flat_leaves($gvalue));
854                         if ($flat === $group) {
855                                 $blocked[$list][]       = $flat;
856                         } else {
857                                 $blocked[$list][$group] = $flat;
858                         }
859                 }
860         }
861
862         // Shrink per list
863         // From: 'A-1' => array('ie.to')
864         // To:   'A-1' => 'ie.to'
865         foreach($blocked as $list => $lvalue) {
866                 if (is_array($lvalue) &&
867                    count($lvalue) == 1 &&
868                    is_numeric(key($lvalue))) {
869                     $blocked[$list] = current($lvalue);
870                 }
871         }
872
873         return var_export_shrink($blocked, TRUE, TRUE);
874 }
875
876 function summarize_detail_newtral($progress = array())
877 {
878         if (! isset($progress['hosts'])    ||
879             ! is_array($progress['hosts']) ||
880             empty($progress['hosts'])) return '';
881
882         // Generate a responsible $trie
883         $trie = array();
884         foreach($progress['hosts'] as $value) {
885                 // 'A.foo.bar.example.com'
886                 $resp = whois_responsibility($value);   // 'example.com'
887                 if (empty($resp)) {
888                         // One or more test, or do nothing here
889                         $resp = strval($value);
890                         $rest = '';
891                 } else {
892                         $rest = rtrim(substr($value, 0, - strlen($resp)), '.'); // 'A.foo.bar'
893                 }
894                 $trie = array_merge_leaves($trie, array($resp => array($rest => NULL)), FALSE);
895         }
896
897         // Format: var_export_shrink() -like output
898         $result = array();
899         ksort_by_domain($trie);
900         foreach(array_keys($trie) as $key) {
901                 ksort_by_domain($trie[$key]);
902                 if (count($trie[$key]) == 1 && key($trie[$key]) == '') {
903                         // Just one 'responsibility.example.com'
904                         $result[] = '  \'' . $key . '\',';
905                 } else {
906                         // One subdomain-or-host, or several ones
907                         $subs = array();
908                         foreach(array_keys($trie[$key]) as $sub) {
909                                 if ($sub == '') {
910                                         $subs[] = $key;
911                                 } else {
912                                         $subs[] = $sub . '.' . $key;
913                                 }
914                         }
915                         $result[] = '  \'' . $key . '\' => \'' . implode(', ', $subs) . '\',';
916                 }
917                 unset($trie[$key]);
918         }
919         return
920                 'array (' . "\n" .
921                         implode("\n", $result) . "\n" .
922                 ')';
923 }
924
925
926 // Check responsibility-root of the FQDN
927 // 'foo.bar.example.com'        => 'example.com'        (.com        has the last whois for it)
928 // 'foo.bar.example.au'         => 'example.au'         (.au         has the last whois for it)
929 // 'foo.bar.example.edu.au'     => 'example.edu.au'     (.edu.au     has the last whois for it)
930 // 'foo.bar.example.act.edu.au' => 'example.act.edu.au' (.act.edu.au has the last whois for it)
931 function whois_responsibility($fqdn = 'foo.bar.example.com', $parent = FALSE, $implicit = TRUE)
932 {
933         static $domain;
934
935         if ($fqdn === NULL) {
936                 $domain = NULL; // Unset
937                 return '';
938         }
939         if (! is_string($fqdn)) return '';
940
941         if (is_ip($fqdn)) return $fqdn;
942
943         if (! isset($domain)) {
944                 $domain = array();
945                 if (file_exists(DOMAIN_INI_FILE)) {
946                         include(DOMAIN_INI_FILE);       // Set
947                 }
948         }
949
950         $result  = array();
951         $dcursor = & $domain;
952         $array   = array_reverse(explode('.', $fqdn));
953         $i = 0;
954         while(TRUE) {
955                 if (! isset($array[$i])) break;
956                 $acursor = $array[$i];
957                 if (is_array($dcursor) && isset($dcursor[$acursor])) {
958                         $result[] = & $array[$i];
959                         $dcursor  = & $dcursor[$acursor];
960                 } else {
961                         if (! $parent && isset($acursor)) {
962                                 $result[] = & $array[$i];       // Whois servers must know this subdomain
963                         }
964                         break;
965                 }
966                 ++$i;
967         }
968
969         // Implicit responsibility: Top-Level-Domains must not be yours
970         // 'bar.foo.something' => 'foo.something'
971         if ($implicit && count($result) == 1 && count($array) > 1) {
972                 $result[] = & $array[1];
973         }
974
975         return $result ? implode('.', array_reverse($result)) : '';
976 }
977
978
979 // ---------------------
980 // Exit
981
982 // Freeing memories
983 function spam_dispose()
984 {
985         get_blocklist(NULL);
986         whois_responsibility(NULL);
987 }
988
989 // Common bahavior for blocking
990 // NOTE: Call this function from various blocking feature, to disgueise the reason 'why blocked'
991 function spam_exit($mode = '', $data = array())
992 {
993         $exit = TRUE;
994
995         switch ($mode) {
996                 case '':
997                         echo("\n");
998                         break;
999                 case 'dump':
1000                         echo('<pre>' . "\n");
1001                         echo htmlspecialchars(var_export($data, TRUE));
1002                         echo('</pre>' . "\n");
1003                         break;
1004         };
1005
1006         if ($exit) exit;        // Force exit
1007 }
1008
1009
1010 // ---------------------
1011 // Simple filtering
1012
1013 // TODO: Record them
1014 // Simple/fast spam filter ($target: 'a string' or an array())
1015 function pkwk_spamfilter($action, $page, $target = array('title' => ''), $method = array(), $exitmode = '')
1016 {
1017         $progress = check_uri_spam($target, $method);
1018
1019         if (empty($progress['is_spam'])) {
1020                 spam_dispose();
1021         } else {
1022
1023 // TODO: detect encoding from $target for mbstring functions
1024 //              $tmp = array();
1025 //              foreach(array_keys($target) as $key) {
1026 //                      $tmp[strings($key, 0, FALSE, TRUE)] = strings($target[$key], 0, FALSE, TRUE);   // Removing "\0" etc
1027 //              }
1028 //              $target = & $tmp;
1029
1030                 pkwk_spamnotify($action, $page, $target, $progress, $method);
1031                 spam_exit($exitmode, $progress);
1032         }
1033 }
1034
1035 // ---------------------
1036 // PukiWiki original
1037
1038 // Mail to administrator(s)
1039 function pkwk_spamnotify($action, $page, $target = array('title' => ''), $progress = array(), $method = array())
1040 {
1041         global $notify, $notify_subject;
1042
1043         if (! $notify) return;
1044
1045         $asap = isset($method['asap']);
1046
1047         $summary['ACTION']  = 'Blocked by: ' . summarize_spam_progress($progress, TRUE);
1048         if (! $asap) {
1049                 $summary['METRICS'] = summarize_spam_progress($progress);
1050         }
1051
1052         $tmp = summarize_detail_badhost($progress);
1053         if ($tmp != '') $summary['DETAIL_BADHOST'] = $tmp;
1054
1055         $tmp = summarize_detail_newtral($progress);
1056         if (! $asap && $tmp != '') $summary['DETAIL_NEUTRAL_HOST'] = $tmp;
1057
1058         $summary['COMMENT'] = $action;
1059         $summary['PAGE']    = '[blocked] ' . (is_pagename($page) ? $page : '');
1060         $summary['URI']     = get_script_uri() . '?' . rawurlencode($page);
1061         $summary['USER_AGENT']  = TRUE;
1062         $summary['REMOTE_ADDR'] = TRUE;
1063         pkwk_mail_notify($notify_subject,  var_export($target, TRUE), $summary, TRUE);
1064 }
1065
1066 ?>