OSDN Git Service

Change order of function, myspace, live search, etc
[pukiwiki/pukiwiki_sandbox.git] / spam / spam.php
1 <?php
2 // $Id: spam.php,v 1.193 2007/06/28 14:52:55 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 // Preprocess: Removing uninterest part for URI detection
431 function spam_uri_removing_hocus_pocus($binary = '', $method = array())
432 {
433         $length = 4 ; // 'http'(1) and '://'(2) and 'fqdn'(1)
434         if (is_array($method)) {
435                 // '<a'(2) or 'href='(5) or '>'(1) or '</a>'(4)
436                 // '[uri'(4) or ']'(1) or '[/uri]'(6) 
437                 if (isset($method['area_anchor']) || isset($method['uri_anchor']) ||
438                     isset($method['area_bbcode']) || isset($method['uri_bbcode']))
439                                 $length = 1;    // Seems not effective
440         }
441
442         // Removing sequential spaces and too short lines
443         $binary = strings($binary, $length, TRUE, FALSE); // Multibyte NOT needed
444
445         // Remove words (has no '<>[]:') between spaces
446         $binary = preg_replace('/[ \t][\w.,()\ \t]+[ \t]/', ' ', $binary);
447
448         return $binary;
449 }
450
451 // Preprocess: Domain exposure callback (See spam_uri_pickup_preprocess())
452 // http://victim.example.org/?foo+site:nasty.example.com+bar
453 // => http://nasty.example.com/?refer=victim.example.org
454 // NOTE: 'refer=' is not so good for (at this time).
455 // Consider about using IP address of the victim, try to avoid that.
456 function _preg_replace_callback_domain_exposure($matches = array())
457 {
458         $result = '';
459
460         // Preserve the victim URI as a complicity or ...
461         if (isset($matches[5])) {
462                 $result =
463                         $matches[1] . '://' .   // scheme
464                         $matches[2] . '/' .             // victim.example.org
465                         $matches[3];                    // The rest of all (before victim)
466         }
467
468         // Flipped URI
469         if (isset($matches[4])) {
470                 $result = 
471                         $matches[1] . '://' .   // scheme
472                         $matches[4] .                   // nasty.example.com
473                         '/?refer=' . strtolower($matches[2]) .  // victim.example.org
474                         ' ' . $result;
475         }
476
477         return $result;
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)://' .  // 1:Scheme
531                         // 2:Host
532                         '(' .
533                                 // Something Google: http://www.google.com/supported_domains
534                                 '(?:[a-z0-9.]+\.)?google\.[a-z]{2,3}(?:\.[a-z]{2})?' .
535                                 '|' .
536                                 // AltaVista
537                                 // http://es.altavista.com/web/results?q=site%3Anasty.example.org+foobar
538                                 '(?:[a-z0-9.]+\.)?altavista.com' .
539                                 '|' .
540                                 // Live Search
541                                 'search.live.com' .
542                                 '|' .
543                                 // MySpace
544                                 // http://sads.myspace.com/Modules/Search/Pages/Search.aspx?_snip_&searchString=site:nasty.example.org
545                                 // also searchresults.myspace.com
546                                 '(?:[a-z0-9.]+\.)?myspace.com' .
547                                 '|' .
548                                 'search.orange.co.uk' .
549                         ')' .
550                         '/' .
551                         '([a-z0-9?=&.%_/\'\\\+-]+)' .                           // 3:path/?query=foo+bar+
552                         '\bsite:([a-z0-9.%_-]+\.[a-z0-9.%_-]+)' .       // 4:site:nasty.example.com
553                         '()' .                                                                          // 5:Preserve or remove?
554                         '#i',
555                 ),
556                 '_preg_replace_callback_domain_exposure',
557                 $string
558         );
559
560         // URI exposure (uriuri => uri uri)
561         $string = preg_replace(
562                 array(
563                         '#(?<! )(?:https?|ftp):/#i',
564                 //      '#[a-z][a-z0-9.+-]{1,8}://#i',
565                 //      '#[a-z][a-z0-9.+-]{1,8}://#i'
566                 ),
567                 ' $0',
568                 $string
569         );
570
571         return $string;
572 }
573
574 // Main function of spam-uri pickup,
575 // A wrapper function of uri_pickup()
576 function spam_uri_pickup($string = '', $method = array())
577 {
578         if (! is_array($method) || empty($method)) {
579                 $method = check_uri_spam_method();
580         }
581
582         $string = spam_uri_pickup_preprocess($string, $method);
583
584         $array  = uri_pickup($string);
585
586         // Area elevation of URIs, for '(especially external)link' intension
587         if (! empty($array)) {
588                 $_method = array();
589                 if (isset($method['uri_anchor'])) $_method['uri_anchor'] = & $method['uri_anchor'];
590                 if (isset($method['uri_bbcode'])) $_method['uri_bbcode'] = & $method['uri_bbcode'];
591                 $areas = area_pickup($string, $_method, TRUE);
592                 if (! empty($areas)) {
593                         $area_shadow = array();
594                         foreach (array_keys($array) as $key) {
595                                 $area_shadow[$key] = & $array[$key]['area'];
596                                 foreach (array_keys($_method) as $_key) {
597                                         $area_shadow[$key][$_key] = 0;
598                                 }
599                         }
600                         foreach (array_keys($_method) as $_key) {
601                                 if (isset($areas[$_key])) {
602                                         area_measure($areas[$_key], $area_shadow, 1, $_key);
603                                 }
604                         }
605                 }
606         }
607
608         // Remove 'offset's for area_measure()
609         foreach(array_keys($array) as $key)
610                 unset($array[$key]['area']['offset']);
611
612         return $array;
613 }
614
615
616 // ---------------------
617 // Normalization
618
619 // Scheme normalization: Renaming the schemes
620 // snntp://example.org =>  nntps://example.org
621 // NOTE: Keep the static lists simple. See also port_normalize().
622 function scheme_normalize($scheme = '', $abbrevs_harmfull = TRUE)
623 {
624         // Abbreviations they have no intention of link
625         static $abbrevs = array(
626                 'ttp'   => 'http',
627                 'ttps'  => 'https',
628         );
629
630         // Aliases => normalized ones
631         static $aliases = array(
632                 'pop'   => 'pop3',
633                 'news'  => 'nntp',
634                 'imap4' => 'imap',
635                 'snntp' => 'nntps',
636                 'snews' => 'nntps',
637                 'spop3' => 'pop3s',
638                 'pops'  => 'pop3s',
639         );
640
641         if (! is_string($scheme)) return '';
642
643         $scheme = strtolower($scheme);
644         if (isset($abbrevs[$scheme])) {
645                 $scheme = $abbrevs_harmfull ? $abbrevs[$scheme] : '';
646         }
647         if (isset($aliases[$scheme])) {
648                 $scheme = $aliases[$scheme];
649         }
650
651         return $scheme;
652 }
653
654 // Hostname normlization (Destructive)
655 // www.foo     => www.foo   ('foo' seems TLD)
656 // www.foo.bar => foo.bar
657 // www.10.20   => www.10.20 (Invalid hostname)
658 // NOTE:
659 //   'www' is  mostly used as traditional hostname of WWW server.
660 //   'www.foo.bar' may be identical with 'foo.bar'.
661 function host_normalize($host = '')
662 {
663         if (! is_string($host)) return '';
664
665         $host = strtolower($host);
666         $matches = array();
667         if (preg_match('/^www\.(.+\.[a-z]+)$/', $host, $matches)) {
668                 return $matches[1];
669         } else {
670                 return $host;
671         }
672 }
673
674 // Port normalization: Suppress the (redundant) default port
675 // HTTP://example.org:80/ => http://example.org/
676 // HTTP://example.org:8080/ => http://example.org:8080/
677 // HTTPS://example.org:443/ => https://example.org/
678 function port_normalize($port, $scheme, $scheme_normalize = FALSE)
679 {
680         // Schemes that users _maybe_ want to add protocol-handlers
681         // to their web browsers. (and attackers _maybe_ want to use ...)
682         // Reference: http://www.iana.org/assignments/port-numbers
683         static $array = array(
684                 // scheme => default port
685                 'ftp'     =>    21,
686                 'ssh'     =>    22,
687                 'telnet'  =>    23,
688                 'smtp'    =>    25,
689                 'tftp'    =>    69,
690                 'gopher'  =>    70,
691                 'finger'  =>    79,
692                 'http'    =>    80,
693                 'pop3'    =>   110,
694                 'sftp'    =>   115,
695                 'nntp'    =>   119,
696                 'imap'    =>   143,
697                 'irc'     =>   194,
698                 'wais'    =>   210,
699                 'https'   =>   443,
700                 'nntps'   =>   563,
701                 'rsync'   =>   873,
702                 'ftps'    =>   990,
703                 'telnets' =>   992,
704                 'imaps'   =>   993,
705                 'ircs'    =>   994,
706                 'pop3s'   =>   995,
707                 'mysql'   =>  3306,
708         );
709
710         // intval() converts '0-1' to '0', so preg_match() rejects these invalid ones
711         if (! is_numeric($port) || $port < 0 || preg_match('/[^0-9]/i', $port))
712                 return '';
713
714         $port = intval($port);
715         if ($scheme_normalize) $scheme = scheme_normalize($scheme);
716         if (isset($array[$scheme]) && $port == $array[$scheme])
717                 $port = ''; // Ignore the defaults
718
719         return $port;
720 }
721
722 // Path normalization
723 // http://example.org => http://example.org/
724 // http://example.org#hoge => http://example.org/#hoge
725 // http://example.org/path/a/b/./c////./d => http://example.org/path/a/b/c/d
726 // http://example.org/path/../../a/../back => http://example.org/back
727 function path_normalize($path = '', $divider = '/', $add_root = TRUE)
728 {
729         if (! is_string($divider)) return is_string($path) ? $path : '';
730
731         if ($add_root) {
732                 $first_div = & $divider;
733         } else {
734                 $first_div = '';
735         }
736         if (! is_string($path) || $path == '') return $first_div;
737
738         if (strpos($path, $divider, strlen($path) - strlen($divider)) === FALSE) {
739                 $last_div = '';
740         } else {
741                 $last_div = & $divider;
742         }
743
744         $array = explode($divider, $path);
745
746         // Remove paddings ('//' and '/./')
747         foreach(array_keys($array) as $key) {
748                 if ($array[$key] == '' || $array[$key] == '.') {
749                          unset($array[$key]);
750                 }
751         }
752
753         // Remove back-tracks ('/../')
754         $tmp = array();
755         foreach($array as $value) {
756                 if ($value == '..') {
757                         array_pop($tmp);
758                 } else {
759                         array_push($tmp, $value);
760                 }
761         }
762         $array = & $tmp;
763
764         if (empty($array)) {
765                 return $first_div;
766         } else {
767                 return $first_div . implode($divider, $array) . $last_div;
768         }
769 }
770
771 // DirectoryIndex normalize (Destructive and rough)
772 // TODO: sample.en.ja.html.gz => sample.html
773 function file_normalize($file = 'index.html.en')
774 {
775         static $simple_defaults = array(
776                 'default.htm'   => TRUE,
777                 'default.html'  => TRUE,
778                 'default.asp'   => TRUE,
779                 'default.aspx'  => TRUE,
780                 'index'                 => TRUE,        // Some system can omit the suffix
781         );
782
783         static $content_suffix = array(
784                 // index.xxx, sample.xxx
785                 'htm'   => TRUE,
786                 'html'  => TRUE,
787                 'shtml' => TRUE,
788                 'jsp'   => TRUE,
789                 'php'   => TRUE,
790                 'php3'  => TRUE,
791                 'php4'  => TRUE,
792                 'pl'    => TRUE,
793                 'py'    => TRUE,
794                 'rb'    => TRUE,
795                 'cgi'   => TRUE,
796                 'xml'   => TRUE,
797         );
798
799         static $language_suffix = array(
800                 // Reference: Apache 2.0.59 'AddLanguage' default
801                 'ca'    => TRUE,
802                 'cs'    => TRUE,        // cs
803                 'cz'    => TRUE,        // cs
804                 'de'    => TRUE,
805                 'dk'    => TRUE,        // da
806                 'el'    => TRUE,
807                 'en'    => TRUE,
808                 'eo'    => TRUE,
809                 'es'    => TRUE,
810                 'et'    => TRUE,
811                 'fr'    => TRUE,
812                 'he'    => TRUE,
813                 'hr'    => TRUE,
814                 'it'    => TRUE,
815                 'ja'    => TRUE,
816                 'ko'    => TRUE,
817                 'ltz'   => TRUE,
818                 'nl'    => TRUE,
819                 'nn'    => TRUE,
820                 'no'    => TRUE,
821                 'po'    => TRUE,
822                 'pt'    => TRUE,
823                 'pt-br' => TRUE,
824                 'ru'    => TRUE,
825                 'sv'    => TRUE,
826                 'zh-cn' => TRUE,
827                 'zh-tw' => TRUE,
828
829                 // Reference: Apache 2.0.59 default 'index.html' variants
830                 'ee'    => TRUE,
831                 'lb'    => TRUE,
832                 'var'   => TRUE,
833         );
834
835         static $charset_suffix = array(
836                 // Reference: Apache 2.0.59 'AddCharset' default
837                 'iso8859-1'     => TRUE, // ISO-8859-1
838                 'latin1'        => TRUE, // ISO-8859-1
839                 'iso8859-2'     => TRUE, // ISO-8859-2
840                 'latin2'        => TRUE, // ISO-8859-2
841                 'cen'           => TRUE, // ISO-8859-2
842                 'iso8859-3'     => TRUE, // ISO-8859-3
843                 'latin3'        => TRUE, // ISO-8859-3
844                 'iso8859-4'     => TRUE, // ISO-8859-4
845                 'latin4'        => TRUE, // ISO-8859-4
846                 'iso8859-5'     => TRUE, // ISO-8859-5
847                 'latin5'        => TRUE, // ISO-8859-5
848                 'cyr'           => TRUE, // ISO-8859-5
849                 'iso-ru'        => TRUE, // ISO-8859-5
850                 'iso8859-6'     => TRUE, // ISO-8859-6
851                 'latin6'        => TRUE, // ISO-8859-6
852                 'arb'           => TRUE, // ISO-8859-6
853                 'iso8859-7'     => TRUE, // ISO-8859-7
854                 'latin7'        => TRUE, // ISO-8859-7
855                 'grk'           => TRUE, // ISO-8859-7
856                 'iso8859-8'     => TRUE, // ISO-8859-8
857                 'latin8'        => TRUE, // ISO-8859-8
858                 'heb'           => TRUE, // ISO-8859-8
859                 'iso8859-9'     => TRUE, // ISO-8859-9
860                 'latin9'        => TRUE, // ISO-8859-9
861                 'trk'           => TRUE, // ISO-8859-9
862                 'iso2022-jp'=> TRUE, // ISO-2022-JP
863                 'jis'           => TRUE, // ISO-2022-JP
864                 'iso2022-kr'=> TRUE, // ISO-2022-KR
865                 'kis'           => TRUE, // ISO-2022-KR
866                 'iso2022-cn'=> TRUE, // ISO-2022-CN
867                 'cis'           => TRUE, // ISO-2022-CN
868                 'big5'          => TRUE,
869                 'cp-1251'       => TRUE, // ru, WINDOWS-1251
870                 'win-1251'      => TRUE, // ru, WINDOWS-1251
871                 'cp866'         => TRUE, // ru
872                 'koi8-r'        => TRUE, // ru, KOI8-r
873                 'koi8-ru'       => TRUE, // ru, KOI8-r
874                 'koi8-uk'       => TRUE, // ru, KOI8-ru
875                 'ua'            => TRUE, // ru, KOI8-ru
876                 'ucs2'          => TRUE, // ru, ISO-10646-UCS-2
877                 'ucs4'          => TRUE, // ru, ISO-10646-UCS-4
878                 'utf8'          => TRUE,
879
880                 // Reference: Apache 2.0.59 default 'index.html' variants
881                 'euc-kr'        => TRUE,
882                 'gb2312'        => TRUE,
883         );
884
885         // May uncompress by web browsers on the fly
886         // Must be at the last of the filename
887         // Reference: Apache 2.0.59 'AddEncoding'
888         static $encoding_suffix = array(
889                 'z'             => TRUE,
890                 'gz'    => TRUE,
891         );
892
893         if (! is_string($file)) return '';
894         $_file = strtolower($file);
895         if (isset($simple_defaults[$_file])) return '';
896
897
898         // Roughly removing language/character-set/encoding suffixes
899         // References:
900         //  * Apache 2 document about 'Content-negotiaton', 'mod_mime' and 'mod_negotiation'
901         //    http://httpd.apache.org/docs/2.0/content-negotiation.html
902         //    http://httpd.apache.org/docs/2.0/mod/mod_mime.html
903         //    http://httpd.apache.org/docs/2.0/mod/mod_negotiation.html
904         //  * http://www.iana.org/assignments/character-sets
905         //  * RFC3066: Tags for the Identification of Languages
906         //    http://www.ietf.org/rfc/rfc3066.txt
907         //  * ISO 639: codes of 'language names'
908         $suffixes = explode('.', $_file);
909         $body = array_shift($suffixes);
910         if ($suffixes) {
911                 // Remove the last .gz/.z
912                 $last_key = end(array_keys($suffixes));
913                 if (isset($encoding_suffix[$suffixes[$last_key]])) {
914                         unset($suffixes[$last_key]);
915                 }
916         }
917         // Cut language and charset suffixes
918         foreach($suffixes as $key => $value){
919                 if (isset($language_suffix[$value]) || isset($charset_suffix[$value])) {
920                         unset($suffixes[$key]);
921                 }
922         }
923         if (empty($suffixes)) return $body;
924
925         // Index.xxx
926         $count = count($suffixes);
927         reset($suffixes);
928         $current = current($suffixes);
929         if ($body == 'index' && $count == 1 && isset($content_suffix[$current])) return '';
930
931         return $file;
932 }
933
934 // Sort query-strings if possible (Destructive and rough)
935 // [OK] &&&&f=d&b&d&c&a=0dd  =>  a=0dd&b&c&d&f=d
936 // [OK] nothing==&eg=dummy&eg=padding&eg=foobar  =>  eg=foobar
937 function query_normalize($string = '', $equal = TRUE, $equal_cutempty = TRUE, $stortolower = TRUE)
938 {
939         if (! is_string($string)) return '';
940         if ($stortolower) $string = strtolower($string);
941
942         $array = explode('&', $string);
943
944         // Remove '&' paddings
945         foreach(array_keys($array) as $key) {
946                 if ($array[$key] == '') {
947                          unset($array[$key]);
948                 }
949         }
950
951         // Consider '='-sepalated input and paddings
952         if ($equal) {
953                 $equals = $not_equals = array();
954                 foreach ($array as $part) {
955                         if (strpos($part, '=') === FALSE) {
956                                  $not_equals[] = $part;
957                         } else {
958                                 list($key, $value) = explode('=', $part, 2);
959                                 $value = ltrim($value, '=');
960                                 if (! $equal_cutempty || $value != '') {
961                                         $equals[$key] = $value;
962                                 }
963                         }
964                 }
965
966                 $array = & $not_equals;
967                 foreach ($equals as $key => $value) {
968                         $array[] = $key . '=' . $value;
969                 }
970                 unset($equals);
971         }
972
973         natsort($array);
974         return implode('&', $array);
975 }
976
977 // ---------------------
978 // Part One : Checker
979
980 // Rough implementation of globbing
981 //
982 // USAGE: $regex = '/^' . generate_glob_regex('*.txt', '/') . '$/i';
983 //
984 function generate_glob_regex($string = '', $divider = '/')
985 {
986         static $from = array(
987                          1 => '*',
988                         11 => '?',
989         //              22 => '[',      // Maybe cause regex compilation error (e.g. '[]')
990         //              23 => ']',      //
991                 );
992         static $mid = array(
993                          1 => '_AST_',
994                         11 => '_QUE_',
995         //              22 => '_RBR_',
996         //              23 => '_LBR_',
997                 );
998         static $to = array(
999                          1 => '.*',
1000                         11 => '.',
1001         //              22 => '[',
1002         //              23 => ']',
1003                 );
1004
1005         if (! is_string($string)) return '';
1006
1007         $string = str_replace($from, $mid, $string); // Hide
1008         $string = preg_quote($string, $divider);
1009         $string = str_replace($mid, $to, $string);   // Unhide
1010
1011         return $string;
1012 }
1013
1014 // Rough hostname checker
1015 // [OK] 192.168.
1016 // TODO: Strict digit, 0x, CIDR, IPv6
1017 function is_ip($string = '')
1018 {
1019         if (preg_match('/^' .
1020                 '(?:[0-9]{1,3}\.){3}[0-9]{1,3}' . '|' .
1021                 '(?:[0-9]{1,3}\.){1,3}' . '$/',
1022                 $string)) {
1023                 return 4;       // Seems IPv4(dot-decimal)
1024         } else {
1025                 return 0;       // Seems not IP
1026         }
1027 }
1028
1029 // Generate host (FQDN, IPv4, ...) regex
1030 // 'localhost'     : Matches with 'localhost' only
1031 // 'example.org'   : Matches with 'example.org' only (See host_normalize() about 'www')
1032 // '.example.org'  : Matches with ALL FQDN ended with '.example.org'
1033 // '*.example.org' : Almost the same of '.example.org' except 'www.example.org'
1034 // '10.20.30.40'   : Matches with IPv4 address '10.20.30.40' only
1035 // [TODO] '192.'   : Matches with all IPv4 hosts started with '192.'
1036 // TODO: IPv4, CIDR?, IPv6
1037 function generate_host_regex($string = '', $divider = '/')
1038 {
1039         if (! is_string($string)) return '';
1040
1041         if (mb_strpos($string, '.') === FALSE)
1042                 return generate_glob_regex($string, $divider);
1043
1044         $result = '';
1045         if (is_ip($string)) {
1046                 // IPv4
1047                 return generate_glob_regex($string, $divider);
1048         } else {
1049                 // FQDN or something
1050                 $part = explode('.', $string, 2);
1051                 if ($part[0] == '') {
1052                         $part[0] = '(?:.*\.)?'; // And all related FQDN
1053                 } else if ($part[0] == '*') {
1054                         $part[0] = '.*\.';      // All subdomains/hosts only
1055                 } else {
1056                         return generate_glob_regex($string, $divider);
1057                 }
1058                 $part[1] = generate_glob_regex($part[1], $divider);
1059                 return implode('', $part);
1060         }
1061 }
1062
1063 function get_blocklist($list = '')
1064 {
1065         static $regexes;
1066
1067         if ($list === NULL) {
1068                 $regexes = NULL;        // Unset
1069                 return array();
1070         }
1071
1072         if (! isset($regexes)) {
1073                 $regexes = array();
1074                 if (file_exists(SPAM_INI_FILE)) {
1075                         $blocklist = array();
1076                         include(SPAM_INI_FILE);
1077                         //      $blocklist['badhost'] = array(
1078                         //              '*.blogspot.com',       // Blog services's subdomains (only)
1079                         //              'IANA-examples' => '#^(?:.*\.)?example\.(?:com|net|org)$#',
1080                         //      );
1081                         if (isset($blocklist['list'])) {
1082                                 $regexes['list'] = & $blocklist['list'];
1083                         } else {
1084                                 // Default
1085                                 $blocklist['list'] = array(
1086                                         'goodhost' => FALSE,
1087                                         'badhost'  => TRUE,
1088                                 );
1089                         }
1090                         foreach(array_keys($blocklist['list']) as $_list) {
1091                                 if (! isset($blocklist[$_list])) continue;
1092                                 foreach ($blocklist[$_list] as $key => $value) {
1093                                         if (is_array($value)) {
1094                                                 $regexes[$_list][$key] = array();
1095                                                 foreach($value as $_key => $_value) {
1096                                                         get_blocklist_add($regexes[$_list][$key], $_key, $_value);
1097                                                 }
1098                                         } else {
1099                                                 get_blocklist_add($regexes[$_list], $key, $value);
1100                                         }
1101                                 }
1102                                 unset($blocklist[$_list]);
1103                         }
1104                 }
1105         }
1106
1107         if ($list === '') {
1108                 return $regexes;        // ALL
1109         } else if (isset($regexes[$list])) {
1110                 return $regexes[$list];
1111         } else {
1112                 return array();
1113         }
1114 }
1115
1116 // Subroutine of get_blocklist()
1117 function get_blocklist_add(& $array, $key = 0, $value = '*.example.org')
1118 {
1119         if (is_string($key)) {
1120                 $array[$key] = & $value; // Treat $value as a regex
1121         } else {
1122                 $array[$value] = '/^' . generate_host_regex($value, '/') . '$/i';
1123         }
1124 }
1125
1126 // Blocklist metrics: Separate $host, to $blocked and not blocked
1127 function blocklist_distiller(& $hosts, $keys = array('goodhost', 'badhost'), $asap = FALSE)
1128 {
1129         if (! is_array($hosts)) $hosts = array($hosts);
1130         if (! is_array($keys))  $keys  = array($keys);
1131
1132         $list = get_blocklist('list');
1133         $blocked = array();
1134
1135         foreach($keys as $key){
1136                 foreach (get_blocklist($key) as $label => $regex) {
1137                         if (is_array($regex)) {
1138                                 foreach($regex as $_label => $_regex) {
1139                                         $group = preg_grep($_regex, $hosts);
1140                                         if ($group) {
1141                                                 $hosts = array_diff($hosts, $group);
1142                                                 $blocked[$key][$label][$_label] = $group;
1143                                                 if ($asap && $list[$key]) break;
1144                                         }
1145                                 }
1146                         } else {
1147                                 $group = preg_grep($regex, $hosts);
1148                                 if ($group) {
1149                                         $hosts = array_diff($hosts, $group);
1150                                         $blocked[$key][$label] = $group;
1151                                         if ($asap && $list[$key]) break;
1152                                 }
1153                         }
1154                 }
1155         }
1156
1157         return $blocked;
1158 }
1159
1160 // Default (enabled) methods and thresholds (for content insertion)
1161 function check_uri_spam_method($times = 1, $t_area = 0, $rule = TRUE)
1162 {
1163         $times  = intval($times);
1164         $t_area = intval($t_area);
1165
1166         $positive = array(
1167                 // Thresholds
1168                 'quantity'     =>  8 * $times,  // Allow N URIs
1169                 'non_uniqhost' =>  3 * $times,  // Allow N duped (and normalized) Hosts
1170                 //'non_uniquri'=>  3 * $times,  // Allow N duped (and normalized) URIs
1171
1172                 // Areas
1173                 'area_anchor'  => $t_area,      // Using <a href> HTML tag
1174                 'area_bbcode'  => $t_area,      // Using [url] or [link] BBCode
1175                 //'uri_anchor' => $t_area,      // URI inside <a href> HTML tag
1176                 //'uri_bbcode' => $t_area,      // URI inside [url] or [link] BBCode
1177         );
1178         if ($rule) {
1179                 $bool = array(
1180                         // Rules
1181                         //'asap'   => TRUE,     // Quit or return As Soon As Possible
1182                         'uniqhost' => TRUE,     // Show uniq host (at block notification mail)
1183                         'badhost'  => TRUE,     // Check badhost
1184                 );
1185         } else {
1186                 $bool = array();
1187         }
1188
1189         // Remove non-$positive values
1190         foreach (array_keys($positive) as $key) {
1191                 if ($positive[$key] < 0) unset($positive[$key]);
1192         }
1193
1194         return $positive + $bool;
1195 }
1196
1197 // Simple/fast spam check
1198 function check_uri_spam($target = '', $method = array())
1199 {
1200         // Return value
1201         $progress = array(
1202                 'method'  => array(
1203                         // Theme to do  => Dummy, optional value, or optional array()
1204                         //'quantity'    => 8,
1205                         //'uniqhost'    => TRUE,
1206                         //'non_uniqhost'=> 3,
1207                         //'non_uniquri' => 3,
1208                         //'badhost'     => TRUE,
1209                         //'area_anchor' => 0,
1210                         //'area_bbcode' => 0,
1211                         //'uri_anchor'  => 0,
1212                         //'uri_bbcode'  => 0,
1213                 ),
1214                 'sum' => array(
1215                         // Theme        => Volume found (int)
1216                 ),
1217                 'is_spam' => array(
1218                         // Flag. If someting defined here,
1219                         // one or more spam will be included
1220                         // in this report
1221                 ),
1222                 'blocked' => array(
1223                         // Hosts blocked
1224                         //'category' => array(
1225                         //      'host',
1226                         //)
1227                 ),
1228                 'hosts' => array(
1229                         // Hosts not blocked
1230                 ),
1231         );
1232
1233         // Aliases
1234         $sum     = & $progress['sum'];
1235         $is_spam = & $progress['is_spam'];
1236         $progress['method'] = & $method;        // Argument
1237         $blocked = & $progress['blocked'];
1238         $hosts   = & $progress['hosts'];
1239         $asap    = isset($method['asap']);
1240
1241         // Init
1242         if (! is_array($method) || empty($method)) {
1243                 $method = check_uri_spam_method();
1244         }
1245         foreach(array_keys($method) as $key) {
1246                 if (! isset($sum[$key])) $sum[$key] = 0;
1247         }
1248         if (! isset($sum['quantity'])) $sum['quantity'] = 0;
1249
1250         if (is_array($target)) {
1251                 foreach($target as $str) {
1252                         if (! is_string($str)) continue;
1253
1254                         $_progress = check_uri_spam($str, $method);     // Recurse
1255
1256                         // Merge $sum
1257                         $_sum = & $_progress['sum'];
1258                         foreach (array_keys($_sum) as $key) {
1259                                 if (! isset($sum[$key])) {
1260                                         $sum[$key] = & $_sum[$key];
1261                                 } else {
1262                                         $sum[$key] += $_sum[$key];
1263                                 }
1264                         }
1265
1266                         // Merge $is_spam
1267                         $_is_spam = & $_progress['is_spam'];
1268                         foreach (array_keys($_is_spam) as $key) {
1269                                 $is_spam[$key] = TRUE;
1270                                 if ($asap) break;
1271                         }
1272                         if ($asap && $is_spam) break;
1273
1274                         // Merge only
1275                         $blocked = array_merge_recursive($blocked, $_progress['blocked']);
1276                         $hosts   = array_merge_recursive($hosts,   $_progress['hosts']);
1277                 }
1278
1279                 // Unique values
1280                 $blocked = array_unique_recursive($blocked);
1281                 $hosts   = array_unique_recursive($hosts);
1282
1283                 // Recount $sum['badhost']
1284                 $sum['badhost'] = array_count_leaves($blocked);
1285
1286                 return $progress;
1287         }
1288
1289         // Area: There's HTML anchor tag
1290         if ((! $asap || ! $is_spam) && isset($method['area_anchor'])) {
1291                 $key = 'area_anchor';
1292                 $_asap = isset($method['asap']) ? array('asap' => TRUE) : array();
1293                 $result = area_pickup($target, array($key => TRUE) + $_asap);
1294                 if ($result) {
1295                         $sum[$key] = $result[$key];
1296                         if (isset($method[$key]) && $sum[$key] > $method[$key]) {
1297                                 $is_spam[$key] = TRUE;
1298                         }
1299                 }
1300         }
1301
1302         // Area: There's 'BBCode' linking tag
1303         if ((! $asap || ! $is_spam) && isset($method['area_bbcode'])) {
1304                 $key = 'area_bbcode';
1305                 $_asap = isset($method['asap']) ? array('asap' => TRUE) : array();
1306                 $result = area_pickup($target, array($key => TRUE) + $_asap);
1307                 if ($result) {
1308                         $sum[$key] = $result[$key];
1309                         if (isset($method[$key]) && $sum[$key] > $method[$key]) {
1310                                 $is_spam[$key] = TRUE;
1311                         }
1312                 }
1313         }
1314
1315         // Return if ...
1316         if ($asap && $is_spam) return $progress;
1317
1318         // URI: Pickup
1319         $pickups = uri_pickup_normalize(spam_uri_pickup($target, $method));
1320
1321         // Return if ...
1322         if (empty($pickups)) return $progress;
1323
1324         // URI: Check quantity
1325         $sum['quantity'] += count($pickups);
1326                 // URI quantity
1327         if ((! $asap || ! $is_spam) && isset($method['quantity']) &&
1328                 $sum['quantity'] > $method['quantity']) {
1329                 $is_spam['quantity'] = TRUE;
1330         }
1331
1332         // URI: used inside HTML anchor tag pair
1333         if ((! $asap || ! $is_spam) && isset($method['uri_anchor'])) {
1334                 $key = 'uri_anchor';
1335                 foreach($pickups as $pickup) {
1336                         if (isset($pickup['area'][$key])) {
1337                                 $sum[$key] += $pickup['area'][$key];
1338                                 if(isset($method[$key]) &&
1339                                         $sum[$key] > $method[$key]) {
1340                                         $is_spam[$key] = TRUE;
1341                                         if ($asap && $is_spam) break;
1342                                 }
1343                                 if ($asap && $is_spam) break;
1344                         }
1345                 }
1346         }
1347
1348         // URI: used inside 'BBCode' pair
1349         if ((! $asap || ! $is_spam) && isset($method['uri_bbcode'])) {
1350                 $key = 'uri_bbcode';
1351                 foreach($pickups as $pickup) {
1352                         if (isset($pickup['area'][$key])) {
1353                                 $sum[$key] += $pickup['area'][$key];
1354                                 if(isset($method[$key]) &&
1355                                         $sum[$key] > $method[$key]) {
1356                                         $is_spam[$key] = TRUE;
1357                                         if ($asap && $is_spam) break;
1358                                 }
1359                                 if ($asap && $is_spam) break;
1360                         }
1361                 }
1362         }
1363
1364         // URI: Uniqueness (and removing non-uniques)
1365         if ((! $asap || ! $is_spam) && isset($method['non_uniquri'])) {
1366
1367                 $uris = array();
1368                 foreach (array_keys($pickups) as $key) {
1369                         $uris[$key] = uri_pickup_implode($pickups[$key]);
1370                 }
1371                 $count = count($uris);
1372                 $uris  = array_unique($uris);
1373                 $sum['non_uniquri'] += $count - count($uris);
1374                 if ($sum['non_uniquri'] > $method['non_uniquri']) {
1375                         $is_spam['non_uniquri'] = TRUE;
1376                 }
1377                 if (! $asap || ! $is_spam) {
1378                         foreach (array_diff(array_keys($pickups),
1379                                 array_keys($uris)) as $remove) {
1380                                 unset($pickups[$remove]);
1381                         }
1382                 }
1383                 unset($uris);
1384         }
1385
1386         // Return if ...
1387         if ($asap && $is_spam) return $progress;
1388
1389         // Host: Uniqueness (uniq / non-uniq)
1390         foreach ($pickups as $pickup) $hosts[] = & $pickup['host'];
1391         $hosts = array_unique($hosts);
1392         $sum['uniqhost'] += count($hosts);
1393         if ((! $asap || ! $is_spam) && isset($method['non_uniqhost'])) {
1394                 $sum['non_uniqhost'] = $sum['quantity'] - $sum['uniqhost'];
1395                 if ($sum['non_uniqhost'] > $method['non_uniqhost']) {
1396                         $is_spam['non_uniqhost'] = TRUE;
1397                 }
1398         }
1399
1400         // Return if ...
1401         if ($asap && $is_spam) return $progress;
1402
1403         // URI: Bad host (Separate good/bad hosts from $hosts)
1404         if ((! $asap || ! $is_spam) && isset($method['badhost'])) {
1405
1406                 // is_badhost()
1407                 $list = get_blocklist('list');
1408                 $blocked = blocklist_distiller($hosts, array_keys($list), $asap);
1409                 foreach($list as $key=>$type){
1410                         if (! $type) unset($blocked[$key]); // Ignore goodhost etc
1411                 }
1412                 unset($list);
1413
1414                 if (! empty($blocked)) $is_spam['badhost'] = TRUE;
1415         }
1416
1417         return $progress;
1418 }
1419
1420 // Count leaves (A leaf = value that is not an array, or an empty array)
1421 function array_count_leaves($array = array(), $count_empty = FALSE)
1422 {
1423         if (! is_array($array) || (empty($array) && $count_empty)) return 1;
1424
1425         // Recurse
1426         $count = 0;
1427         foreach ($array as $part) {
1428                 $count += array_count_leaves($part, $count_empty);
1429         }
1430         return $count;
1431 }
1432
1433 // An array-leaves to a flat array
1434 function array_flat_leaves($array, $unique = TRUE)
1435 {
1436         if (! is_array($array)) return $array;
1437
1438         $tmp = array();
1439         foreach(array_keys($array) as $key) {
1440                 if (is_array($array[$key])) {
1441                         // Recurse
1442                         foreach(array_flat_leaves($array[$key]) as $_value) {
1443                                 $tmp[] = $_value;
1444                         }
1445                 } else {
1446                         $tmp[] = & $array[$key];
1447                 }
1448         }
1449
1450         return $unique ? array_values(array_unique($tmp)) : $tmp;
1451 }
1452
1453 // An array() to an array leaf
1454 function array_leaf($array = array('A', 'B', 'C.D'), $stem = FALSE, $edge = TRUE)
1455 {
1456         if (! is_array($array)) return $array;
1457
1458         $leaf = array();
1459         $tmp  = & $leaf;
1460         foreach($array as $arg) {
1461                 if (! is_string($arg) && ! is_int($arg)) continue;
1462                 $tmp[$arg] = array();
1463                 $parent    = & $tmp;
1464                 $tmp       = & $tmp[$arg];
1465         }
1466         if ($stem) {
1467                 $parent[key($parent)] = & $edge;
1468         } else {
1469                 $parent = key($parent);
1470         }
1471
1472         return $leaf;   // array('A' => array('B' => 'C.D'))
1473 }
1474
1475
1476 // ---------------------
1477 // Reporting
1478
1479 // Summarize $progress (blocked only)
1480 function summarize_spam_progress($progress = array(), $blockedonly = FALSE)
1481 {
1482         if ($blockedonly) {
1483                 $tmp = array_keys($progress['is_spam']);
1484         } else {
1485                 $tmp = array();
1486                 $method = & $progress['method'];
1487                 if (isset($progress['sum'])) {
1488                         foreach ($progress['sum'] as $key => $value) {
1489                                 if (isset($method[$key]) && $value) {
1490                                         $tmp[] = $key . '(' . $value . ')';
1491                                 }
1492                         }
1493                 }
1494         }
1495
1496         return implode(', ', $tmp);
1497 }
1498
1499 function summarize_detail_badhost($progress = array())
1500 {
1501         if (! isset($progress['blocked']) || empty($progress['blocked'])) return '';
1502
1503         // Flat per group
1504         $blocked = array();
1505         foreach($progress['blocked'] as $list => $lvalue) {
1506                 foreach($lvalue as $group => $gvalue) {
1507                         $flat = implode(', ', array_flat_leaves($gvalue));
1508                         if ($flat === $group) {
1509                                 $blocked[$list][]       = $flat;
1510                         } else {
1511                                 $blocked[$list][$group] = $flat;
1512                         }
1513                 }
1514         }
1515
1516         // Shrink per list
1517         // From: 'A-1' => array('ie.to')
1518         // To:   'A-1' => 'ie.to'
1519         foreach($blocked as $list => $lvalue) {
1520                 if (is_array($lvalue) &&
1521                    count($lvalue) == 1 &&
1522                    is_numeric(key($lvalue))) {
1523                     $blocked[$list] = current($lvalue);
1524                 }
1525         }
1526
1527         return var_export_shrink($blocked, TRUE, TRUE);
1528 }
1529
1530 function summarize_detail_newtral($progress = array())
1531 {
1532         if (! isset($progress['hosts'])    ||
1533             ! is_array($progress['hosts']) ||
1534             empty($progress['hosts'])) return '';
1535
1536         // Generate a responsible $trie
1537         $trie = array();
1538         foreach($progress['hosts'] as $value) {
1539                 // 'A.foo.bar.example.com'
1540                 $resp = whois_responsibility($value);   // 'example.com'
1541                 if (empty($resp)) {
1542                         // One or more test, or do nothing here
1543                         $resp = strval($value);
1544                         $rest = '';
1545                 } else {
1546                         $rest = rtrim(substr($value, 0, - strlen($resp)), '.'); // 'A.foo.bar'
1547                 }
1548                 $trie = array_merge_recursive($trie, array($resp => array($rest => NULL)));
1549         }
1550
1551         // Format: var_export_shrink() -like output
1552         $result = array();
1553         ksort_by_domain($trie);
1554         foreach(array_keys($trie) as $key) {
1555                 ksort_by_domain($trie[$key]);
1556                 if (count($trie[$key]) == 1 && key($trie[$key]) == '') {
1557                         // Just one 'responsibility.example.com'
1558                         $result[] = '  \'' . $key . '\',';
1559                 } else {
1560                         // One subdomain-or-host, or several ones
1561                         $subs = array();
1562                         foreach(array_keys($trie[$key]) as $sub) {
1563                                 if ($sub == '') {
1564                                         $subs[] = $key;
1565                                 } else {
1566                                         $subs[] = $sub . '.' . $key;
1567                                 }
1568                         }
1569                         $result[] = '  \'' . $key . '\' => \'' . implode(', ', $subs) . '\',';
1570                 }
1571                 unset($trie[$key]);
1572         }
1573         return
1574                 'array (' . "\n" .
1575                         implode("\n", $result) . "\n" .
1576                 ')';
1577 }
1578
1579 // ksort() by domain
1580 function ksort_by_domain(& $array)
1581 {
1582         $sort = array();
1583         foreach(array_keys($array) as $key) {
1584                 $sort[delimiter_reverse($key)] = $key;
1585         }
1586         ksort($sort, SORT_STRING);
1587         $result = array();
1588         foreach($sort as $key) {
1589                 $result[$key] = & $array[$key];
1590         }
1591         $array = $result;
1592 }
1593
1594 // Check responsibility-root of the FQDN
1595 // 'foo.bar.example.com'        => 'example.com'        (.com        has the last whois for it)
1596 // 'foo.bar.example.au'         => 'example.au'         (.au         has the last whois for it)
1597 // 'foo.bar.example.edu.au'     => 'example.edu.au'     (.edu.au     has the last whois for it)
1598 // 'foo.bar.example.act.edu.au' => 'example.act.edu.au' (.act.edu.au has the last whois for it)
1599 function whois_responsibility($fqdn = 'foo.bar.example.com', $parent = FALSE, $implicit = TRUE)
1600 {
1601         static $domain;
1602
1603         if ($fqdn === NULL) {
1604                 $domain = NULL; // Unset
1605                 return '';
1606         }
1607         if (! is_string($fqdn)) return '';
1608
1609         if (is_ip($fqdn))       return $fqdn;
1610
1611         if (! isset($domain)) {
1612                 $domain = array();
1613                 if (file_exists(DOMAIN_INI_FILE)) {
1614                         include(DOMAIN_INI_FILE);       // Set
1615                 }
1616         }
1617
1618         $result  = array();
1619         $dcursor = & $domain;
1620         $array   = array_reverse(explode('.', $fqdn));
1621         $i = 0;
1622         while(TRUE) {
1623                 if (! isset($array[$i])) break;
1624                 $acursor = $array[$i];
1625                 if (is_array($dcursor) && isset($dcursor[$acursor])) {
1626                         $result[] = & $array[$i];
1627                         $dcursor  = & $dcursor[$acursor];
1628                 } else {
1629                         if (! $parent && isset($acursor)) {
1630                                 $result[] = & $array[$i];       // Whois servers must know this subdomain
1631                         }
1632                         break;
1633                 }
1634                 ++$i;
1635         }
1636
1637         // Implicit responsibility: Top-Level-Domains must not be yours
1638         // 'bar.foo.something' => 'foo.something'
1639         if ($implicit && count($result) == 1 && count($array) > 1) {
1640                 $result[] = & $array[1];
1641         }
1642
1643         return $result ? implode('.', array_reverse($result)) : '';
1644 }
1645
1646
1647 // ---------------------
1648 // Exit
1649
1650 // Freeing memories
1651 function spam_dispose()
1652 {
1653         get_blocklist(NULL);
1654         whois_responsibility(NULL);
1655 }
1656
1657 // Common bahavior for blocking
1658 // NOTE: Call this function from various blocking feature, to disgueise the reason 'why blocked'
1659 function spam_exit($mode = '', $data = array())
1660 {
1661         $exit = TRUE;
1662
1663         switch ($mode) {
1664                 case '':
1665                         echo("\n");
1666                         break;
1667                 case 'dump':
1668                         echo('<pre>' . "\n");
1669                         echo htmlspecialchars(var_export($data, TRUE));
1670                         echo('</pre>' . "\n");
1671                         break;
1672         };
1673
1674         if ($exit) exit;        // Force exit
1675 }
1676
1677
1678 // ---------------------
1679 // Simple filtering
1680
1681 // TODO: Record them
1682 // Simple/fast spam filter ($target: 'a string' or an array())
1683 function pkwk_spamfilter($action, $page, $target = array('title' => ''), $method = array(), $exitmode = '')
1684 {
1685         $progress = check_uri_spam($target, $method);
1686
1687         if (empty($progress['is_spam'])) {
1688                 spam_dispose();
1689         } else {
1690
1691 // TODO: detect encoding from $target for mbstring functions
1692 //              $tmp = array();
1693 //              foreach(array_keys($target) as $key) {
1694 //                      $tmp[strings($key, 0, FALSE, TRUE)] = strings($target[$key], 0, FALSE, TRUE);   // Removing "\0" etc
1695 //              }
1696 //              $target = & $tmp;
1697
1698                 pkwk_spamnotify($action, $page, $target, $progress, $method);
1699                 spam_exit($exitmode, $progress);
1700         }
1701 }
1702
1703 // ---------------------
1704 // PukiWiki original
1705
1706 // Mail to administrator(s)
1707 function pkwk_spamnotify($action, $page, $target = array('title' => ''), $progress = array(), $method = array())
1708 {
1709         global $notify, $notify_subject;
1710
1711         if (! $notify) return;
1712
1713         $asap = isset($method['asap']);
1714
1715         $summary['ACTION']  = 'Blocked by: ' . summarize_spam_progress($progress, TRUE);
1716         if (! $asap) {
1717                 $summary['METRICS'] = summarize_spam_progress($progress);
1718         }
1719
1720         $tmp = summarize_detail_badhost($progress);
1721         if ($tmp != '') $summary['DETAIL_BADHOST'] = $tmp;
1722
1723         $tmp = summarize_detail_newtral($progress);
1724         if (! $asap && $tmp != '') $summary['DETAIL_NEUTRAL_HOST'] = $tmp;
1725
1726         $summary['COMMENT'] = $action;
1727         $summary['PAGE']    = '[blocked] ' . (is_pagename($page) ? $page : '');
1728         $summary['URI']     = get_script_uri() . '?' . rawurlencode($page);
1729         $summary['USER_AGENT']  = TRUE;
1730         $summary['REMOTE_ADDR'] = TRUE;
1731         pkwk_mail_notify($notify_subject,  var_export($target, TRUE), $summary, TRUE);
1732 }
1733
1734 ?>