OSDN Git Service

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