OSDN Git Service

array_merge_leaves() seems similar to array_merge_recursive()
[pukiwiki/pukiwiki_sandbox.git] / spam / spam.php
1 <?php
2 // $Id: spam.php,v 1.140 2007/05/01 05:29:19 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
12 // ---------------------
13 // Compat etc
14
15 // (PHP 4 >= 4.2.0): var_export(): mail-reporting and dump related
16 if (! function_exists('var_export')) {
17         function var_export() {
18                 return 'var_export() is not found on this server' . "\n";
19         }
20 }
21
22 // (PHP 4 >= 4.2.0): preg_grep() enables invert option
23 function preg_grep_invert($pattern = '//', $input = array())
24 {
25         static $invert;
26         if (! isset($invert)) $invert = defined('PREG_GREP_INVERT');
27
28         if ($invert) {
29                 return preg_grep($pattern, $input, PREG_GREP_INVERT);
30         } else {
31                 $result = preg_grep($pattern, $input);
32                 if ($result) {
33                         return array_diff($input, preg_grep($pattern, $input));
34                 } else {
35                         return $input;
36                 }
37         }
38 }
39
40 // Roughly strings(1) using PCRE
41 // This function is useful to:
42 //   * Reduce the size of data, from removing unprintable binary data
43 //   * Detect _bare_strings_ from binary data
44 // References:
45 //   http://www.freebsd.org/cgi/man.cgi?query=strings (Man-page of GNU strings)
46 //   http://www.pcre.org/pcre.txt
47 function strings($binary = '', $min_len = 4, $ignore_space = FALSE)
48 {
49         if ($ignore_space) {
50                 $binary = preg_replace(
51                         array(
52                                 '/(?:[^[:graph:] \t\n]|[\r])+/s',
53                                 '/[ \t]{2,}/',
54                                 '/^[ \t]/m',
55                                 '/[ \t]$/m',
56                         ),
57                         array(
58                                 "\n",
59                                 ' ',
60                                 '',
61                                 ''
62                         ),
63                          $binary);
64         } else {
65                 $binary = preg_replace('/(?:[^[:graph:][:space:]]|[\r])+/s', "\n", $binary);
66         }
67
68         if ($min_len > 1) {
69                 $min_len = min(1024, intval($min_len));
70                 $binary = 
71                         implode("\n",
72                                 preg_grep('/^.{' . $min_len . ',}/S',
73                                         explode("\n", $binary)
74                                 )
75                         );
76         }
77
78         return $binary;
79 }
80
81
82 // ---------------------
83 // URI pickup
84
85 // Return an array of URIs in the $string
86 // [OK] http://nasty.example.org#nasty_string
87 // [OK] http://nasty.example.org:80/foo/xxx#nasty_string/bar
88 // [OK] ftp://nasty.example.org:80/dfsdfs
89 // [OK] ftp://cnn.example.com&story=breaking_news@10.0.0.1/top_story.htm (from RFC3986)
90 function uri_pickup($string = '')
91 {
92         if (! is_string($string)) return array();
93
94         // Not available for: IDN(ignored)
95         $array = array();
96         preg_match_all(
97                 // scheme://userinfo@host:port/path/or/pathinfo/maybefile.and?query=string#fragment
98                 // Refer RFC3986 (Regex below is not strict)
99                 '#(\b[a-z][a-z0-9.+-]{1,8}):/+' .       // 1: Scheme
100                 '(?:' .
101                         '([^\s<>"\'\[\]/\#?@]*)' .              // 2: Userinfo (Username)
102                 '@)?' .
103                 '(' .
104                         // 3: Host
105                         '\[[0-9a-f:.]+\]' . '|' .                               // IPv6([colon-hex and dot]): RFC2732
106                         '(?:[0-9]{1,3}\.){3}[0-9]{1,3}' . '|' . // IPv4(dot-decimal): 001.22.3.44
107                         '[a-z0-9.-]+' .                                                 // hostname(FQDN) : foo.example.org
108                 ')' .
109                 '(?::([0-9]*))?' .                                      // 4: Port
110                 '((?:/+[^\s<>"\'\[\]/\#]+)*/+)?' .      // 5: Directory path or path-info
111                 '([^\s<>"\'\[\]\#?]+)?' .                       // 6: File?
112                 '(?:\?([^\s<>"\'\[\]\#]+))?' .          // 7: Query string
113                 '(?:\#([a-z0-9._~%!$&\'()*+,;=:@-]*))?' .       // 8: Fragment
114                 '#i',
115                  $string, $array, PREG_SET_ORDER | PREG_OFFSET_CAPTURE
116         );
117
118         // Format the $array
119         static $parts = array(
120                 1 => 'scheme', 2 => 'userinfo', 3 => 'host', 4 => 'port',
121                 5 => 'path', 6 => 'file', 7 => 'query', 8 => 'fragment'
122         );
123         $default = array('');
124         foreach(array_keys($array) as $uri) {
125                 $_uri = & $array[$uri];
126                 array_rename_keys($_uri, $parts, TRUE, $default);
127                 $offset = $_uri['scheme'][1]; // Scheme's offset = URI's offset
128                 foreach(array_keys($_uri) as $part) {
129                         $_uri[$part] = & $_uri[$part][0];       // Remove offsets
130                 }
131         }
132
133         foreach(array_keys($array) as $uri) {
134                 $_uri = & $array[$uri];
135                 if ($_uri['scheme'] === '') {
136                         unset($array[$uri]);    // Considererd harmless
137                         continue;
138                 }
139                 unset($_uri[0]); // Matched string itself
140                 $_uri['area']['offset'] = $offset;      // Area offset for area_measure()
141         }
142
143         return $array;
144 }
145
146 // Normalize an array of URI arrays
147 // NOTE: Give me the uri_pickup() results
148 function uri_pickup_normalize(& $pickups, $destructive = TRUE)
149 {
150         if (! is_array($pickups)) return $pickups;
151
152         if ($destructive) {
153                 foreach (array_keys($pickups) as $key) {
154                         $_key = & $pickups[$key];
155                         $_key['scheme']   = isset($_key['scheme']) ? scheme_normalize($_key['scheme']) : '';
156                         $_key['host']     = isset($_key['host'])     ? host_normalize($_key['host']) : '';
157                         $_key['port']     = isset($_key['port'])       ? port_normalize($_key['port'], $_key['scheme'], FALSE) : '';
158                         $_key['path']     = isset($_key['path'])     ? strtolower(path_normalize($_key['path'])) : '';
159                         $_key['file']     = isset($_key['file'])     ? file_normalize($_key['file']) : '';
160                         $_key['query']    = isset($_key['query'])    ? query_normalize($_key['query']) : '';
161                         $_key['fragment'] = isset($_key['fragment']) ? strtolower($_key['fragment']) : '';
162                 }
163         } else {
164                 foreach (array_keys($pickups) as $key) {
165                         $_key = & $pickups[$key];
166                         $_key['scheme']   = isset($_key['scheme']) ? scheme_normalize($_key['scheme']) : '';
167                         $_key['host']     = isset($_key['host'])   ? strtolower($_key['host']) : '';
168                         $_key['port']     = isset($_key['port'])   ? port_normalize($_key['port'], $_key['scheme'], FALSE) : '';
169                         $_key['path']     = isset($_key['path'])   ? path_normalize($_key['path']) : '';
170                 }
171         }
172
173         return $pickups;
174 }
175
176 // An URI array => An URI (See uri_pickup())
177 // USAGE:
178 //      $pickups = uri_pickup('a string include some URIs');
179 //      $uris = array();
180 //      foreach (array_keys($pickups) as $key) {
181 //              $uris[$key] = uri_pickup_implode($pickups[$key]);
182 //      }
183 function uri_pickup_implode($uri = array())
184 {
185         if (empty($uri) || ! is_array($uri)) return NULL;
186
187         $tmp = array();
188         if (isset($uri['scheme']) && $uri['scheme'] !== '') {
189                 $tmp[] = & $uri['scheme'];
190                 $tmp[] = '://';
191         }
192         if (isset($uri['userinfo']) && $uri['userinfo'] !== '') {
193                 $tmp[] = & $uri['userinfo'];
194                 $tmp[] = '@';
195         }
196         if (isset($uri['host']) && $uri['host'] !== '') {
197                 $tmp[] = & $uri['host'];
198         }
199         if (isset($uri['port']) && $uri['port'] !== '') {
200                 $tmp[] = ':';
201                 $tmp[] = & $uri['port'];
202         }
203         if (isset($uri['path']) && $uri['path'] !== '') {
204                 $tmp[] = & $uri['path'];
205         }
206         if (isset($uri['file']) && $uri['file'] !== '') {
207                 $tmp[] = & $uri['file'];
208         }
209         if (isset($uri['query']) && $uri['query'] !== '') {
210                 $tmp[] = '?';
211                 $tmp[] = & $uri['query'];
212         }
213         if (isset($uri['fragment']) && $uri['fragment'] !== '') {
214                 $tmp[] = '#';
215                 $tmp[] = & $uri['fragment'];
216         }
217
218         return implode('', $tmp);
219 }
220
221 // $array['something'] => $array['wanted']
222 function array_rename_keys(& $array, $keys = array('from' => 'to'), $force = FALSE, $default = '')
223 {
224         if (! is_array($array) || ! is_array($keys)) return FALSE;
225
226         // Nondestructive test
227         if (! $force)
228                 foreach(array_keys($keys) as $from)
229                         if (! isset($array[$from]))
230                                 return FALSE;
231
232         foreach($keys as $from => $to) {
233                 if ($from === $to) continue;
234                 if (! $force || isset($array[$from])) {
235                         $array[$to] = & $array[$from];
236                         unset($array[$from]);
237                 } else  {
238                         $array[$to] = $default;
239                 }
240         }
241
242         return TRUE;
243 }
244
245 // ---------------------
246 // Area pickup
247
248 // Pickup all of markup areas
249 function area_pickup($string = '', $method = array())
250 {
251         $area = array();
252         if (empty($method)) return $area;
253
254         // Anchor tag pair by preg_match and preg_match_all()
255         // [OK] <a href></a>
256         // [OK] <a href=  >Good site!</a>
257         // [OK] <a href= "#" >test</a>
258         // [OK] <a href="http://nasty.example.com">visit http://nasty.example.com/</a>
259         // [OK] <a href=\'http://nasty.example.com/\' >discount foobar</a> 
260         // [NG] <a href="http://ng.example.com">visit http://ng.example.com _not_ended_
261         $regex = '#<a\b[^>]*\bhref\b[^>]*>.*?</a\b[^>]*(>)#is';
262         if (isset($method['area_anchor'])) {
263                 $areas = array();
264                 $count = isset($method['asap']) ?
265                         preg_match($regex, $string) :
266                         preg_match_all($regex, $string, $areas);
267                 if (! empty($count)) $area['area_anchor'] = $count;
268         }
269         if (isset($method['uri_anchor'])) {
270                 $areas = array();
271                 preg_match_all($regex, $string, $areas, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
272                 foreach(array_keys($areas) as $_area) {
273                         $areas[$_area] =  array(
274                                 $areas[$_area][0][1], // Area start (<a href>)
275                                 $areas[$_area][1][1], // Area end   (</a>)
276                         );
277                 }
278                 if (! empty($areas)) $area['uri_anchor'] = $areas;
279         }
280
281         // phpBB's "BBCode" pair by preg_match and preg_match_all()
282         // [OK] [url][/url]
283         // [OK] [url]http://nasty.example.com/[/url]
284         // [OK] [link]http://nasty.example.com/[/link]
285         // [OK] [url=http://nasty.example.com]visit http://nasty.example.com/[/url]
286         // [OK] [link http://nasty.example.com/]buy something[/link]
287         $regex = '#\[(url|link)\b[^\]]*\].*?\[/\1\b[^\]]*(\])#is';
288         if (isset($method['area_bbcode'])) {
289                 $areas = array();
290                 $count = isset($method['asap']) ?
291                         preg_match($regex, $string) :
292                         preg_match_all($regex, $string, $areas, PREG_SET_ORDER);
293                 if (! empty($count)) $area['area_bbcode'] = $count;
294         }
295         if (isset($method['uri_bbcode'])) {
296                 $areas = array();
297                 preg_match_all($regex, $string, $areas, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
298                 foreach(array_keys($areas) as $_area) {
299                         $areas[$_area] = array(
300                                 $areas[$_area][0][1], // Area start ([url])
301                                 $areas[$_area][2][1], // Area end   ([/url])
302                         );
303                 }
304                 if (! empty($areas)) $area['uri_bbcode'] = $areas;
305         }
306
307         // Various Wiki syntax
308         // [text_or_uri>text_or_uri]
309         // [text_or_uri:text_or_uri]
310         // [text_or_uri|text_or_uri]
311         // [text_or_uri->text_or_uri]
312         // [text_or_uri text_or_uri] // MediaWiki
313         // MediaWiki: [http://nasty.example.com/ visit http://nasty.example.com/]
314
315         return $area;
316 }
317
318 // If in doubt, it's a little doubtful
319 // if (Area => inside <= Area) $brief += -1
320 function area_measure($areas, & $array, $belief = -1, $a_key = 'area', $o_key = 'offset')
321 {
322         if (! is_array($areas) || ! is_array($array)) return;
323
324         $areas_keys = array_keys($areas);
325         foreach(array_keys($array) as $u_index) {
326                 $offset = isset($array[$u_index][$o_key]) ?
327                         intval($array[$u_index][$o_key]) : 0;
328                 foreach($areas_keys as $a_index) {
329                         if (isset($array[$u_index][$a_key])) {
330                                 $offset_s = intval($areas[$a_index][0]);
331                                 $offset_e = intval($areas[$a_index][1]);
332                                 // [Area => inside <= Area]
333                                 if ($offset_s < $offset && $offset < $offset_e) {
334                                         $array[$u_index][$a_key] += $belief;
335                                 }
336                         }
337                 }
338         }
339 }
340
341 // ---------------------
342 // Spam-uri pickup
343
344 // Domain exposure callback (See spam_uri_pickup_preprocess())
345 // http://victim.example.org/?foo+site:nasty.example.com+bar
346 // => http://nasty.example.com/?refer=victim.example.org
347 // NOTE: 'refer=' is not so good for (at this time).
348 // Consider about using IP address of the victim, try to avoid that.
349 function _preg_replace_callback_domain_exposure($matches = array())
350 {
351         $result = '';
352
353         // Preserve the victim URI as a complicity or ...
354         if (isset($matches[5])) {
355                 $result =
356                         $matches[1] . '://' .   // scheme
357                         $matches[2] . '/' .             // victim.example.org
358                         $matches[3];                    // The rest of all (before victim)
359         }
360
361         // Flipped URI
362         if (isset($matches[4])) {
363                 $result = 
364                         $matches[1] . '://' .   // scheme
365                         $matches[4] .                   // nasty.example.com
366                         '/?refer=' . strtolower($matches[2]) .  // victim.example.org
367                         ' ' . $result;
368         }
369
370         return $result;
371 }
372
373 // Preprocess: rawurldecode() and adding space(s) and something
374 // to detect/count some URIs _if possible_
375 // NOTE: It's maybe danger to var_dump(result). [e.g. 'javascript:']
376 // [OK] http://victim.example.org/?site:nasty.example.org
377 // [OK] http://victim.example.org/nasty.example.org
378 // [OK] http://victim.example.org/go?http%3A%2F%2Fnasty.example.org
379 // [OK] http://victim.example.org/http://nasty.example.org
380 function spam_uri_pickup_preprocess($string = '')
381 {
382         if (! is_string($string)) return '';
383
384         $string = rawurldecode($string);
385
386         // Domain exposure (simple)
387         // http://victim.example.org/nasty.example.org/path#frag
388         // => http://nasty.example.org/?refer=victim.example.org and original
389         $string = preg_replace(
390                 '#http://' .
391                 '(' .
392                         'ime\.nu' . '|' .       // 2ch.net
393                         'ime\.st' . '|' .       // 2ch.net
394                         'link\.toolbot\.com' . '|' .
395                         'urlx\.org' .
396                 ')' .
397                 '/([a-z0-9.%_-]+\.[a-z0-9.%_-]+)#i',    // nasty.example.org
398                 'http://$2/?refer=$1 $0',                               // Preserve $0 or remove?
399                 $string
400         );
401
402         // Domain exposure (See _preg_replace_callback_domain_exposure())
403         $string = preg_replace_callback(
404                 array(
405                         '#(http)://' .
406                         '(' .
407                                 // Something Google: http://www.google.com/supported_domains
408                                 '(?:[a-z0-9.]+\.)?google\.[a-z]{2,3}(?:\.[a-z]{2})?' .
409                                 '|' .
410                                 // AltaVista
411                                 '(?:[a-z0-9.]+\.)?altavista.com' .
412                                 
413                         ')' .
414                         '/' .
415                         '([a-z0-9?=&.%_/\'\\\+-]+)' .                           // path/?query=foo+bar+
416                         '\bsite:([a-z0-9.%_-]+\.[a-z0-9.%_-]+)' .       // site:nasty.example.com
417                         //'()' .        // Preserve or remove?
418                         '#i',
419                 ),
420                 '_preg_replace_callback_domain_exposure',
421                 $string
422         );
423
424         // URI exposure (uriuri => uri uri)
425         $string = preg_replace(
426                 array(
427                         '#(?<! )(?:https?|ftp):/#i',
428                 //      '#[a-z][a-z0-9.+-]{1,8}://#i',
429                 //      '#[a-z][a-z0-9.+-]{1,8}://#i'
430                 ),
431                 ' $0',
432                 $string
433         );
434
435         return $string;
436 }
437
438 // Main function of spam-uri pickup,
439 // A wrapper function of uri_pickup()
440 function spam_uri_pickup($string = '', $method = array())
441 {
442         if (! is_array($method) || empty($method)) {
443                 $method = check_uri_spam_method();
444         }
445
446         $string = spam_uri_pickup_preprocess($string);
447
448         $array  = uri_pickup($string);
449
450         // Area elevation of URIs, for '(especially external)link' intension
451         if (! empty($array)) {
452                 $_method = array();
453                 if (isset($method['uri_anchor'])) $_method['uri_anchor'] = & $method['uri_anchor'];
454                 if (isset($method['uri_bbcode'])) $_method['uri_bbcode'] = & $method['uri_bbcode'];
455                 $areas = area_pickup($string, $_method, TRUE);
456                 if (! empty($areas)) {
457                         $area_shadow = array();
458                         foreach (array_keys($array) as $key) {
459                                 $area_shadow[$key] = & $array[$key]['area'];
460                                 foreach (array_keys($_method) as $_key) {
461                                         $area_shadow[$key][$_key] = 0;
462                                 }
463                         }
464                         foreach (array_keys($_method) as $_key) {
465                                 if (isset($areas[$_key])) {
466                                         area_measure($areas[$_key], $area_shadow, 1, $_key);
467                                 }
468                         }
469                 }
470         }
471
472         // Remove 'offset's for area_measure()
473         foreach(array_keys($array) as $key)
474                 unset($array[$key]['area']['offset']);
475
476         return $array;
477 }
478
479
480 // ---------------------
481 // Normalization
482
483 // Scheme normalization: Renaming the schemes
484 // snntp://example.org =>  nntps://example.org
485 // NOTE: Keep the static lists simple. See also port_normalize().
486 function scheme_normalize($scheme = '', $abbrevs_harmfull = TRUE)
487 {
488         // Abbreviations they have no intention of link
489         static $abbrevs = array(
490                 'ttp'   => 'http',
491                 'ttps'  => 'https',
492         );
493
494         // Aliases => normalized ones
495         static $aliases = array(
496                 'pop'   => 'pop3',
497                 'news'  => 'nntp',
498                 'imap4' => 'imap',
499                 'snntp' => 'nntps',
500                 'snews' => 'nntps',
501                 'spop3' => 'pop3s',
502                 'pops'  => 'pop3s',
503         );
504
505         if (! is_string($scheme)) return '';
506
507         $scheme = strtolower($scheme);
508         if (isset($abbrevs[$scheme])) {
509                 $scheme = $abbrevs_harmfull ? $abbrevs[$scheme] : '';
510         }
511         if (isset($aliases[$scheme])) {
512                 $scheme = $aliases[$scheme];
513         }
514
515         return $scheme;
516 }
517
518 // Hostname normlization (Destructive)
519 // www.foo     => www.foo   ('foo' seems TLD)
520 // www.foo.bar => foo.bar
521 // www.10.20   => www.10.20 (Invalid hostname)
522 // NOTE:
523 //   'www' is  mostly used as traditional hostname of WWW server.
524 //   'www.foo.bar' may be identical with 'foo.bar'.
525 function host_normalize($host = '')
526 {
527         if (! is_string($host)) return '';
528
529         $host = strtolower($host);
530         $matches = array();
531         if (preg_match('/^www\.(.+\.[a-z]+)$/', $host, $matches)) {
532                 return $matches[1];
533         } else {
534                 return $host;
535         }
536 }
537
538 // Port normalization: Suppress the (redundant) default port
539 // HTTP://example.org:80/ => http://example.org/
540 // HTTP://example.org:8080/ => http://example.org:8080/
541 // HTTPS://example.org:443/ => https://example.org/
542 function port_normalize($port, $scheme, $scheme_normalize = FALSE)
543 {
544         // Schemes that users _maybe_ want to add protocol-handlers
545         // to their web browsers. (and attackers _maybe_ want to use ...)
546         // Reference: http://www.iana.org/assignments/port-numbers
547         static $array = array(
548                 // scheme => default port
549                 'ftp'     =>    21,
550                 'ssh'     =>    22,
551                 'telnet'  =>    23,
552                 'smtp'    =>    25,
553                 'tftp'    =>    69,
554                 'gopher'  =>    70,
555                 'finger'  =>    79,
556                 'http'    =>    80,
557                 'pop3'    =>   110,
558                 'sftp'    =>   115,
559                 'nntp'    =>   119,
560                 'imap'    =>   143,
561                 'irc'     =>   194,
562                 'wais'    =>   210,
563                 'https'   =>   443,
564                 'nntps'   =>   563,
565                 'rsync'   =>   873,
566                 'ftps'    =>   990,
567                 'telnets' =>   992,
568                 'imaps'   =>   993,
569                 'ircs'    =>   994,
570                 'pop3s'   =>   995,
571                 'mysql'   =>  3306,
572         );
573
574         // intval() converts '0-1' to '0', so preg_match() rejects these invalid ones
575         if (! is_numeric($port) || $port < 0 || preg_match('/[^0-9]/i', $port))
576                 return '';
577
578         $port = intval($port);
579         if ($scheme_normalize) $scheme = scheme_normalize($scheme);
580         if (isset($array[$scheme]) && $port == $array[$scheme])
581                 $port = ''; // Ignore the defaults
582
583         return $port;
584 }
585
586 // Path normalization
587 // http://example.org => http://example.org/
588 // http://example.org#hoge => http://example.org/#hoge
589 // http://example.org/path/a/b/./c////./d => http://example.org/path/a/b/c/d
590 // http://example.org/path/../../a/../back => http://example.org/back
591 function path_normalize($path = '', $divider = '/', $add_root = TRUE)
592 {
593         if (! is_string($divider)) return is_string($path) ? $path : '';
594
595         if ($add_root) {
596                 $first_div = & $divider;
597         } else {
598                 $first_div = '';
599         }
600         if (! is_string($path) || $path == '') return $first_div;
601
602         if (strpos($path, $divider, strlen($path) - strlen($divider)) === FALSE) {
603                 $last_div = '';
604         } else {
605                 $last_div = & $divider;
606         }
607
608         $array = explode($divider, $path);
609
610         // Remove paddings ('//' and '/./')
611         foreach(array_keys($array) as $key) {
612                 if ($array[$key] == '' || $array[$key] == '.') {
613                          unset($array[$key]);
614                 }
615         }
616
617         // Remove back-tracks ('/../')
618         $tmp = array();
619         foreach($array as $value) {
620                 if ($value == '..') {
621                         array_pop($tmp);
622                 } else {
623                         array_push($tmp, $value);
624                 }
625         }
626         $array = & $tmp;
627
628         if (empty($array)) {
629                 return $first_div;
630         } else {
631                 return $first_div . implode($divider, $array) . $last_div;
632         }
633 }
634
635 // DirectoryIndex normalize (Destructive and rough)
636 // TODO: sample.en.ja.html.gz => sample.html
637 function file_normalize($file = 'index.html.en')
638 {
639         static $simple_defaults = array(
640                 'default.htm'   => TRUE,
641                 'default.html'  => TRUE,
642                 'default.asp'   => TRUE,
643                 'default.aspx'  => TRUE,
644                 'index'                 => TRUE,        // Some system can omit the suffix
645         );
646
647         static $content_suffix = array(
648                 // index.xxx, sample.xxx
649                 'htm'   => TRUE,
650                 'html'  => TRUE,
651                 'shtml' => TRUE,
652                 'jsp'   => TRUE,
653                 'php'   => TRUE,
654                 'php3'  => TRUE,
655                 'php4'  => TRUE,
656                 'pl'    => TRUE,
657                 'py'    => TRUE,
658                 'rb'    => TRUE,
659                 'cgi'   => TRUE,
660                 'xml'   => TRUE,
661         );
662
663         static $language_suffix = array(
664                 // Reference: Apache 2.0.59 'AddLanguage' default
665                 'ca'    => TRUE,
666                 'cs'    => TRUE,        // cs
667                 'cz'    => TRUE,        // cs
668                 'de'    => TRUE,
669                 'dk'    => TRUE,        // da
670                 'el'    => TRUE,
671                 'en'    => TRUE,
672                 'eo'    => TRUE,
673                 'es'    => TRUE,
674                 'et'    => TRUE,
675                 'fr'    => TRUE,
676                 'he'    => TRUE,
677                 'hr'    => TRUE,
678                 'it'    => TRUE,
679                 'ja'    => TRUE,
680                 'ko'    => TRUE,
681                 'ltz'   => TRUE,
682                 'nl'    => TRUE,
683                 'nn'    => TRUE,
684                 'no'    => TRUE,
685                 'po'    => TRUE,
686                 'pt'    => TRUE,
687                 'pt-br' => TRUE,
688                 'ru'    => TRUE,
689                 'sv'    => TRUE,
690                 'zh-cn' => TRUE,
691                 'zh-tw' => TRUE,
692
693                 // Reference: Apache 2.0.59 default 'index.html' variants
694                 'ee'    => TRUE,
695                 'lb'    => TRUE,
696                 'var'   => TRUE,
697         );
698
699         static $charset_suffix = array(
700                 // Reference: Apache 2.0.59 'AddCharset' default
701                 'iso8859-1'     => TRUE, // ISO-8859-1
702                 'latin1'        => TRUE, // ISO-8859-1
703                 'iso8859-2'     => TRUE, // ISO-8859-2
704                 'latin2'        => TRUE, // ISO-8859-2
705                 'cen'           => TRUE, // ISO-8859-2
706                 'iso8859-3'     => TRUE, // ISO-8859-3
707                 'latin3'        => TRUE, // ISO-8859-3
708                 'iso8859-4'     => TRUE, // ISO-8859-4
709                 'latin4'        => TRUE, // ISO-8859-4
710                 'iso8859-5'     => TRUE, // ISO-8859-5
711                 'latin5'        => TRUE, // ISO-8859-5
712                 'cyr'           => TRUE, // ISO-8859-5
713                 'iso-ru'        => TRUE, // ISO-8859-5
714                 'iso8859-6'     => TRUE, // ISO-8859-6
715                 'latin6'        => TRUE, // ISO-8859-6
716                 'arb'           => TRUE, // ISO-8859-6
717                 'iso8859-7'     => TRUE, // ISO-8859-7
718                 'latin7'        => TRUE, // ISO-8859-7
719                 'grk'           => TRUE, // ISO-8859-7
720                 'iso8859-8'     => TRUE, // ISO-8859-8
721                 'latin8'        => TRUE, // ISO-8859-8
722                 'heb'           => TRUE, // ISO-8859-8
723                 'iso8859-9'     => TRUE, // ISO-8859-9
724                 'latin9'        => TRUE, // ISO-8859-9
725                 'trk'           => TRUE, // ISO-8859-9
726                 'iso2022-jp'=> TRUE, // ISO-2022-JP
727                 'jis'           => TRUE, // ISO-2022-JP
728                 'iso2022-kr'=> TRUE, // ISO-2022-KR
729                 'kis'           => TRUE, // ISO-2022-KR
730                 'iso2022-cn'=> TRUE, // ISO-2022-CN
731                 'cis'           => TRUE, // ISO-2022-CN
732                 'big5'          => TRUE,
733                 'cp-1251'       => TRUE, // ru, WINDOWS-1251
734                 'win-1251'      => TRUE, // ru, WINDOWS-1251
735                 'cp866'         => TRUE, // ru
736                 'koi8-r'        => TRUE, // ru, KOI8-r
737                 'koi8-ru'       => TRUE, // ru, KOI8-r
738                 'koi8-uk'       => TRUE, // ru, KOI8-ru
739                 'ua'            => TRUE, // ru, KOI8-ru
740                 'ucs2'          => TRUE, // ru, ISO-10646-UCS-2
741                 'ucs4'          => TRUE, // ru, ISO-10646-UCS-4
742                 'utf8'          => TRUE,
743
744                 // Reference: Apache 2.0.59 default 'index.html' variants
745                 'euc-kr'        => TRUE,
746                 'gb2312'        => TRUE,
747         );
748
749         // May uncompress by web browsers on the fly
750         // Must be at the last of the filename
751         // Reference: Apache 2.0.59 'AddEncoding'
752         static $encoding_suffix = array(
753                 'z'             => TRUE,
754                 'gz'    => TRUE,
755         );
756
757         if (! is_string($file)) return '';
758         $_file = strtolower($file);
759         if (isset($simple_defaults[$_file])) return '';
760
761
762         // Roughly removing language/character-set/encoding suffixes
763         // References:
764         //  * Apache 2 document about 'Content-negotiaton', 'mod_mime' and 'mod_negotiation'
765         //    http://httpd.apache.org/docs/2.0/content-negotiation.html
766         //    http://httpd.apache.org/docs/2.0/mod/mod_mime.html
767         //    http://httpd.apache.org/docs/2.0/mod/mod_negotiation.html
768         //  * http://www.iana.org/assignments/character-sets
769         //  * RFC3066: Tags for the Identification of Languages
770         //    http://www.ietf.org/rfc/rfc3066.txt
771         //  * ISO 639: codes of 'language names'
772         $suffixes = explode('.', $_file);
773         $body = array_shift($suffixes);
774         if ($suffixes) {
775                 // Remove the last .gz/.z
776                 $last_key = end(array_keys($suffixes));
777                 if (isset($encoding_suffix[$suffixes[$last_key]])) {
778                         unset($suffixes[$last_key]);
779                 }
780         }
781         // Cut language and charset suffixes
782         foreach($suffixes as $key => $value){
783                 if (isset($language_suffix[$value]) || isset($charset_suffix[$value])) {
784                         unset($suffixes[$key]);
785                 }
786         }
787         if (empty($suffixes)) return $body;
788
789         // Index.xxx
790         $count = count($suffixes);
791         reset($suffixes);
792         $current = current($suffixes);
793         if ($body == 'index' && $count == 1 && isset($content_suffix[$current])) return '';
794
795         return $file;
796 }
797
798 // Sort query-strings if possible (Destructive and rough)
799 // [OK] &&&&f=d&b&d&c&a=0dd  =>  a=0dd&b&c&d&f=d
800 // [OK] nothing==&eg=dummy&eg=padding&eg=foobar  =>  eg=foobar
801 function query_normalize($string = '', $equal = TRUE, $equal_cutempty = TRUE, $stortolower = TRUE)
802 {
803         if (! is_string($string)) return '';
804         if ($stortolower) $string = strtolower($string);
805
806         $array = explode('&', $string);
807
808         // Remove '&' paddings
809         foreach(array_keys($array) as $key) {
810                 if ($array[$key] == '') {
811                          unset($array[$key]);
812                 }
813         }
814
815         // Consider '='-sepalated input and paddings
816         if ($equal) {
817                 $equals = $not_equals = array();
818                 foreach ($array as $part) {
819                         if (strpos($part, '=') === FALSE) {
820                                  $not_equals[] = $part;
821                         } else {
822                                 list($key, $value) = explode('=', $part, 2);
823                                 $value = ltrim($value, '=');
824                                 if (! $equal_cutempty || $value != '') {
825                                         $equals[$key] = $value;
826                                 }
827                         }
828                 }
829
830                 $array = & $not_equals;
831                 foreach ($equals as $key => $value) {
832                         $array[] = $key . '=' . $value;
833                 }
834                 unset($equals);
835         }
836
837         natsort($array);
838         return implode('&', $array);
839 }
840
841 // ---------------------
842 // Part One : Checker
843
844 // Rough implementation of globbing
845 //
846 // USAGE: $regex = '/^' . generate_glob_regex('*.txt', '/') . '$/i';
847 //
848 function generate_glob_regex($string = '', $divider = '/')
849 {
850         static $from = array(
851                          1 => '*',
852                         11 => '?',
853         //              22 => '[',      // Maybe cause regex compilation error (e.g. '[]')
854         //              23 => ']',      //
855                 );
856         static $mid = array(
857                          1 => '_AST_',
858                         11 => '_QUE_',
859         //              22 => '_RBR_',
860         //              23 => '_LBR_',
861                 );
862         static $to = array(
863                          1 => '.*',
864                         11 => '.',
865         //              22 => '[',
866         //              23 => ']',
867                 );
868
869         if (! is_string($string)) return '';
870
871         $string = str_replace($from, $mid, $string); // Hide
872         $string = preg_quote($string, $divider);
873         $string = str_replace($mid, $to, $string);   // Unhide
874
875         return $string;
876 }
877
878 // Rough hostname checker
879 // [OK] 192.168.
880 // TODO: Strict digit, 0x, CIDR, IPv6
881 function is_ip($string = '')
882 {
883         if (preg_match('/^' .
884                 '(?:[0-9]{1,3}\.){3}[0-9]{1,3}' . '|' .
885                 '(?:[0-9]{1,3}\.){1,3}' . '$/',
886                 $string)) {
887                 return 4;       // Seems IPv4(dot-decimal)
888         } else {
889                 return 0;       // Seems not IP
890         }
891 }
892
893 // Generate host (FQDN, IPv4, ...) regex
894 // 'localhost'     : Matches with 'localhost' only
895 // 'example.org'   : Matches with 'example.org' only (See host_normalize() about 'www')
896 // '.example.org'  : Matches with ALL FQDN ended with '.example.org'
897 // '*.example.org' : Almost the same of '.example.org' except 'www.example.org'
898 // '10.20.30.40'   : Matches with IPv4 address '10.20.30.40' only
899 // [TODO] '192.'   : Matches with all IPv4 hosts started with '192.'
900 // TODO: IPv4, CIDR?, IPv6
901 function generate_host_regex($string = '', $divider = '/')
902 {
903         if (! is_string($string)) return '';
904
905         if (mb_strpos($string, '.') === FALSE)
906                 return generate_glob_regex($string, $divider);
907
908         $result = '';
909         if (is_ip($string)) {
910                 // IPv4
911                 return generate_glob_regex($string, $divider);
912         } else {
913                 // FQDN or something
914                 $part = explode('.', $string, 2);
915                 if ($part[0] == '') {
916                         $part[0] = '(?:.*\.)?'; // And all related FQDN
917                 } else if ($part[0] == '*') {
918                         $part[0] = '.*\.';      // All subdomains/hosts only
919                 } else {
920                         return generate_glob_regex($string, $divider);
921                 }
922                 $part[1] = generate_glob_regex($part[1], $divider);
923                 return implode('', $part);
924         }
925 }
926
927 function get_blocklist($list = '')
928 {
929         static $regexs;
930
931         if (! isset($regexs)) {
932                 $regexs = array();
933                 if (file_exists(SPAM_INI_FILE)) {
934                         $blocklist = array();
935                         include(SPAM_INI_FILE);
936                         //      $blocklist['badhost'] = array(
937                         //              '*.blogspot.com',       // Blog services's subdomains (only)
938                         //              'IANA-examples' => '#^(?:.*\.)?example\.(?:com|net|org)$#',
939                         //      );
940                         if (isset($blocklist['list'])) {
941                                 $regexs['list'] = & $blocklist['list'];
942                         } else {
943                                 // Default
944                                 $blocklist['list'] = array(
945                                         'goodhost' => FALSE,
946                                         'badhost'  => TRUE,
947                                 );
948                         }
949                         foreach(array_keys($blocklist['list']) as $_list) {
950                                 if (! isset($blocklist[$_list])) continue;
951                                 foreach ($blocklist[$_list] as $key => $value) {
952                                         if (is_array($value)) {
953                                                 $regexs[$_list][$key] = array();
954                                                 foreach($value as $_key => $_value) {
955                                                         get_blocklist_add($regexs[$_list][$key], $_key, $_value);
956                                                 }
957                                         } else {
958                                                 get_blocklist_add($regexs[$_list], $key, $value);
959                                         }
960                                 }
961                                 unset($blocklist[$_list]);
962                         }
963                 }
964         }
965
966         if ($list == '') {
967                 return $regexs; // ALL
968         } else if (isset($regexs[$list])) {
969                 return $regexs[$list];
970         } else {        
971                 return array();
972         }
973 }
974
975 // Subroutine of get_blocklist()
976 function get_blocklist_add(& $array, $key = 0, $value = '*.example.org')
977 {
978         if (is_string($key)) {
979                 $array[$key] = & $value; // Treat $value as a regex
980         } else {
981                 $array[$value] = '/^' . generate_host_regex($value, '/') . '$/i';
982         }
983 }
984
985 // Blocklist metrics: Separate $host, to $blocked and not blocked
986 function blocklist_distiller(& $hosts, $keys = array('goodhost', 'badhost'), $asap = FALSE)
987 {
988         if (! is_array($hosts)) $hosts = array($hosts);
989         if (! is_array($keys))  $keys  = array($keys);
990
991         $list = get_blocklist('list');
992         $blocked = array();
993
994         foreach($keys as $key){
995                 foreach (get_blocklist($key) as $label => $regex) {
996                         if (is_array($regex)) {
997                                 foreach($regex as $_label => $_regex) {
998                                         $group = preg_grep($_regex, $hosts);
999                                         if ($group) {
1000                                                 $hosts = array_diff($hosts, $group);
1001                                                 $blocked[$key][$label][$_label] = $group;
1002                                                 if ($asap && $list[$key]) break;
1003                                         }
1004                                 }
1005                         } else {
1006                                 $group = preg_grep($regex, $hosts);
1007                                 if ($group) {
1008                                         $hosts = array_diff($hosts, $group);
1009                                         $blocked[$key][$label] = $group;
1010                                         if ($asap && $list[$key]) break;
1011                                 }
1012                         }
1013                 }
1014         }
1015
1016         return $blocked;
1017 }
1018
1019 // Simple example for badhost (not used now)
1020 function is_badhost($hosts = array(), $asap = TRUE, $bool = TRUE)
1021 {
1022         $list = get_blocklist('list');
1023         $blocked = blocklist_distiller($hosts, array_keys($list), $asap);
1024         foreach($list as $key=>$type){
1025                 if (! $type) unset($blocked[$key]); // Ignore goodhost etc
1026         }
1027
1028         return $bool ? ! empty($blocked) : $blocked;
1029 }
1030
1031
1032 // Default (enabled) methods and thresholds (for content insertion)
1033 function check_uri_spam_method($times = 1, $t_area = 0, $rule = TRUE)
1034 {
1035         $times  = intval($times);
1036         $t_area = intval($t_area);
1037
1038         $positive = array(
1039                 // Thresholds
1040                 'quantity'     =>  8 * $times,  // Allow N URIs
1041                 'non_uniqhost' =>  3 * $times,  // Allow N duped (and normalized) Hosts
1042                 //'non_uniquri'=>  3 * $times,  // Allow N duped (and normalized) URIs
1043
1044                 // Areas
1045                 'area_anchor'  => $t_area,      // Using <a href> HTML tag
1046                 'area_bbcode'  => $t_area,      // Using [url] or [link] BBCode
1047                 //'uri_anchor' => $t_area,      // URI inside <a href> HTML tag
1048                 //'uri_bbcode' => $t_area,      // URI inside [url] or [link] BBCode
1049         );
1050         if ($rule) {
1051                 $bool = array(
1052                         // Rules
1053                         //'asap'   => TRUE,     // Quit or return As Soon As Possible
1054                         'uniqhost' => TRUE,     // Show uniq host (at block notification mail)
1055                         'badhost'  => TRUE,     // Check badhost
1056                 );
1057         } else {
1058                 $bool = array();
1059         }
1060
1061         // Remove non-$positive values
1062         foreach (array_keys($positive) as $key) {
1063                 if ($positive[$key] < 0) unset($positive[$key]);
1064         }
1065
1066         return $positive + $bool;
1067 }
1068
1069 // Simple/fast spam check
1070 function check_uri_spam($target = '', $method = array())
1071 {
1072         if (! is_array($method) || empty($method)) {
1073                 $method = check_uri_spam_method();
1074         }
1075         $progress = array(
1076                 'sum' => array(
1077                         'quantity'    => 0,
1078                         'uniqhost'    => 0,
1079                         'non_uniqhost'=> 0,
1080                         'non_uniquri' => 0,
1081                         'badhost'     => 0,
1082                         'area_anchor' => 0,
1083                         'area_bbcode' => 0,
1084                         'uri_anchor'  => 0,
1085                         'uri_bbcode'  => 0,
1086                 ),
1087                 'is_spam' => array(),
1088                 'method'  => & $method,
1089                 'remains' => array(),
1090                 'error'   => array(),
1091         );
1092         $sum     = & $progress['sum'];
1093         $is_spam = & $progress['is_spam'];
1094         $remains = & $progress['remains'];
1095         $error   = & $progress['error'];
1096         $asap    = isset($method['asap']);
1097
1098         // Recurse
1099         if (is_array($target)) {
1100                 foreach($target as $str) {
1101                         // Recurse
1102                         $_progress = check_uri_spam($str, $method);
1103                         $_sum      = & $_progress['sum'];
1104                         $_is_spam  = & $_progress['is_spam'];
1105                         $_remains  = & $_progress['remains'];
1106                         $_error    = & $_progress['error'];
1107                         foreach (array_keys($_sum) as $key) {
1108                                 $sum[$key] += $_sum[$key];
1109                         }
1110                         foreach (array_keys($_is_spam) as $key) {
1111                                 if (is_array($_is_spam[$key])) {
1112                                         // Marge keys (badhost)
1113                                         foreach(array_keys($_is_spam[$key]) as $_key) {
1114                                                 if (! isset($is_spam[$key][$_key])) {
1115                                                         $is_spam[$key][$_key] =  $_is_spam[$key][$_key];
1116                                                 } else {
1117                                                         $is_spam[$key][$_key] += $_is_spam[$key][$_key];
1118                                                 }
1119                                         }
1120                                 } else {
1121                                         $is_spam[$key] = TRUE;
1122                                 }
1123                         }
1124                         foreach ($_remains as $key=>$value) {
1125                                 foreach ($value as $_key=>$_value) {
1126                                         if (is_int($_key)) {
1127                                                 $remains[$key][]      = $_value;
1128                                         } else {
1129                                                 $remains[$key][$_key] = $_value;
1130                                         }
1131                                 }
1132                         }
1133                         if (! empty($_error)) $error += $_error;
1134                         if ($asap && $is_spam) break;
1135                 }
1136                 return $progress;
1137         }
1138
1139         // Area: There's HTML anchor tag
1140         if ((! $asap || ! $is_spam) && isset($method['area_anchor'])) {
1141                 $key = 'area_anchor';
1142                 $_asap = isset($method['asap']) ? array('asap' => TRUE) : array();
1143                 $result = area_pickup($target, array($key => TRUE) + $_asap);
1144                 if ($result) {
1145                         $sum[$key] = $result[$key];
1146                         if (isset($method[$key]) && $sum[$key] > $method[$key]) {
1147                                 $is_spam[$key] = TRUE;
1148                         }
1149                 }
1150         }
1151
1152         // Area: There's 'BBCode' linking tag
1153         if ((! $asap || ! $is_spam) && isset($method['area_bbcode'])) {
1154                 $key = 'area_bbcode';
1155                 $_asap = isset($method['asap']) ? array('asap' => TRUE) : array();
1156                 $result = area_pickup($target, array($key => TRUE) + $_asap);
1157                 if ($result) {
1158                         $sum[$key] = $result[$key];
1159                         if (isset($method[$key]) && $sum[$key] > $method[$key]) {
1160                                 $is_spam[$key] = TRUE;
1161                         }
1162                 }
1163         }
1164
1165         // Return if ...
1166         if ($asap && $is_spam) return $progress;
1167
1168         // URI: Pickup
1169         $pickups = uri_pickup_normalize(spam_uri_pickup($target, $method));
1170         //$remains['uri_pickup'] = & $pickups;
1171
1172         // Return if ...
1173         if (empty($pickups)) return $progress;
1174
1175         // URI: Check quantity
1176         $sum['quantity'] += count($pickups);
1177                 // URI quantity
1178         if ((! $asap || ! $is_spam) && isset($method['quantity']) &&
1179                 $sum['quantity'] > $method['quantity']) {
1180                 $is_spam['quantity'] = TRUE;
1181         }
1182
1183         // URI: used inside HTML anchor tag pair
1184         if ((! $asap || ! $is_spam) && isset($method['uri_anchor'])) {
1185                 $key = 'uri_anchor';
1186                 foreach($pickups as $pickup) {
1187                         if (isset($pickup['area'][$key])) {
1188                                 $sum[$key] += $pickup['area'][$key];
1189                                 if(isset($method[$key]) &&
1190                                         $sum[$key] > $method[$key]) {
1191                                         $is_spam[$key] = TRUE;
1192                                         if ($asap && $is_spam) break;
1193                                 }
1194                                 if ($asap && $is_spam) break;
1195                         }
1196                 }
1197         }
1198
1199         // URI: used inside 'BBCode' pair
1200         if ((! $asap || ! $is_spam) && isset($method['uri_bbcode'])) {
1201                 $key = 'uri_bbcode';
1202                 foreach($pickups as $pickup) {
1203                         if (isset($pickup['area'][$key])) {
1204                                 $sum[$key] += $pickup['area'][$key];
1205                                 if(isset($method[$key]) &&
1206                                         $sum[$key] > $method[$key]) {
1207                                         $is_spam[$key] = TRUE;
1208                                         if ($asap && $is_spam) break;
1209                                 }
1210                                 if ($asap && $is_spam) break;
1211                         }
1212                 }
1213         }
1214
1215         // URI: Uniqueness (and removing non-uniques)
1216         if ((! $asap || ! $is_spam) && isset($method['non_uniquri'])) {
1217
1218                 $uris = array();
1219                 foreach (array_keys($pickups) as $key) {
1220                         $uris[$key] = uri_pickup_implode($pickups[$key]);
1221                 }
1222                 $count = count($uris);
1223                 $uris  = array_unique($uris);
1224                 $sum['non_uniquri'] += $count - count($uris);
1225                 if ($sum['non_uniquri'] > $method['non_uniquri']) {
1226                         $is_spam['non_uniquri'] = TRUE;
1227                 }
1228                 if (! $asap || ! $is_spam) {
1229                         foreach (array_diff(array_keys($pickups),
1230                                 array_keys($uris)) as $remove) {
1231                                 unset($pickups[$remove]);
1232                         }
1233                 }
1234                 unset($uris);
1235         }
1236
1237         // Return if ...
1238         if ($asap && $is_spam) return $progress;
1239
1240         // Host: Uniqueness (uniq / non-uniq)
1241         $hosts = array();
1242         foreach ($pickups as $pickup) $hosts[] = & $pickup['host'];
1243         $hosts = array_unique($hosts);
1244         //$remains['uniqhost'] = & $hosts;
1245         $sum['uniqhost'] += count($hosts);
1246         if ((! $asap || ! $is_spam) && isset($method['non_uniqhost'])) {
1247                 $sum['non_uniqhost'] = $sum['quantity'] - $sum['uniqhost'];
1248                 if ($sum['non_uniqhost'] > $method['non_uniqhost']) {
1249                         $is_spam['non_uniqhost'] = TRUE;
1250                 }
1251         }
1252
1253         // Return if ...
1254         if ($asap && $is_spam) return $progress;
1255
1256         // URI: Bad host (Separate good/bad hosts from $hosts)
1257         if ((! $asap || ! $is_spam) && isset($method['badhost'])) {
1258
1259                 // is_badhost()
1260                 $list = get_blocklist('list');
1261                 $blocked = blocklist_distiller($hosts, array_keys($list), $asap);
1262                 foreach($list as $key=>$type){
1263                         if (! $type) unset($blocked[$key]); // Ignore goodhost etc
1264                 }
1265                 unset($list);
1266
1267                 if (! $asap && $hosts) {
1268                         $remains['badhost'] = array();
1269                         foreach ($hosts as $value) {
1270                                 $remains['badhost'][$value] = TRUE;
1271                         }
1272                 }
1273
1274                 if (! empty($blocked)) {
1275
1276                         //var_dump($blocked);   // BADHOST detail
1277
1278                         $sum['badhost'] += array_count_leaves($blocked);
1279                         foreach(array_keys($blocked) as $keys) {
1280                                 $is_spam['badhost'][$keys] =
1281                                         array_count_leaves($blocked[$keys]);
1282                         }
1283                 }
1284         }
1285
1286         return $progress;
1287 }
1288
1289 // Count leaves (A leaf = value that is not an array, or an empty array)
1290 function array_count_leaves($array = array(), $count_empty = FALSE)
1291 {
1292         if (! is_array($array) || (empty($array) && $count_empty)) return 1;
1293
1294         // Recurse
1295         $count = 0;
1296         foreach ($array as $part) {
1297                 $count += array_count_leaves($part, $count_empty);
1298         }
1299         return $count;
1300 }
1301
1302 // Merge two leaves
1303 function array_merge_leaves($array1 = array(), $array2 = array())
1304 {
1305         return array_merge_recursive($array1, $array2);
1306 }
1307
1308 // ---------------------
1309 // Reporting
1310
1311 // TODO: Don't show unused $method!
1312 // Summarize $progress (blocked only)
1313 function summarize_spam_progress($progress = array(), $blockedonly = FALSE)
1314 {
1315         if ($blockedonly) {
1316                 $tmp = array_keys($progress['is_spam']);
1317         } else {
1318                 $tmp = array();
1319                 $method = & $progress['method'];
1320                 if (isset($progress['sum'])) {
1321                         foreach ($progress['sum'] as $key => $value) {
1322                                 if (isset($method[$key])) {
1323                                         $tmp[] = $key . '(' . $value . ')';
1324                                 }
1325                         }
1326                 }
1327         }
1328
1329         return implode(', ', $tmp);
1330 }
1331
1332 // ---------------------
1333 // Exit
1334
1335 // Common bahavior for blocking
1336 // NOTE: Call this function from various blocking feature, to disgueise the reason 'why blocked'
1337 function spam_exit($mode = '', $data = array())
1338 {
1339         switch ($mode) {
1340                 case '':        echo("\n");     break;
1341                 case 'dump':
1342                         echo('<pre>' . "\n");
1343                         echo htmlspecialchars(var_export($data, TRUE));
1344                         echo('</pre>' . "\n");
1345                         break;
1346         };
1347
1348         // Force exit
1349         exit;
1350 }
1351
1352
1353 // ---------------------
1354 // Simple filtering
1355
1356 // TODO: Record them
1357 // Simple/fast spam filter ($target: 'a string' or an array())
1358 function pkwk_spamfilter($action, $page, $target = array('title' => ''), $method = array(), $exitmode = '')
1359 {
1360         $progress = check_uri_spam($target, $method);
1361
1362         if (! empty($progress['is_spam'])) {
1363                 // Mail to administrator(s)
1364                 pkwk_spamnotify($action, $page, $target, $progress, $method);
1365
1366                 // Exit
1367                 spam_exit($exitmode, $progress);
1368         }
1369 }
1370
1371 // ---------------------
1372 // PukiWiki original
1373
1374 // Mail to administrator(s)
1375 function pkwk_spamnotify($action, $page, $target = array('title' => ''), $progress = array(), $method = array())
1376 {
1377         global $notify, $notify_subject;
1378
1379         if (! $notify) return;
1380
1381         $asap = isset($method['asap']);
1382
1383         $summary['ACTION']  = 'Blocked by: ' . summarize_spam_progress($progress, TRUE);
1384         if (! $asap) {
1385                 $summary['METRICS'] = summarize_spam_progress($progress);
1386         }
1387         if (isset($progress['is_spam']['badhost'])) {
1388                 $badhost = array();
1389                 foreach($progress['is_spam']['badhost'] as $glob=>$number) {
1390                         $badhost[] = $glob . '(' . $number . ')';
1391                 }
1392                 $summary['DETAIL_BADHOST'] = implode(', ', $badhost);
1393         }
1394         if (! $asap && $progress['remains']['badhost']) {
1395                 $count = count($progress['remains']['badhost']);
1396                 $summary['DETAIL_NEUTRAL_HOST'] = $count .
1397                         ' (' .
1398                                 preg_replace(
1399                                         '/[^, a-z0-9.-]/i', '',
1400                                         implode(', ', array_keys($progress['remains']['badhost']))
1401                                 ) .
1402                         ')';
1403         }
1404         $summary['COMMENT'] = $action;
1405         $summary['PAGE']    = '[blocked] ' . (is_pagename($page) ? $page : '');
1406         $summary['URI']     = get_script_uri() . '?' . rawurlencode($page);
1407         $summary['USER_AGENT']  = TRUE;
1408         $summary['REMOTE_ADDR'] = TRUE;
1409         pkwk_mail_notify($notify_subject,  var_export($target, TRUE), $summary, TRUE);
1410 }
1411
1412 ?>