OSDN Git Service

ja, uk
[pukiwiki/pukiwiki_sandbox.git] / spam / spam.php
1 <?php
2 // $Id: spam.php,v 1.173 2007/06/10 07:41:24 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 // ----
41
42 // Very roughly, shrink the lines of var_export()
43 // NOTE: If the same data exists, it must be corrupted.
44 function var_export_shrink($expression, $return = FALSE, $ignore_numeric_keys = FALSE)
45 {
46         $result =preg_replace(
47                 // Remove a newline and spaces
48                 '# => \n *array \(#', ' => array (',
49                 var_export($expression, TRUE)
50         );
51
52         if ($ignore_numeric_keys) {
53                 $result =preg_replace(
54                         // Remove numeric keys
55                         '#^( *)[0-9]+ => #m', '$1',
56                         $result
57                 );
58         }
59
60         if ($return) {
61                 return $result;
62         } else {
63                 echo   $result;
64                 return NULL;
65         }
66 }
67
68 // Remove redundant values from array()
69 function array_unique_recursive($array = array())
70 {
71         if (! is_array($array)) return $array;
72
73         $tmp = array();
74         foreach($array as $key => $value){
75                 if (is_array($value)) {
76                         $array[$key] = array_unique_recursive($value);
77                 } else {
78                         if (isset($tmp[$value])) {
79                                 unset($array[$key]);
80                         } else {
81                                 $tmp[$value] = TRUE;
82                         }
83                 }
84         }
85
86         return $array;
87 }
88
89 // Renumber all numeric keys from 0
90 function array_renumber_numeric_keys(& $array)
91 {
92         if (! is_array($array)) return $array;
93
94         $count = -1;
95         $tmp = array();
96         foreach($array as $key => $value){
97                 if (is_array($value)) array_renumber_numeric_keys($array[$key]);        // Recurse
98                 if (is_numeric($key)) $tmp[$key] = ++$count;
99         }
100         array_rename_keys($array, $tmp);
101
102         return $array;
103 }
104
105 // Roughly strings(1) using PCRE
106 // This function is useful to:
107 //   * Reduce the size of data, from removing unprintable binary data
108 //   * Detect _bare_strings_ from binary data
109 // References:
110 //   http://www.freebsd.org/cgi/man.cgi?query=strings (Man-page of GNU strings)
111 //   http://www.pcre.org/pcre.txt
112 function strings($binary = '', $min_len = 4, $ignore_space = FALSE)
113 {
114         if ($ignore_space) {
115                 $binary = preg_replace(
116                         array(
117                                 '/(?:[^[:graph:] \t\n]|[\r])+/s',
118                                 '/[ \t]{2,}/',
119                                 '/^[ \t]/m',
120                                 '/[ \t]$/m',
121                         ),
122                         array(
123                                 "\n",
124                                 ' ',
125                                 '',
126                                 ''
127                         ),
128                          $binary);
129         } else {
130                 // Remove "\0" etc. Preserve readable spaces if possible.
131                 $binary = preg_replace('/(?:[^[:graph:][:space:]]|[\r])+/s', "\n", $binary);
132         }
133
134         if ($min_len > 1) {
135                 $min_len = min(1024, intval($min_len));
136                 $regex = '/^.{' . $min_len . ',}/S';
137                 if (is_array($binary)) {
138                         foreach(array_keys($binary) as $key) {
139                                 $binary[$key] = implode("\n", preg_grep($regex, explode("\n", $binary[$key])));
140                         }
141                 } else {
142                         $binary = implode("\n", preg_grep($regex, explode("\n", $binary)));
143                 }
144         }
145
146         return $binary;
147 }
148
149 // Reverse $string with specified delimiter
150 function delimiter_reverse($string = 'foo.bar.example.com', $from_delim = '.', $to_delim = '.')
151 {
152         if (! is_string($string) || ! is_string($from_delim) || ! is_string($to_delim))
153                 return $string;
154
155         // com.example.bar.foo
156         return implode($to_delim, array_reverse(explode($from_delim, $string)));
157 }
158
159
160 // ---------------------
161 // URI pickup
162
163 // Return an array of URIs in the $string
164 // [OK] http://nasty.example.org#nasty_string
165 // [OK] http://nasty.example.org:80/foo/xxx#nasty_string/bar
166 // [OK] ftp://nasty.example.org:80/dfsdfs
167 // [OK] ftp://cnn.example.com&story=breaking_news@10.0.0.1/top_story.htm (from RFC3986)
168 function uri_pickup($string = '')
169 {
170         if (! is_string($string)) return array();
171
172         // Not available for: IDN(ignored)
173         $array = array();
174         preg_match_all(
175                 // scheme://userinfo@host:port/path/or/pathinfo/maybefile.and?query=string#fragment
176                 // Refer RFC3986 (Regex below is not strict)
177                 '#(\b[a-z][a-z0-9.+-]{1,8}):[/\\\]+' .  // 1: Scheme
178                 '(?:' .
179                         '([^\s<>"\'\[\]/\#?@]*)' .              // 2: Userinfo (Username)
180                 '@)?' .
181                 '(' .
182                         // 3: Host
183                         '\[[0-9a-f:.]+\]' . '|' .                               // IPv6([colon-hex and dot]): RFC2732
184                         '(?:[0-9]{1,3}\.){3}[0-9]{1,3}' . '|' . // IPv4(dot-decimal): 001.22.3.44
185                         '[a-z0-9][a-z0-9.-]+[a-z0-9]' .                 // hostname(FQDN) : foo.example.org
186                 ')' .
187                 '(?::([0-9]*))?' .                                      // 4: Port
188                 '((?:/+[^\s<>"\'\[\]/\#]+)*/+)?' .      // 5: Directory path or path-info
189                 '([^\s<>"\'\[\]\#?]+)?' .                       // 6: File?
190                 '(?:\?([^\s<>"\'\[\]\#]+))?' .          // 7: Query string
191                 '(?:\#([a-z0-9._~%!$&\'()*+,;=:@-]*))?' .       // 8: Fragment
192                 '#i',
193                  $string, $array, PREG_SET_ORDER | PREG_OFFSET_CAPTURE
194         );
195
196         // Format the $array
197         static $parts = array(
198                 1 => 'scheme', 2 => 'userinfo', 3 => 'host', 4 => 'port',
199                 5 => 'path', 6 => 'file', 7 => 'query', 8 => 'fragment'
200         );
201         $default = array('');
202         foreach(array_keys($array) as $uri) {
203                 $_uri = & $array[$uri];
204                 array_rename_keys($_uri, $parts, TRUE, $default);
205                 $offset = $_uri['scheme'][1]; // Scheme's offset = URI's offset
206                 foreach(array_keys($_uri) as $part) {
207                         $_uri[$part] = & $_uri[$part][0];       // Remove offsets
208                 }
209         }
210
211         foreach(array_keys($array) as $uri) {
212                 $_uri = & $array[$uri];
213                 if ($_uri['scheme'] === '') {
214                         unset($array[$uri]);    // Considererd harmless
215                         continue;
216                 }
217                 unset($_uri[0]); // Matched string itself
218                 $_uri['area']['offset'] = $offset;      // Area offset for area_measure()
219         }
220
221         return $array;
222 }
223
224 // Normalize an array of URI arrays
225 // NOTE: Give me the uri_pickup() results
226 function uri_pickup_normalize(& $pickups, $destructive = TRUE)
227 {
228         if (! is_array($pickups)) return $pickups;
229
230         if ($destructive) {
231                 foreach (array_keys($pickups) as $key) {
232                         $_key = & $pickups[$key];
233                         $_key['scheme']   = isset($_key['scheme']) ? scheme_normalize($_key['scheme']) : '';
234                         $_key['host']     = isset($_key['host'])     ? host_normalize($_key['host']) : '';
235                         $_key['port']     = isset($_key['port'])       ? port_normalize($_key['port'], $_key['scheme'], FALSE) : '';
236                         $_key['path']     = isset($_key['path'])     ? strtolower(path_normalize($_key['path'])) : '';
237                         $_key['file']     = isset($_key['file'])     ? file_normalize($_key['file']) : '';
238                         $_key['query']    = isset($_key['query'])    ? query_normalize($_key['query']) : '';
239                         $_key['fragment'] = isset($_key['fragment']) ? strtolower($_key['fragment']) : '';
240                 }
241         } else {
242                 foreach (array_keys($pickups) as $key) {
243                         $_key = & $pickups[$key];
244                         $_key['scheme']   = isset($_key['scheme']) ? scheme_normalize($_key['scheme']) : '';
245                         $_key['host']     = isset($_key['host'])   ? strtolower($_key['host']) : '';
246                         $_key['port']     = isset($_key['port'])   ? port_normalize($_key['port'], $_key['scheme'], FALSE) : '';
247                         $_key['path']     = isset($_key['path'])   ? path_normalize($_key['path']) : '';
248                 }
249         }
250
251         return $pickups;
252 }
253
254 // An URI array => An URI (See uri_pickup())
255 // USAGE:
256 //      $pickups = uri_pickup('a string include some URIs');
257 //      $uris = array();
258 //      foreach (array_keys($pickups) as $key) {
259 //              $uris[$key] = uri_pickup_implode($pickups[$key]);
260 //      }
261 function uri_pickup_implode($uri = array())
262 {
263         if (empty($uri) || ! is_array($uri)) return NULL;
264
265         $tmp = array();
266         if (isset($uri['scheme']) && $uri['scheme'] !== '') {
267                 $tmp[] = & $uri['scheme'];
268                 $tmp[] = '://';
269         }
270         if (isset($uri['userinfo']) && $uri['userinfo'] !== '') {
271                 $tmp[] = & $uri['userinfo'];
272                 $tmp[] = '@';
273         }
274         if (isset($uri['host']) && $uri['host'] !== '') {
275                 $tmp[] = & $uri['host'];
276         }
277         if (isset($uri['port']) && $uri['port'] !== '') {
278                 $tmp[] = ':';
279                 $tmp[] = & $uri['port'];
280         }
281         if (isset($uri['path']) && $uri['path'] !== '') {
282                 $tmp[] = & $uri['path'];
283         }
284         if (isset($uri['file']) && $uri['file'] !== '') {
285                 $tmp[] = & $uri['file'];
286         }
287         if (isset($uri['query']) && $uri['query'] !== '') {
288                 $tmp[] = '?';
289                 $tmp[] = & $uri['query'];
290         }
291         if (isset($uri['fragment']) && $uri['fragment'] !== '') {
292                 $tmp[] = '#';
293                 $tmp[] = & $uri['fragment'];
294         }
295
296         return implode('', $tmp);
297 }
298
299 // $array['something'] => $array['wanted']
300 function array_rename_keys(& $array, $keys = array('from' => 'to'), $force = FALSE, $default = '')
301 {
302         if (! is_array($array) || ! is_array($keys)) return FALSE;
303
304         // Nondestructive test
305         if (! $force)
306                 foreach(array_keys($keys) as $from)
307                         if (! isset($array[$from]))
308                                 return FALSE;
309
310         foreach($keys as $from => $to) {
311                 if ($from === $to) continue;
312                 if (! $force || isset($array[$from])) {
313                         $array[$to] = & $array[$from];
314                         unset($array[$from]);
315                 } else  {
316                         $array[$to] = $default;
317                 }
318         }
319
320         return TRUE;
321 }
322
323 // ---------------------
324 // Area pickup
325
326 // Pickup all of markup areas
327 function area_pickup($string = '', $method = array())
328 {
329         $area = array();
330         if (empty($method)) return $area;
331
332         // Anchor tag pair by preg_match and preg_match_all()
333         // [OK] <a href></a>
334         // [OK] <a href=  >Good site!</a>
335         // [OK] <a href= "#" >test</a>
336         // [OK] <a href="http://nasty.example.com">visit http://nasty.example.com/</a>
337         // [OK] <a href=\'http://nasty.example.com/\' >discount foobar</a> 
338         // [NG] <a href="http://ng.example.com">visit http://ng.example.com _not_ended_
339         $regex = '#<a\b[^>]*\bhref\b[^>]*>.*?</a\b[^>]*(>)#is';
340         if (isset($method['area_anchor'])) {
341                 $areas = array();
342                 $count = isset($method['asap']) ?
343                         preg_match($regex, $string) :
344                         preg_match_all($regex, $string, $areas);
345                 if (! empty($count)) $area['area_anchor'] = $count;
346         }
347         if (isset($method['uri_anchor'])) {
348                 $areas = array();
349                 preg_match_all($regex, $string, $areas, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
350                 foreach(array_keys($areas) as $_area) {
351                         $areas[$_area] =  array(
352                                 $areas[$_area][0][1], // Area start (<a href>)
353                                 $areas[$_area][1][1], // Area end   (</a>)
354                         );
355                 }
356                 if (! empty($areas)) $area['uri_anchor'] = $areas;
357         }
358
359         // phpBB's "BBCode" pair by preg_match and preg_match_all()
360         // [OK] [url][/url]
361         // [OK] [url]http://nasty.example.com/[/url]
362         // [OK] [link]http://nasty.example.com/[/link]
363         // [OK] [url=http://nasty.example.com]visit http://nasty.example.com/[/url]
364         // [OK] [link http://nasty.example.com/]buy something[/link]
365         $regex = '#\[(url|link)\b[^\]]*\].*?\[/\1\b[^\]]*(\])#is';
366         if (isset($method['area_bbcode'])) {
367                 $areas = array();
368                 $count = isset($method['asap']) ?
369                         preg_match($regex, $string) :
370                         preg_match_all($regex, $string, $areas, PREG_SET_ORDER);
371                 if (! empty($count)) $area['area_bbcode'] = $count;
372         }
373         if (isset($method['uri_bbcode'])) {
374                 $areas = array();
375                 preg_match_all($regex, $string, $areas, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
376                 foreach(array_keys($areas) as $_area) {
377                         $areas[$_area] = array(
378                                 $areas[$_area][0][1], // Area start ([url])
379                                 $areas[$_area][2][1], // Area end   ([/url])
380                         );
381                 }
382                 if (! empty($areas)) $area['uri_bbcode'] = $areas;
383         }
384
385         // Various Wiki syntax
386         // [text_or_uri>text_or_uri]
387         // [text_or_uri:text_or_uri]
388         // [text_or_uri|text_or_uri]
389         // [text_or_uri->text_or_uri]
390         // [text_or_uri text_or_uri] // MediaWiki
391         // MediaWiki: [http://nasty.example.com/ visit http://nasty.example.com/]
392
393         return $area;
394 }
395
396 // If in doubt, it's a little doubtful
397 // if (Area => inside <= Area) $brief += -1
398 function area_measure($areas, & $array, $belief = -1, $a_key = 'area', $o_key = 'offset')
399 {
400         if (! is_array($areas) || ! is_array($array)) return;
401
402         $areas_keys = array_keys($areas);
403         foreach(array_keys($array) as $u_index) {
404                 $offset = isset($array[$u_index][$o_key]) ?
405                         intval($array[$u_index][$o_key]) : 0;
406                 foreach($areas_keys as $a_index) {
407                         if (isset($array[$u_index][$a_key])) {
408                                 $offset_s = intval($areas[$a_index][0]);
409                                 $offset_e = intval($areas[$a_index][1]);
410                                 // [Area => inside <= Area]
411                                 if ($offset_s < $offset && $offset < $offset_e) {
412                                         $array[$u_index][$a_key] += $belief;
413                                 }
414                         }
415                 }
416         }
417 }
418
419 // ---------------------
420 // Spam-uri pickup
421
422 // Domain exposure callback (See spam_uri_pickup_preprocess())
423 // http://victim.example.org/?foo+site:nasty.example.com+bar
424 // => http://nasty.example.com/?refer=victim.example.org
425 // NOTE: 'refer=' is not so good for (at this time).
426 // Consider about using IP address of the victim, try to avoid that.
427 function _preg_replace_callback_domain_exposure($matches = array())
428 {
429         $result = '';
430
431         // Preserve the victim URI as a complicity or ...
432         if (isset($matches[5])) {
433                 $result =
434                         $matches[1] . '://' .   // scheme
435                         $matches[2] . '/' .             // victim.example.org
436                         $matches[3];                    // The rest of all (before victim)
437         }
438
439         // Flipped URI
440         if (isset($matches[4])) {
441                 $result = 
442                         $matches[1] . '://' .   // scheme
443                         $matches[4] .                   // nasty.example.com
444                         '/?refer=' . strtolower($matches[2]) .  // victim.example.org
445                         ' ' . $result;
446         }
447
448         return $result;
449 }
450
451 // Preprocess: rawurldecode() and adding space(s) and something
452 // to detect/count some URIs _if possible_
453 // NOTE: It's maybe danger to var_dump(result). [e.g. 'javascript:']
454 // [OK] http://victim.example.org/?site:nasty.example.org
455 // [OK] http://victim.example.org/nasty.example.org
456 // [OK] http://victim.example.org/go?http%3A%2F%2Fnasty.example.org
457 // [OK] http://victim.example.org/http://nasty.example.org
458 function spam_uri_pickup_preprocess($string = '')
459 {
460         if (! is_string($string)) return '';
461
462         $string = rawurldecode($string);
463
464         // Domain exposure (simple)
465         // http://victim.example.org/nasty.example.org/path#frag
466         // => http://nasty.example.org/?refer=victim.example.org and original
467         $string = preg_replace(
468                 '#h?ttp://' .
469                 '(' .
470                         'ime\.nu' . '|' .       // 2ch.net
471                         'ime\.st' . '|' .       // 2ch.net
472                         'link\.toolbot\.com' . '|' .
473                         'urlx\.org' .
474                 ')' .
475                 '/([a-z0-9.%_-]+\.[a-z0-9.%_-]+)#i',    // nasty.example.org
476                 'http://$2/?refer=$1 $0',                               // Preserve $0 or remove?
477                 $string
478         );
479
480         // Domain exposure (gate-big5)
481         // http://victim.example.org/gate/big5/nasty.example.org/path
482         // => http://nasty.example.org/?refer=victim.example.org and original
483         $string = preg_replace(
484                 '#h?ttp://' .
485                 '(' .
486                         'big5.51job.com'         . '|' .
487                         'big5.china.com'         . '|' .
488                         'big5.xinhuanet.com' . '|' .
489                 ')' .
490                 '/gate/big5' .
491                 '/([a-z0-9.%_-]+\.[a-z0-9.%_-]+)' .
492                  '#i',  // nasty.example.org
493                 'http://$2/?refer=$1 $0',                               // Preserve $0 or remove?
494                 $string
495         );
496
497         // Domain exposure (See _preg_replace_callback_domain_exposure())
498         $string = preg_replace_callback(
499                 array(
500                         '#(http)://' .
501                         '(' .
502                                 // Something Google: http://www.google.com/supported_domains
503                                 '(?:[a-z0-9.]+\.)?google\.[a-z]{2,3}(?:\.[a-z]{2})?' .
504                                 '|' .
505                                 // AltaVista
506                                 '(?:[a-z0-9.]+\.)?altavista.com' .
507                                 
508                         ')' .
509                         '/' .
510                         '([a-z0-9?=&.%_/\'\\\+-]+)' .                           // path/?query=foo+bar+
511                         '\bsite:([a-z0-9.%_-]+\.[a-z0-9.%_-]+)' .       // site:nasty.example.com
512                         //'()' .        // Preserve or remove?
513                         '#i',
514                 ),
515                 '_preg_replace_callback_domain_exposure',
516                 $string
517         );
518
519         // URI exposure (uriuri => uri uri)
520         $string = preg_replace(
521                 array(
522                         '#(?<! )(?:https?|ftp):/#i',
523                 //      '#[a-z][a-z0-9.+-]{1,8}://#i',
524                 //      '#[a-z][a-z0-9.+-]{1,8}://#i'
525                 ),
526                 ' $0',
527                 $string
528         );
529
530         return $string;
531 }
532
533 // Main function of spam-uri pickup,
534 // A wrapper function of uri_pickup()
535 function spam_uri_pickup($string = '', $method = array())
536 {
537         if (! is_array($method) || empty($method)) {
538                 $method = check_uri_spam_method();
539         }
540
541         $string = spam_uri_pickup_preprocess($string);
542
543         $array  = uri_pickup($string);
544
545         // Area elevation of URIs, for '(especially external)link' intension
546         if (! empty($array)) {
547                 $_method = array();
548                 if (isset($method['uri_anchor'])) $_method['uri_anchor'] = & $method['uri_anchor'];
549                 if (isset($method['uri_bbcode'])) $_method['uri_bbcode'] = & $method['uri_bbcode'];
550                 $areas = area_pickup($string, $_method, TRUE);
551                 if (! empty($areas)) {
552                         $area_shadow = array();
553                         foreach (array_keys($array) as $key) {
554                                 $area_shadow[$key] = & $array[$key]['area'];
555                                 foreach (array_keys($_method) as $_key) {
556                                         $area_shadow[$key][$_key] = 0;
557                                 }
558                         }
559                         foreach (array_keys($_method) as $_key) {
560                                 if (isset($areas[$_key])) {
561                                         area_measure($areas[$_key], $area_shadow, 1, $_key);
562                                 }
563                         }
564                 }
565         }
566
567         // Remove 'offset's for area_measure()
568         foreach(array_keys($array) as $key)
569                 unset($array[$key]['area']['offset']);
570
571         return $array;
572 }
573
574
575 // ---------------------
576 // Normalization
577
578 // Scheme normalization: Renaming the schemes
579 // snntp://example.org =>  nntps://example.org
580 // NOTE: Keep the static lists simple. See also port_normalize().
581 function scheme_normalize($scheme = '', $abbrevs_harmfull = TRUE)
582 {
583         // Abbreviations they have no intention of link
584         static $abbrevs = array(
585                 'ttp'   => 'http',
586                 'ttps'  => 'https',
587         );
588
589         // Aliases => normalized ones
590         static $aliases = array(
591                 'pop'   => 'pop3',
592                 'news'  => 'nntp',
593                 'imap4' => 'imap',
594                 'snntp' => 'nntps',
595                 'snews' => 'nntps',
596                 'spop3' => 'pop3s',
597                 'pops'  => 'pop3s',
598         );
599
600         if (! is_string($scheme)) return '';
601
602         $scheme = strtolower($scheme);
603         if (isset($abbrevs[$scheme])) {
604                 $scheme = $abbrevs_harmfull ? $abbrevs[$scheme] : '';
605         }
606         if (isset($aliases[$scheme])) {
607                 $scheme = $aliases[$scheme];
608         }
609
610         return $scheme;
611 }
612
613 // Hostname normlization (Destructive)
614 // www.foo     => www.foo   ('foo' seems TLD)
615 // www.foo.bar => foo.bar
616 // www.10.20   => www.10.20 (Invalid hostname)
617 // NOTE:
618 //   'www' is  mostly used as traditional hostname of WWW server.
619 //   'www.foo.bar' may be identical with 'foo.bar'.
620 function host_normalize($host = '')
621 {
622         if (! is_string($host)) return '';
623
624         $host = strtolower($host);
625         $matches = array();
626         if (preg_match('/^www\.(.+\.[a-z]+)$/', $host, $matches)) {
627                 return $matches[1];
628         } else {
629                 return $host;
630         }
631 }
632
633 // Port normalization: Suppress the (redundant) default port
634 // HTTP://example.org:80/ => http://example.org/
635 // HTTP://example.org:8080/ => http://example.org:8080/
636 // HTTPS://example.org:443/ => https://example.org/
637 function port_normalize($port, $scheme, $scheme_normalize = FALSE)
638 {
639         // Schemes that users _maybe_ want to add protocol-handlers
640         // to their web browsers. (and attackers _maybe_ want to use ...)
641         // Reference: http://www.iana.org/assignments/port-numbers
642         static $array = array(
643                 // scheme => default port
644                 'ftp'     =>    21,
645                 'ssh'     =>    22,
646                 'telnet'  =>    23,
647                 'smtp'    =>    25,
648                 'tftp'    =>    69,
649                 'gopher'  =>    70,
650                 'finger'  =>    79,
651                 'http'    =>    80,
652                 'pop3'    =>   110,
653                 'sftp'    =>   115,
654                 'nntp'    =>   119,
655                 'imap'    =>   143,
656                 'irc'     =>   194,
657                 'wais'    =>   210,
658                 'https'   =>   443,
659                 'nntps'   =>   563,
660                 'rsync'   =>   873,
661                 'ftps'    =>   990,
662                 'telnets' =>   992,
663                 'imaps'   =>   993,
664                 'ircs'    =>   994,
665                 'pop3s'   =>   995,
666                 'mysql'   =>  3306,
667         );
668
669         // intval() converts '0-1' to '0', so preg_match() rejects these invalid ones
670         if (! is_numeric($port) || $port < 0 || preg_match('/[^0-9]/i', $port))
671                 return '';
672
673         $port = intval($port);
674         if ($scheme_normalize) $scheme = scheme_normalize($scheme);
675         if (isset($array[$scheme]) && $port == $array[$scheme])
676                 $port = ''; // Ignore the defaults
677
678         return $port;
679 }
680
681 // Path normalization
682 // http://example.org => http://example.org/
683 // http://example.org#hoge => http://example.org/#hoge
684 // http://example.org/path/a/b/./c////./d => http://example.org/path/a/b/c/d
685 // http://example.org/path/../../a/../back => http://example.org/back
686 function path_normalize($path = '', $divider = '/', $add_root = TRUE)
687 {
688         if (! is_string($divider)) return is_string($path) ? $path : '';
689
690         if ($add_root) {
691                 $first_div = & $divider;
692         } else {
693                 $first_div = '';
694         }
695         if (! is_string($path) || $path == '') return $first_div;
696
697         if (strpos($path, $divider, strlen($path) - strlen($divider)) === FALSE) {
698                 $last_div = '';
699         } else {
700                 $last_div = & $divider;
701         }
702
703         $array = explode($divider, $path);
704
705         // Remove paddings ('//' and '/./')
706         foreach(array_keys($array) as $key) {
707                 if ($array[$key] == '' || $array[$key] == '.') {
708                          unset($array[$key]);
709                 }
710         }
711
712         // Remove back-tracks ('/../')
713         $tmp = array();
714         foreach($array as $value) {
715                 if ($value == '..') {
716                         array_pop($tmp);
717                 } else {
718                         array_push($tmp, $value);
719                 }
720         }
721         $array = & $tmp;
722
723         if (empty($array)) {
724                 return $first_div;
725         } else {
726                 return $first_div . implode($divider, $array) . $last_div;
727         }
728 }
729
730 // DirectoryIndex normalize (Destructive and rough)
731 // TODO: sample.en.ja.html.gz => sample.html
732 function file_normalize($file = 'index.html.en')
733 {
734         static $simple_defaults = array(
735                 'default.htm'   => TRUE,
736                 'default.html'  => TRUE,
737                 'default.asp'   => TRUE,
738                 'default.aspx'  => TRUE,
739                 'index'                 => TRUE,        // Some system can omit the suffix
740         );
741
742         static $content_suffix = array(
743                 // index.xxx, sample.xxx
744                 'htm'   => TRUE,
745                 'html'  => TRUE,
746                 'shtml' => TRUE,
747                 'jsp'   => TRUE,
748                 'php'   => TRUE,
749                 'php3'  => TRUE,
750                 'php4'  => TRUE,
751                 'pl'    => TRUE,
752                 'py'    => TRUE,
753                 'rb'    => TRUE,
754                 'cgi'   => TRUE,
755                 'xml'   => TRUE,
756         );
757
758         static $language_suffix = array(
759                 // Reference: Apache 2.0.59 'AddLanguage' default
760                 'ca'    => TRUE,
761                 'cs'    => TRUE,        // cs
762                 'cz'    => TRUE,        // cs
763                 'de'    => TRUE,
764                 'dk'    => TRUE,        // da
765                 'el'    => TRUE,
766                 'en'    => TRUE,
767                 'eo'    => TRUE,
768                 'es'    => TRUE,
769                 'et'    => TRUE,
770                 'fr'    => TRUE,
771                 'he'    => TRUE,
772                 'hr'    => TRUE,
773                 'it'    => TRUE,
774                 'ja'    => TRUE,
775                 'ko'    => TRUE,
776                 'ltz'   => TRUE,
777                 'nl'    => TRUE,
778                 'nn'    => TRUE,
779                 'no'    => TRUE,
780                 'po'    => TRUE,
781                 'pt'    => TRUE,
782                 'pt-br' => TRUE,
783                 'ru'    => TRUE,
784                 'sv'    => TRUE,
785                 'zh-cn' => TRUE,
786                 'zh-tw' => TRUE,
787
788                 // Reference: Apache 2.0.59 default 'index.html' variants
789                 'ee'    => TRUE,
790                 'lb'    => TRUE,
791                 'var'   => TRUE,
792         );
793
794         static $charset_suffix = array(
795                 // Reference: Apache 2.0.59 'AddCharset' default
796                 'iso8859-1'     => TRUE, // ISO-8859-1
797                 'latin1'        => TRUE, // ISO-8859-1
798                 'iso8859-2'     => TRUE, // ISO-8859-2
799                 'latin2'        => TRUE, // ISO-8859-2
800                 'cen'           => TRUE, // ISO-8859-2
801                 'iso8859-3'     => TRUE, // ISO-8859-3
802                 'latin3'        => TRUE, // ISO-8859-3
803                 'iso8859-4'     => TRUE, // ISO-8859-4
804                 'latin4'        => TRUE, // ISO-8859-4
805                 'iso8859-5'     => TRUE, // ISO-8859-5
806                 'latin5'        => TRUE, // ISO-8859-5
807                 'cyr'           => TRUE, // ISO-8859-5
808                 'iso-ru'        => TRUE, // ISO-8859-5
809                 'iso8859-6'     => TRUE, // ISO-8859-6
810                 'latin6'        => TRUE, // ISO-8859-6
811                 'arb'           => TRUE, // ISO-8859-6
812                 'iso8859-7'     => TRUE, // ISO-8859-7
813                 'latin7'        => TRUE, // ISO-8859-7
814                 'grk'           => TRUE, // ISO-8859-7
815                 'iso8859-8'     => TRUE, // ISO-8859-8
816                 'latin8'        => TRUE, // ISO-8859-8
817                 'heb'           => TRUE, // ISO-8859-8
818                 'iso8859-9'     => TRUE, // ISO-8859-9
819                 'latin9'        => TRUE, // ISO-8859-9
820                 'trk'           => TRUE, // ISO-8859-9
821                 'iso2022-jp'=> TRUE, // ISO-2022-JP
822                 'jis'           => TRUE, // ISO-2022-JP
823                 'iso2022-kr'=> TRUE, // ISO-2022-KR
824                 'kis'           => TRUE, // ISO-2022-KR
825                 'iso2022-cn'=> TRUE, // ISO-2022-CN
826                 'cis'           => TRUE, // ISO-2022-CN
827                 'big5'          => TRUE,
828                 'cp-1251'       => TRUE, // ru, WINDOWS-1251
829                 'win-1251'      => TRUE, // ru, WINDOWS-1251
830                 'cp866'         => TRUE, // ru
831                 'koi8-r'        => TRUE, // ru, KOI8-r
832                 'koi8-ru'       => TRUE, // ru, KOI8-r
833                 'koi8-uk'       => TRUE, // ru, KOI8-ru
834                 'ua'            => TRUE, // ru, KOI8-ru
835                 'ucs2'          => TRUE, // ru, ISO-10646-UCS-2
836                 'ucs4'          => TRUE, // ru, ISO-10646-UCS-4
837                 'utf8'          => TRUE,
838
839                 // Reference: Apache 2.0.59 default 'index.html' variants
840                 'euc-kr'        => TRUE,
841                 'gb2312'        => TRUE,
842         );
843
844         // May uncompress by web browsers on the fly
845         // Must be at the last of the filename
846         // Reference: Apache 2.0.59 'AddEncoding'
847         static $encoding_suffix = array(
848                 'z'             => TRUE,
849                 'gz'    => TRUE,
850         );
851
852         if (! is_string($file)) return '';
853         $_file = strtolower($file);
854         if (isset($simple_defaults[$_file])) return '';
855
856
857         // Roughly removing language/character-set/encoding suffixes
858         // References:
859         //  * Apache 2 document about 'Content-negotiaton', 'mod_mime' and 'mod_negotiation'
860         //    http://httpd.apache.org/docs/2.0/content-negotiation.html
861         //    http://httpd.apache.org/docs/2.0/mod/mod_mime.html
862         //    http://httpd.apache.org/docs/2.0/mod/mod_negotiation.html
863         //  * http://www.iana.org/assignments/character-sets
864         //  * RFC3066: Tags for the Identification of Languages
865         //    http://www.ietf.org/rfc/rfc3066.txt
866         //  * ISO 639: codes of 'language names'
867         $suffixes = explode('.', $_file);
868         $body = array_shift($suffixes);
869         if ($suffixes) {
870                 // Remove the last .gz/.z
871                 $last_key = end(array_keys($suffixes));
872                 if (isset($encoding_suffix[$suffixes[$last_key]])) {
873                         unset($suffixes[$last_key]);
874                 }
875         }
876         // Cut language and charset suffixes
877         foreach($suffixes as $key => $value){
878                 if (isset($language_suffix[$value]) || isset($charset_suffix[$value])) {
879                         unset($suffixes[$key]);
880                 }
881         }
882         if (empty($suffixes)) return $body;
883
884         // Index.xxx
885         $count = count($suffixes);
886         reset($suffixes);
887         $current = current($suffixes);
888         if ($body == 'index' && $count == 1 && isset($content_suffix[$current])) return '';
889
890         return $file;
891 }
892
893 // Sort query-strings if possible (Destructive and rough)
894 // [OK] &&&&f=d&b&d&c&a=0dd  =>  a=0dd&b&c&d&f=d
895 // [OK] nothing==&eg=dummy&eg=padding&eg=foobar  =>  eg=foobar
896 function query_normalize($string = '', $equal = TRUE, $equal_cutempty = TRUE, $stortolower = TRUE)
897 {
898         if (! is_string($string)) return '';
899         if ($stortolower) $string = strtolower($string);
900
901         $array = explode('&', $string);
902
903         // Remove '&' paddings
904         foreach(array_keys($array) as $key) {
905                 if ($array[$key] == '') {
906                          unset($array[$key]);
907                 }
908         }
909
910         // Consider '='-sepalated input and paddings
911         if ($equal) {
912                 $equals = $not_equals = array();
913                 foreach ($array as $part) {
914                         if (strpos($part, '=') === FALSE) {
915                                  $not_equals[] = $part;
916                         } else {
917                                 list($key, $value) = explode('=', $part, 2);
918                                 $value = ltrim($value, '=');
919                                 if (! $equal_cutempty || $value != '') {
920                                         $equals[$key] = $value;
921                                 }
922                         }
923                 }
924
925                 $array = & $not_equals;
926                 foreach ($equals as $key => $value) {
927                         $array[] = $key . '=' . $value;
928                 }
929                 unset($equals);
930         }
931
932         natsort($array);
933         return implode('&', $array);
934 }
935
936 // ---------------------
937 // Part One : Checker
938
939 // Rough implementation of globbing
940 //
941 // USAGE: $regex = '/^' . generate_glob_regex('*.txt', '/') . '$/i';
942 //
943 function generate_glob_regex($string = '', $divider = '/')
944 {
945         static $from = array(
946                          1 => '*',
947                         11 => '?',
948         //              22 => '[',      // Maybe cause regex compilation error (e.g. '[]')
949         //              23 => ']',      //
950                 );
951         static $mid = array(
952                          1 => '_AST_',
953                         11 => '_QUE_',
954         //              22 => '_RBR_',
955         //              23 => '_LBR_',
956                 );
957         static $to = array(
958                          1 => '.*',
959                         11 => '.',
960         //              22 => '[',
961         //              23 => ']',
962                 );
963
964         if (! is_string($string)) return '';
965
966         $string = str_replace($from, $mid, $string); // Hide
967         $string = preg_quote($string, $divider);
968         $string = str_replace($mid, $to, $string);   // Unhide
969
970         return $string;
971 }
972
973 // Rough hostname checker
974 // [OK] 192.168.
975 // TODO: Strict digit, 0x, CIDR, IPv6
976 function is_ip($string = '')
977 {
978         if (preg_match('/^' .
979                 '(?:[0-9]{1,3}\.){3}[0-9]{1,3}' . '|' .
980                 '(?:[0-9]{1,3}\.){1,3}' . '$/',
981                 $string)) {
982                 return 4;       // Seems IPv4(dot-decimal)
983         } else {
984                 return 0;       // Seems not IP
985         }
986 }
987
988 // Generate host (FQDN, IPv4, ...) regex
989 // 'localhost'     : Matches with 'localhost' only
990 // 'example.org'   : Matches with 'example.org' only (See host_normalize() about 'www')
991 // '.example.org'  : Matches with ALL FQDN ended with '.example.org'
992 // '*.example.org' : Almost the same of '.example.org' except 'www.example.org'
993 // '10.20.30.40'   : Matches with IPv4 address '10.20.30.40' only
994 // [TODO] '192.'   : Matches with all IPv4 hosts started with '192.'
995 // TODO: IPv4, CIDR?, IPv6
996 function generate_host_regex($string = '', $divider = '/')
997 {
998         if (! is_string($string)) return '';
999
1000         if (mb_strpos($string, '.') === FALSE)
1001                 return generate_glob_regex($string, $divider);
1002
1003         $result = '';
1004         if (is_ip($string)) {
1005                 // IPv4
1006                 return generate_glob_regex($string, $divider);
1007         } else {
1008                 // FQDN or something
1009                 $part = explode('.', $string, 2);
1010                 if ($part[0] == '') {
1011                         $part[0] = '(?:.*\.)?'; // And all related FQDN
1012                 } else if ($part[0] == '*') {
1013                         $part[0] = '.*\.';      // All subdomains/hosts only
1014                 } else {
1015                         return generate_glob_regex($string, $divider);
1016                 }
1017                 $part[1] = generate_glob_regex($part[1], $divider);
1018                 return implode('', $part);
1019         }
1020 }
1021
1022 function get_blocklist($list = '')
1023 {
1024         static $regexes;
1025
1026         if ($list === NULL) {
1027                 $regexes = NULL;        // Unset
1028                 return array();
1029         }
1030
1031         if (! isset($regexes)) {
1032                 $regexes = array();
1033                 if (file_exists(SPAM_INI_FILE)) {
1034                         $blocklist = array();
1035                         include(SPAM_INI_FILE);
1036                         //      $blocklist['badhost'] = array(
1037                         //              '*.blogspot.com',       // Blog services's subdomains (only)
1038                         //              'IANA-examples' => '#^(?:.*\.)?example\.(?:com|net|org)$#',
1039                         //      );
1040                         if (isset($blocklist['list'])) {
1041                                 $regexes['list'] = & $blocklist['list'];
1042                         } else {
1043                                 // Default
1044                                 $blocklist['list'] = array(
1045                                         'goodhost' => FALSE,
1046                                         'badhost'  => TRUE,
1047                                 );
1048                         }
1049                         foreach(array_keys($blocklist['list']) as $_list) {
1050                                 if (! isset($blocklist[$_list])) continue;
1051                                 foreach ($blocklist[$_list] as $key => $value) {
1052                                         if (is_array($value)) {
1053                                                 $regexes[$_list][$key] = array();
1054                                                 foreach($value as $_key => $_value) {
1055                                                         get_blocklist_add($regexes[$_list][$key], $_key, $_value);
1056                                                 }
1057                                         } else {
1058                                                 get_blocklist_add($regexes[$_list], $key, $value);
1059                                         }
1060                                 }
1061                                 unset($blocklist[$_list]);
1062                         }
1063                 }
1064         }
1065
1066         if ($list === '') {
1067                 return $regexes;        // ALL
1068         } else if (isset($regexes[$list])) {
1069                 return $regexes[$list];
1070         } else {
1071                 return array();
1072         }
1073 }
1074
1075 // Subroutine of get_blocklist()
1076 function get_blocklist_add(& $array, $key = 0, $value = '*.example.org')
1077 {
1078         if (is_string($key)) {
1079                 $array[$key] = & $value; // Treat $value as a regex
1080         } else {
1081                 $array[$value] = '/^' . generate_host_regex($value, '/') . '$/i';
1082         }
1083 }
1084
1085 // Blocklist metrics: Separate $host, to $blocked and not blocked
1086 function blocklist_distiller(& $hosts, $keys = array('goodhost', 'badhost'), $asap = FALSE)
1087 {
1088         if (! is_array($hosts)) $hosts = array($hosts);
1089         if (! is_array($keys))  $keys  = array($keys);
1090
1091         $list = get_blocklist('list');
1092         $blocked = array();
1093
1094         foreach($keys as $key){
1095                 foreach (get_blocklist($key) as $label => $regex) {
1096                         if (is_array($regex)) {
1097                                 foreach($regex as $_label => $_regex) {
1098                                         $group = preg_grep($_regex, $hosts);
1099                                         if ($group) {
1100                                                 $hosts = array_diff($hosts, $group);
1101                                                 $blocked[$key][$label][$_label] = $group;
1102                                                 if ($asap && $list[$key]) break;
1103                                         }
1104                                 }
1105                         } else {
1106                                 $group = preg_grep($regex, $hosts);
1107                                 if ($group) {
1108                                         $hosts = array_diff($hosts, $group);
1109                                         $blocked[$key][$label] = $group;
1110                                         if ($asap && $list[$key]) break;
1111                                 }
1112                         }
1113                 }
1114         }
1115
1116         return $blocked;
1117 }
1118
1119 // Default (enabled) methods and thresholds (for content insertion)
1120 function check_uri_spam_method($times = 1, $t_area = 0, $rule = TRUE)
1121 {
1122         $times  = intval($times);
1123         $t_area = intval($t_area);
1124
1125         $positive = array(
1126                 // Thresholds
1127                 'quantity'     =>  8 * $times,  // Allow N URIs
1128                 'non_uniqhost' =>  3 * $times,  // Allow N duped (and normalized) Hosts
1129                 //'non_uniquri'=>  3 * $times,  // Allow N duped (and normalized) URIs
1130
1131                 // Areas
1132                 'area_anchor'  => $t_area,      // Using <a href> HTML tag
1133                 'area_bbcode'  => $t_area,      // Using [url] or [link] BBCode
1134                 //'uri_anchor' => $t_area,      // URI inside <a href> HTML tag
1135                 //'uri_bbcode' => $t_area,      // URI inside [url] or [link] BBCode
1136         );
1137         if ($rule) {
1138                 $bool = array(
1139                         // Rules
1140                         //'asap'   => TRUE,     // Quit or return As Soon As Possible
1141                         'uniqhost' => TRUE,     // Show uniq host (at block notification mail)
1142                         'badhost'  => TRUE,     // Check badhost
1143                 );
1144         } else {
1145                 $bool = array();
1146         }
1147
1148         // Remove non-$positive values
1149         foreach (array_keys($positive) as $key) {
1150                 if ($positive[$key] < 0) unset($positive[$key]);
1151         }
1152
1153         return $positive + $bool;
1154 }
1155
1156 // Simple/fast spam check
1157 function check_uri_spam($target = '', $method = array())
1158 {
1159         // Return value
1160         $progress = array(
1161                 'method'  => array(
1162                         // Theme to do  => Dummy, optional value, or optional array()
1163                         //'quantity'    => 8,
1164                         //'uniqhost'    => TRUE,
1165                         //'non_uniqhost'=> 3,
1166                         //'non_uniquri' => 3,
1167                         //'badhost'     => TRUE,
1168                         //'area_anchor' => 0,
1169                         //'area_bbcode' => 0,
1170                         //'uri_anchor'  => 0,
1171                         //'uri_bbcode'  => 0,
1172                 ),
1173                 'sum' => array(
1174                         // Theme        => Volume found (int)
1175                 ),
1176                 'is_spam' => array(
1177                         // Flag. If someting defined here,
1178                         // one or more spam will be included
1179                         // in this report
1180                 ),
1181                 'blocked' => array(
1182                         // Hosts blocked
1183                         //'category' => array(
1184                         //      'host',
1185                         //)
1186                 ),
1187                 'hosts' => array(
1188                         // Hosts not blocked
1189                 ),
1190         );
1191
1192         // Aliases
1193         $sum     = & $progress['sum'];
1194         $is_spam = & $progress['is_spam'];
1195         $progress['method'] = & $method;        // Argument
1196         $blocked = & $progress['blocked'];
1197         $hosts   = & $progress['hosts'];
1198         $asap    = isset($method['asap']);
1199
1200         // Init
1201         if (! is_array($method) || empty($method)) {
1202                 $method = check_uri_spam_method();
1203         }
1204         foreach(array_keys($method) as $key) {
1205                 if (! isset($sum[$key])) $sum[$key] = 0;
1206         }
1207
1208         if (is_array($target)) {
1209                 foreach($target as $str) {
1210                         if (! is_string($str)) continue;
1211
1212                         $_progress = check_uri_spam($str, $method);     // Recurse
1213
1214                         // Merge $sum
1215                         $_sum = & $_progress['sum'];
1216                         foreach (array_keys($_sum) as $key) {
1217                                 if (! isset($sum[$key])) {
1218                                         $sum[$key] = & $_sum[$key];
1219                                 } else {
1220                                         $sum[$key] += $_sum[$key];
1221                                 }
1222                         }
1223
1224                         // Merge $is_spam
1225                         $_is_spam = & $_progress['is_spam'];
1226                         foreach (array_keys($_is_spam) as $key) {
1227                                 $is_spam[$key] = TRUE;
1228                                 if ($asap) break;
1229                         }
1230                         if ($asap && $is_spam) break;
1231
1232                         // Merge only
1233                         $blocked = array_merge_recursive($blocked, $_progress['blocked']);
1234                         $hosts   = array_merge_recursive($hosts,   $_progress['hosts']);
1235                 }
1236
1237                 // Unique values
1238                 $blocked = array_unique_recursive($blocked);
1239                 $hosts   = array_unique_recursive($hosts);
1240
1241                 // Recount $sum['badhost']
1242                 $sum['badhost'] = array_count_leaves($blocked);
1243
1244                 return $progress;
1245         }
1246
1247         // Area: There's HTML anchor tag
1248         if ((! $asap || ! $is_spam) && isset($method['area_anchor'])) {
1249                 $key = 'area_anchor';
1250                 $_asap = isset($method['asap']) ? array('asap' => TRUE) : array();
1251                 $result = area_pickup($target, array($key => TRUE) + $_asap);
1252                 if ($result) {
1253                         $sum[$key] = $result[$key];
1254                         if (isset($method[$key]) && $sum[$key] > $method[$key]) {
1255                                 $is_spam[$key] = TRUE;
1256                         }
1257                 }
1258         }
1259
1260         // Area: There's 'BBCode' linking tag
1261         if ((! $asap || ! $is_spam) && isset($method['area_bbcode'])) {
1262                 $key = 'area_bbcode';
1263                 $_asap = isset($method['asap']) ? array('asap' => TRUE) : array();
1264                 $result = area_pickup($target, array($key => TRUE) + $_asap);
1265                 if ($result) {
1266                         $sum[$key] = $result[$key];
1267                         if (isset($method[$key]) && $sum[$key] > $method[$key]) {
1268                                 $is_spam[$key] = TRUE;
1269                         }
1270                 }
1271         }
1272
1273         // Return if ...
1274         if ($asap && $is_spam) return $progress;
1275
1276         // URI: Pickup
1277         $pickups = uri_pickup_normalize(spam_uri_pickup($target, $method));
1278
1279         // Return if ...
1280         if (empty($pickups)) return $progress;
1281
1282         // URI: Check quantity
1283         $sum['quantity'] += count($pickups);
1284                 // URI quantity
1285         if ((! $asap || ! $is_spam) && isset($method['quantity']) &&
1286                 $sum['quantity'] > $method['quantity']) {
1287                 $is_spam['quantity'] = TRUE;
1288         }
1289
1290         // URI: used inside HTML anchor tag pair
1291         if ((! $asap || ! $is_spam) && isset($method['uri_anchor'])) {
1292                 $key = 'uri_anchor';
1293                 foreach($pickups as $pickup) {
1294                         if (isset($pickup['area'][$key])) {
1295                                 $sum[$key] += $pickup['area'][$key];
1296                                 if(isset($method[$key]) &&
1297                                         $sum[$key] > $method[$key]) {
1298                                         $is_spam[$key] = TRUE;
1299                                         if ($asap && $is_spam) break;
1300                                 }
1301                                 if ($asap && $is_spam) break;
1302                         }
1303                 }
1304         }
1305
1306         // URI: used inside 'BBCode' pair
1307         if ((! $asap || ! $is_spam) && isset($method['uri_bbcode'])) {
1308                 $key = 'uri_bbcode';
1309                 foreach($pickups as $pickup) {
1310                         if (isset($pickup['area'][$key])) {
1311                                 $sum[$key] += $pickup['area'][$key];
1312                                 if(isset($method[$key]) &&
1313                                         $sum[$key] > $method[$key]) {
1314                                         $is_spam[$key] = TRUE;
1315                                         if ($asap && $is_spam) break;
1316                                 }
1317                                 if ($asap && $is_spam) break;
1318                         }
1319                 }
1320         }
1321
1322         // URI: Uniqueness (and removing non-uniques)
1323         if ((! $asap || ! $is_spam) && isset($method['non_uniquri'])) {
1324
1325                 $uris = array();
1326                 foreach (array_keys($pickups) as $key) {
1327                         $uris[$key] = uri_pickup_implode($pickups[$key]);
1328                 }
1329                 $count = count($uris);
1330                 $uris  = array_unique($uris);
1331                 $sum['non_uniquri'] += $count - count($uris);
1332                 if ($sum['non_uniquri'] > $method['non_uniquri']) {
1333                         $is_spam['non_uniquri'] = TRUE;
1334                 }
1335                 if (! $asap || ! $is_spam) {
1336                         foreach (array_diff(array_keys($pickups),
1337                                 array_keys($uris)) as $remove) {
1338                                 unset($pickups[$remove]);
1339                         }
1340                 }
1341                 unset($uris);
1342         }
1343
1344         // Return if ...
1345         if ($asap && $is_spam) return $progress;
1346
1347         // Host: Uniqueness (uniq / non-uniq)
1348         foreach ($pickups as $pickup) $hosts[] = & $pickup['host'];
1349         $hosts = array_unique($hosts);
1350         $sum['uniqhost'] += count($hosts);
1351         if ((! $asap || ! $is_spam) && isset($method['non_uniqhost'])) {
1352                 $sum['non_uniqhost'] = $sum['quantity'] - $sum['uniqhost'];
1353                 if ($sum['non_uniqhost'] > $method['non_uniqhost']) {
1354                         $is_spam['non_uniqhost'] = TRUE;
1355                 }
1356         }
1357
1358         // Return if ...
1359         if ($asap && $is_spam) return $progress;
1360
1361         // URI: Bad host (Separate good/bad hosts from $hosts)
1362         if ((! $asap || ! $is_spam) && isset($method['badhost'])) {
1363
1364                 // is_badhost()
1365                 $list = get_blocklist('list');
1366                 $blocked = blocklist_distiller($hosts, array_keys($list), $asap);
1367                 foreach($list as $key=>$type){
1368                         if (! $type) unset($blocked[$key]); // Ignore goodhost etc
1369                 }
1370                 unset($list);
1371
1372                 if (! empty($blocked)) $is_spam['badhost'] = TRUE;
1373         }
1374
1375         return $progress;
1376 }
1377
1378 // Count leaves (A leaf = value that is not an array, or an empty array)
1379 function array_count_leaves($array = array(), $count_empty = FALSE)
1380 {
1381         if (! is_array($array) || (empty($array) && $count_empty)) return 1;
1382
1383         // Recurse
1384         $count = 0;
1385         foreach ($array as $part) {
1386                 $count += array_count_leaves($part, $count_empty);
1387         }
1388         return $count;
1389 }
1390
1391 // An array-leaves to a flat array
1392 function array_flat_leaves($array, $unique = TRUE)
1393 {
1394         if (! is_array($array)) return $array;
1395
1396         $tmp = array();
1397         foreach(array_keys($array) as $key) {
1398                 if (is_array($array[$key])) {
1399                         // Recurse
1400                         foreach(array_flat_leaves($array[$key]) as $_value) {
1401                                 $tmp[] = $_value;
1402                         }
1403                 } else {
1404                         $tmp[] = & $array[$key];
1405                 }
1406         }
1407
1408         return $unique ? array_values(array_unique($tmp)) : $tmp;
1409 }
1410
1411 // An array() to an array leaf
1412 function array_leaf($array = array('A', 'B', 'C.D'), $stem = FALSE, $edge = TRUE)
1413 {
1414         if (! is_array($array)) return $array;
1415
1416         $leaf = array();
1417         $tmp  = & $leaf;
1418         foreach($array as $arg) {
1419                 if (! is_string($arg) && ! is_int($arg)) continue;
1420                 $tmp[$arg] = array();
1421                 $parent    = & $tmp;
1422                 $tmp       = & $tmp[$arg];
1423         }
1424         if ($stem) {
1425                 $parent[key($parent)] = & $edge;
1426         } else {
1427                 $parent = key($parent);
1428         }
1429
1430         return $leaf;   // array('A' => array('B' => 'C.D'))
1431 }
1432
1433
1434 // ---------------------
1435 // Reporting
1436
1437 // Summarize $progress (blocked only)
1438 function summarize_spam_progress($progress = array(), $blockedonly = FALSE)
1439 {
1440         if ($blockedonly) {
1441                 $tmp = array_keys($progress['is_spam']);
1442         } else {
1443                 $tmp = array();
1444                 $method = & $progress['method'];
1445                 if (isset($progress['sum'])) {
1446                         foreach ($progress['sum'] as $key => $value) {
1447                                 if (isset($method[$key]) && $value) {
1448                                         $tmp[] = $key . '(' . $value . ')';
1449                                 }
1450                         }
1451                 }
1452         }
1453
1454         return implode(', ', $tmp);
1455 }
1456
1457 function summarize_detail_badhost($progress = array())
1458 {
1459         if (! isset($progress['blocked']) || empty($progress['blocked'])) return '';
1460
1461         // Flat per group
1462         $blocked = array();
1463         foreach($progress['blocked'] as $list => $lvalue) {
1464                 foreach($lvalue as $group => $gvalue) {
1465                         $flat = implode(', ', array_flat_leaves($gvalue));
1466                         if ($flat === $group) {
1467                                 $blocked[$list][]       = $flat;
1468                         } else {
1469                                 $blocked[$list][$group] = $flat;
1470                         }
1471                 }
1472         }
1473
1474         // Shrink per list
1475         // From: 'A-1' => array('ie.to')
1476         // To:   'A-1' => 'ie.to'
1477         foreach($blocked as $list => $lvalue) {
1478                 if (is_array($lvalue) &&
1479                    count($lvalue) == 1 &&
1480                    is_numeric(key($lvalue))) {
1481                     $blocked[$list] = current($lvalue);
1482                 }
1483         }
1484
1485         return var_export_shrink($blocked, TRUE, TRUE);
1486 }
1487
1488 function summarize_detail_newtral($progress = array())
1489 {
1490         if (! isset($progress['hosts'])    ||
1491             ! is_array($progress['hosts']) ||
1492             empty($progress['hosts'])) return '';
1493
1494         $result = '';
1495         if (FALSE) {
1496                 // Sort by domain
1497                 $tmp = array();
1498                 foreach($progress['hosts'] as $value) {
1499                         $tmp[delimiter_reverse($value)] = $value;
1500                 }
1501                 ksort($tmp, SORT_STRING);
1502                 $result = count($tmp) . ' (' .implode(', ', $tmp) . ')';
1503         } else {
1504                 $tmp = array();
1505                 foreach($progress['hosts'] as $value) {
1506                         $tmp = array_merge_recursive(
1507                                 $tmp,
1508                                 array_leaf(explode('.', delimiter_reverse($value)), TRUE, $value)
1509                         );
1510                 }
1511
1512 //var_dump($tmp);
1513 // TODO: IP address 1.2.3.4 => "0"-3-2-1 by array_shrinkbranch_leaves()
1514
1515                 array_shrinkbranch_leaves($tmp, '.', TRUE); // "domain.tld"
1516                 array_joinbranch_leaf($tmp, '.', 0, TRUE);
1517                 foreach($tmp as $key => $value) {
1518                         if (is_array($value)) {
1519                                 ksort($tmp[$key], SORT_STRING);
1520                                 $tmp[$key] = implode(', ', array_flat_leaves($value));
1521                         }
1522                 }
1523                 ksort($tmp, SORT_STRING);
1524
1525                 $result = var_export_shrink($tmp, TRUE, TRUE);
1526         }
1527
1528         return $result;
1529 }
1530
1531 // array('F' => array('B' => array('C' => array('d' => array('' => 'foobar')))))
1532 // to
1533 // array('F.B.C.d.' => 'foobar')
1534 function array_joinbranch_leaf(& $array, $delim = '.', $limit = 0, $reverse = FALSE)
1535 {
1536         $result = array();
1537         if (! is_array($array)) return $result; // Nothing to do
1538
1539         $limit  = max(0, intval($limit));
1540         $cstack = array();
1541
1542         foreach(array_keys($array) as $key) {
1543                 $kstack = array();
1544                 $k      = -1;
1545
1546                 $single = array($key => & $array[$key]);        // Keep it single
1547                 $cursor = & $single;
1548                 while(is_array($cursor) && count($cursor) == 1) {       // Once
1549                         ++$k;
1550                         $kstack[] = key($cursor);
1551                         $cursor   = & $cursor[$kstack[$k]];
1552                         if ($limit != 0 && $k == $limit) break;
1553                 }
1554
1555                 // Relink
1556                 if ($k != 0) {
1557                         if ($reverse) $kstack = array_reverse($kstack);
1558                         $joinkey = implode($delim, $kstack);
1559
1560                         unset($array[$key]);
1561                         $array[$joinkey]  = & $cursor;
1562                         $result[$joinkey] = $k + 1;     // Key seems not an single array => joined length
1563                 }
1564         }
1565
1566         return $result;
1567 }
1568
1569
1570 // array('A' => array('B' => 'C')) to
1571 // array('A.B' => 'C')
1572 // array(
1573 //      'A' => array(
1574 //              'B' => array(
1575 //                      'C' => array(
1576 //                              'D' => '1'
1577 //                      ),
1578 //              ),
1579 //      ),
1580 //      'G' => array(
1581 //              'H' => '2'
1582 //      ),
1583 // )
1584 // to
1585 // array (
1586 //      'G.H'     => '2',
1587 //      'A.B.C.D' => '1',
1588 // )
1589 function array_shrinkbranch_leaves(& $array, $delim = '.', $reverse = FALSE, $recurse = FALSE)
1590 {
1591         $result = 0;
1592         if (! is_array($array) || empty($array)) return $result;
1593
1594         foreach(array_keys($array) as $key) {
1595                 $branch = & $array[$key];
1596                 if (! is_array($branch) || empty($branch)) continue;
1597
1598                 foreach(array_keys($branch) as $bkey) {
1599                         $joinkey = $reverse ?
1600                                 $bkey . $delim . $key :
1601                                 $key  . $delim . $bkey;
1602                         $array[$joinkey] = & $branch[$bkey];
1603                         unset($array[$key]);
1604                         ++$result;
1605                 }
1606         }
1607
1608         // Rescan (Recurse)
1609         if ($recurse && $result) {
1610                 $result = array_shrinkbranch_leaves($array, $delim, $reverse, $recurse);
1611         }
1612
1613         return $result; // Tell me how many
1614 }
1615 //$a = array (
1616 //      'edu' => array (
1617 //              'berkeley' => array (
1618 //                      'polisci' => array (
1619 //                              '' => 'polisci.berkeley.edu',
1620 //                      ),
1621 //              ),
1622 //              'cmich' => array (
1623 //                      'rso' => array (
1624 //                              '' => 'rso.cmich.edu',
1625 //                      ),
1626 //              ),
1627 //      ),
1628 //);
1629 //array_shrinkbranch_leaves($a, '.', TRUE);
1630 //var_export($a);
1631
1632 //$a = array (
1633 //      '4' => array (
1634 //              '5' => array (
1635 //                      '6' => array (
1636 //                              '' => '7.8.9',
1637 //                      ),
1638 //              ),
1639 //      ),
1640 //);
1641 //array_shrinkbranch_leaves($a, '.', TRUE);
1642 //var_export($a);
1643
1644
1645
1646 // Check responsibility-root of the FQDN
1647 // 'foobar.example.co.jp'      => 'example.co.jp'      (.co.jp      seems public)
1648 // 'foobar.example.act.edu.au' => 'example.act.edu.au' (.act.edu.au seems public)
1649 // 'foobar.example.com'        => 'example.com'        (.com        seems public)
1650 function domain_responsibility($fqdn = 'fqdn.foo.bar.example.com', $implicit = TRUE)
1651 {
1652         // Domains who have 2nd and/or 3rd level domains
1653         static $domain = array(
1654
1655                 // ccTLD Australia http://www.auda.org.au/ http://www.aunic.net/ http://www.ausregistry.com.au/
1656                 'au' => array(
1657                         // ".au Second Level Domains" http://www.auda.org.au/domains/
1658                         'asn'   => TRUE,
1659                         'com'   => TRUE,
1660                         'conf'  => TRUE,
1661                         'csiro' => TRUE,
1662                         'edu'   => array(       // http://www.domainname.edu.au/
1663                                 'act' => TRUE,
1664                                 'nt'  => TRUE,
1665                                 'nsw' => TRUE,
1666                                 'qld' => TRUE,
1667                                 'sa'  => TRUE,
1668                                 'tas' => TRUE,
1669                                 'vic' => TRUE,
1670                                 'wa'  => TRUE,
1671                         ),
1672                         'gov'   => array(
1673                                 'act' => TRUE,  // Australian Capital Territory
1674                                 'nt'  => TRUE,  // Northern Territory
1675                                 'nsw' => TRUE,  // New South Wales
1676                                 'qld' => TRUE,  // Queensland
1677                                 'sa'  => TRUE,  // South Australia
1678                                 'tas' => TRUE,  // Tasmania
1679                                 'vic' => TRUE,  // Victoria
1680                                 'wa'  => TRUE,  // Western Australia
1681                         ),
1682                         'id'    => TRUE,
1683                         'net'   => TRUE,
1684                         'org'   => TRUE,
1685                         'info'  => TRUE,
1686                 ),
1687
1688                 // ccTLD Japan http://jprs.co.jp/en/ http://whois.jprs.jp/en/
1689                 'jp' => array(
1690                         // http://jprs.co.jp/en/jpdomain.html
1691
1692                         // Organizational
1693                         'ac'  => TRUE,
1694                         'ad'  => TRUE,
1695                         'co'  => TRUE,
1696                         'go'  => TRUE,
1697                         'gr'  => TRUE,
1698                         'lg'  => TRUE,
1699                         'ne'  => TRUE,
1700                         'or'  => TRUE,
1701
1702                         // Geographic
1703                         //
1704                         // Example of 3rd level domains
1705                         //'kumamoto'  => array(
1706                         //      // http://www.pref.kumamoto.jp/link/list.asp#4
1707                         //      'amakusa'   => TRUE,
1708                         //      'hitoyoshi' => TRUE,
1709                         //      'jonan'     => TRUE,
1710                         //      'kumamoto'  => TRUE,
1711                         //      ...
1712                         //),
1713                         'aichi'     => TRUE,
1714                         'akita'     => TRUE,
1715                         'aomori'    => TRUE,
1716                         'chiba'     => TRUE,
1717                         'ehime'     => TRUE,
1718                         'fukui'     => TRUE,
1719                         'fukuoka'   => TRUE,
1720                         'fukushima' => TRUE,
1721                         'gifu'      => TRUE,
1722                         'gunma'     => TRUE,
1723                         'hiroshima' => TRUE,
1724                         'hokkaido'  => TRUE,
1725                         'hyogo'     => TRUE,
1726                         'ibaraki'   => TRUE,
1727                         'ishikawa'  => TRUE,
1728                         'iwate'     => TRUE,
1729                         'kagawa'    => TRUE,
1730                         'kagoshima' => TRUE,
1731                         'kanagawa'  => TRUE,
1732                         'kawasaki'  => TRUE,
1733                         'kitakyushu'=> TRUE,
1734                         'kobe'      => TRUE,
1735                         'kochi'     => TRUE,
1736                         'kumamoto'  => TRUE,
1737                         'kyoto'     => TRUE,
1738                         'mie'       => TRUE,
1739                         'miyagi'    => TRUE,
1740                         'miyazaki'  => TRUE,
1741                         'nagano'    => TRUE,
1742                         'nagasaki'  => TRUE,
1743                         'nagoya'    => TRUE,
1744                         'nara'      => TRUE,
1745                         'niigata'   => TRUE,
1746                         'oita'      => TRUE,
1747                         'okayama'   => TRUE,
1748                         'okinawa'   => TRUE,
1749                         'osaka'     => TRUE,
1750                         'saga'      => TRUE,
1751                         'saitama'   => TRUE,
1752                         'sapporo'   => TRUE,
1753                         'sendai'    => TRUE,
1754                         'shiga'     => TRUE,
1755                         'shimane'   => TRUE,
1756                         'shizuoka'  => TRUE,
1757                         'tochigi'   => TRUE,
1758                         'tokushima' => TRUE,
1759                         'tokyo'     => TRUE,
1760                         'tottori'   => TRUE,
1761                         'toyama'    => TRUE,
1762                         'wakayama'  => TRUE,
1763                         'yamagata'  => TRUE,
1764                         'yamaguchi' => TRUE,
1765                         'yamanashi' => TRUE,
1766                         'yokohama'  => TRUE,
1767                 ),
1768
1769                 // ccTLD Ukraine http://www.nic.net.ua/ http://whois.com.ua/
1770                 'ua' => array(
1771                         'cherkassy'  => TRUE,   // www.cherkassy.ua
1772                         'chernigov'  => TRUE,   
1773                         'chernovtsy' => TRUE,
1774                         'ck'         => TRUE,
1775                         'cn'         => TRUE,
1776                         'com'        => TRUE,
1777                         'crimea'     => TRUE,
1778                         'cv'         => TRUE,
1779                         'dn'         => TRUE,
1780                         'dnepropetrovsk' => TRUE,
1781                         'donetsk'    => TRUE,
1782                         'dp'         => TRUE,
1783                         'edu'        => TRUE,
1784                         'gov'        => TRUE,
1785                         'if'         => TRUE,
1786                         'ivano-frankivsk' => TRUE,
1787                         'kh'         => TRUE,
1788                         'kharkov'    => TRUE,
1789                         'kherson'    => TRUE,
1790                         'kiev'       => TRUE,
1791                         'kirovograd' => TRUE,
1792                         'km'         => TRUE,
1793                         'kr'         => TRUE,
1794                         'ks'         => TRUE,
1795                         'lg'         => TRUE,
1796                         'lugansk'    => TRUE,
1797                         'lutsk'      => TRUE,
1798                         'lviv'       => TRUE,
1799                         'mk'         => TRUE,
1800                         'net'        => TRUE,
1801                         'nikolaev'   => TRUE,
1802                         'od'         => TRUE,
1803                         'odessa'     => TRUE,
1804                         'org'        => TRUE,
1805                         'pl'         => TRUE,
1806                         'poltava'    => TRUE,
1807                         'rovno'      => TRUE,
1808                         'rv'         => TRUE,
1809                         'sebastopol' => TRUE,
1810                         'sumy'       => TRUE,
1811                         'te'         => TRUE,
1812                         'ternopil'   => TRUE,
1813                         'uz'         => TRUE,
1814                         'uzhgorod'   => TRUE,
1815                         'vinnica'    => TRUE,
1816                         'vn'         => TRUE,
1817                         'zaporizhzhe' => TRUE,
1818                         'zhitomir'   => TRUE,
1819                         'zp'         => TRUE,
1820                         'zt'         => TRUE,
1821                 ),
1822
1823                 // ccTLD United Kingdom http://www.nic.uk/
1824                 'uk' => array(
1825                         // http://www.nominet.org.uk/registrants/faq/#available
1826                         'co'     => TRUE,
1827                         'ltd'    => TRUE,
1828                         'me'     => TRUE,
1829                         'net'    => TRUE,
1830                         'nic'    => TRUE,
1831                         'org'    => TRUE,
1832                         'plc'    => TRUE,
1833                         'sch'    => TRUE,
1834                         
1835                         // "Delegated Second Level Domains" http://www.nominet.org.uk/registrants/aboutdomainnames/sld/delegated/
1836                         'ac'     => TRUE,
1837                         'gov'    => TRUE,
1838                         'mil'    => TRUE,
1839                         'mod'    => TRUE,
1840                         'nhs'    => TRUE,
1841                         'police' => TRUE,
1842                 ),
1843
1844         );
1845
1846         if (! is_string($fqdn)) return '';
1847
1848         $result  = array();
1849         $dcursor = & $domain;
1850         $array   = array_reverse(explode('.', $fqdn));
1851         $i = 0;
1852         while(TRUE) {
1853                 $acursor = $array[$i];
1854                 if (is_array($dcursor) && isset($dcursor[$acursor])) {
1855                         $result[] = & $array[$i];
1856                         $dcursor  = & $dcursor[$acursor];
1857                 } else {
1858                         if (isset($acursor)) {
1859                                 $result[] = & $array[$i];       // Whois servers must know this subdomain
1860                         }
1861                         break;
1862                 }
1863                 ++$i;
1864         }
1865
1866         // Implicit responsibility: Top-Level-Domains must not be yours
1867         // 'bar.foo.something' => 'foo.something'
1868         if ($implicit && count($result) == 1 && count($array) > 1) {
1869                 $result[] = & $array[1];
1870         }
1871
1872         return $result ? implode('.', array_reverse($result)) : '';
1873 }
1874
1875
1876 // ---------------------
1877 // Exit
1878
1879 // Freeing memories
1880 function spam_dispose()
1881 {
1882         get_blocklist(NULL);
1883 }
1884
1885 // Common bahavior for blocking
1886 // NOTE: Call this function from various blocking feature, to disgueise the reason 'why blocked'
1887 function spam_exit($mode = '', $data = array())
1888 {
1889
1890         $exit = TRUE;
1891         switch ($mode) {
1892                 case '':
1893                         echo("\n");
1894                         break;
1895                 case 'dump':
1896                         echo('<pre>' . "\n");
1897                         echo htmlspecialchars(var_export($data, TRUE));
1898                         echo('</pre>' . "\n");
1899                         break;
1900         };
1901
1902         if ($exit) exit;        // Force exit
1903 }
1904
1905
1906 // ---------------------
1907 // Simple filtering
1908
1909 // TODO: Record them
1910 // Simple/fast spam filter ($target: 'a string' or an array())
1911 function pkwk_spamfilter($action, $page, $target = array('title' => ''), $method = array(), $exitmode = '')
1912 {
1913         $progress = check_uri_spam($target, $method);
1914
1915         if (empty($progress['is_spam'])) {
1916                 spam_dispose();
1917         } else {
1918                 $target = string($target, 0);   // Removing "\0" etc
1919                 pkwk_spamnotify($action, $page, $target, $progress, $method);
1920                 spam_exit($exitmode, $progress);
1921         }
1922 }
1923
1924 // ---------------------
1925 // PukiWiki original
1926
1927 // Mail to administrator(s)
1928 function pkwk_spamnotify($action, $page, $target = array('title' => ''), $progress = array(), $method = array())
1929 {
1930         global $notify, $notify_subject;
1931
1932         if (! $notify) return;
1933
1934         $asap = isset($method['asap']);
1935
1936         $summary['ACTION']  = 'Blocked by: ' . summarize_spam_progress($progress, TRUE);
1937         if (! $asap) {
1938                 $summary['METRICS'] = summarize_spam_progress($progress);
1939         }
1940
1941         $tmp = summarize_detail_badhost($progress);
1942         if ($tmp != '') $summary['DETAIL_BADHOST'] = $tmp;
1943
1944         $tmp = summarize_detail_newtral($progress);
1945         if (! $asap && $tmp != '') $summary['DETAIL_NEUTRAL_HOST'] = $tmp;
1946
1947         $summary['COMMENT'] = $action;
1948         $summary['PAGE']    = '[blocked] ' . (is_pagename($page) ? $page : '');
1949         $summary['URI']     = get_script_uri() . '?' . rawurlencode($page);
1950         $summary['USER_AGENT']  = TRUE;
1951         $summary['REMOTE_ADDR'] = TRUE;
1952         pkwk_mail_notify($notify_subject,  var_export($target, TRUE), $summary, TRUE);
1953 }
1954
1955 ?>