OSDN Git Service

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