OSDN Git Service

spam_uri_pickup(): Just renaming variable: $area => $method
[pukiwiki/pukiwiki_sandbox.git] / spam.php
1 <?php
2 // $Id: spam.php,v 1.68 2006/12/12 15:04:22 henoheno Exp $
3 // Copyright (C) 2006 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 if (! defined('SPAM_INI_FILE')) define('SPAM_INI_FILE', 'spam.ini.php');
9
10 // ---------------------
11 // URI pickup
12
13 // Return an array of URIs in the $string
14 // [OK] http://nasty.example.org#nasty_string
15 // [OK] http://nasty.example.org:80/foo/xxx#nasty_string/bar
16 // [OK] ftp://nasty.example.org:80/dfsdfs
17 // [OK] ftp://cnn.example.com&story=breaking_news@10.0.0.1/top_story.htm (from RFC3986)
18 function uri_pickup($string = '', $normalize = TRUE,
19         $preserve_rawuri = FALSE, $preserve_chunk = TRUE)
20 {
21         // Not available for: IDN(ignored)
22         $array = array();
23         preg_match_all(
24                 // scheme://userinfo@host:port/path/or/pathinfo/maybefile.and?query=string#fragment
25                 // Refer RFC3986 (Regex below is not strict)
26                 '#(\b[a-z][a-z0-9.+-]{1,8})://' .       // 1: Scheme
27                 '(?:' .
28                         '([^\s<>"\'\[\]/\#?@]*)' .              // 2: Userinfo (Username)
29                 '@)?' .
30                 '(' .
31                         // 3: Host
32                         '\[[0-9a-f:.]+\]' . '|' .                               // IPv6([colon-hex and dot]): RFC2732
33                         '(?:[0-9]{1-3}\.){3}[0-9]{1-3}' . '|' . // IPv4(dot-decimal): 001.22.3.44
34                         '[^\s<>"\'\[\]:/\#?]+' .                                // FQDN: foo.example.org
35                 ')' .
36                 '(?::([0-9]*))?' .                                      // 4: Port
37                 '((?:/+[^\s<>"\'\[\]/\#]+)*/+)?' .      // 5: Directory path or path-info
38                 '([^\s<>"\'\[\]\#?]+)?' .                       // 6: File?
39                 '(?:\?([^\s<>"\'\[\]\#]+))?' .          // 7: Query string
40                 '(?:\#([a-z0-9._~%!$&\'()*+,;=:@-]*))?' .       // 8: Fragment
41                 '#i',
42                  $string, $array, PREG_SET_ORDER | PREG_OFFSET_CAPTURE
43         );
44         //var_dump(recursive_map('htmlspecialchars', $array));
45
46         // Shrink $array
47         static $parts = array(
48                 1 => 'scheme', 2 => 'userinfo', 3 => 'host', 4 => 'port',
49                 5 => 'path', 6 => 'file', 7 => 'query', 8 => 'fragment'
50         );
51         $default = array('');
52         foreach(array_keys($array) as $uri) {
53                 $_uri = & $array[$uri];
54                 array_rename_keys($_uri, $parts, TRUE, $default);
55
56                 $offset = $_uri['scheme'][1]; // Scheme's offset
57                 foreach(array_keys($_uri) as $part) {
58                         // Remove offsets for each part
59                         $_uri[$part] = & $_uri[$part][0];
60                 }
61
62                 if ($normalize) {
63                         $_uri['scheme'] = scheme_normalize($_uri['scheme']);
64                         if ($_uri['scheme'] === '') {
65                                 unset ($array[$uri]);
66                                 continue;
67                         }
68                         $_uri['host']  = strtolower($_uri['host']);
69                         $_uri['port']  = port_normalize($_uri['port'], $_uri['scheme'], FALSE);
70                         $_uri['path']  = path_normalize($_uri['path']);
71                         if ($preserve_rawuri) $_uri['rawuri'] = & $_uri[0];
72
73                         // DEBUG
74                         //$_uri['uri'] = uri_array_implode($_uri);
75                 } else {
76                         $_uri['uri'] = & $_uri[0]; // Raw
77                 }
78                 unset($_uri[0]); // Matched string itself
79                 if (! $preserve_chunk) {
80                         unset(
81                                 $_uri['scheme'],
82                                 $_uri['userinfo'],
83                                 $_uri['host'],
84                                 $_uri['port'],
85                                 $_uri['path'],
86                                 $_uri['file'],
87                                 $_uri['query'],
88                                 $_uri['fragment']
89                         );
90                 }
91
92                 // Area offset for area_measure()
93                 $_uri['area']['offset'] = $offset;
94         }
95
96         return $array;
97 }
98
99 // Destructive normalize of URI array
100 // NOTE: Give me the uri_pickup() result with chunks
101 function uri_array_normalize(& $pickups, $preserve = TRUE)
102 {
103         if (! is_array($pickups)) return $pickups;
104
105         foreach (array_keys($pickups) as $key) {
106                 $_key = & $pickups[$key];
107                 $_key['path']     = isset($_key['path']) ? strtolower($_key['path']) : '';
108                 $_key['file']     = isset($_key['file']) ? file_normalize($_key['file']) : '';
109                 $_key['query']    = isset($_key['query']) ? query_normalize(strtolower($_key['query']), TRUE) : '';
110                 $_key['fragment'] = (isset($_key['fragment']) && $preserve) ?
111                         strtolower($_key['fragment']) : ''; // Just ignore
112         }
113
114         return $pickups;
115 }
116
117 // An URI array => An URI (See uri_pickup())
118 function uri_array_implode($uri = array())
119 {
120         if (empty($uri) || ! is_array($uri)) return NULL;
121
122         $tmp = array();
123         if (isset($uri['scheme']) && $uri['scheme'] !== '') {
124                 $tmp[] = & $uri['scheme'];
125                 $tmp[] = '://';
126         }
127         if (isset($uri['userinfo']) && $uri['userinfo'] !== '') {
128                 $tmp[] = & $uri['userinfo'];
129                 $tmp[] = '@';
130         }
131         if (isset($uri['host']) && $uri['host'] !== '') {
132                 $tmp[] = & $uri['host'];
133         }
134         if (isset($uri['port']) && $uri['port'] !== '') {
135                 $tmp[] = ':';
136                 $tmp[] = & $uri['port'];
137         }
138         if (isset($uri['path']) && $uri['path'] !== '') {
139                 $tmp[] = & $uri['path'];
140         }
141         if (isset($uri['file']) && $uri['file'] !== '') {
142                 $tmp[] = & $uri['file'];
143         }
144         if (isset($uri['query']) && $uri['query'] !== '') {
145                 $tmp[] = '?';
146                 $tmp[] = & $uri['query'];
147         }
148         if (isset($uri['fragment']) && $uri['fragment'] !== '') {
149                 $tmp[] = '#';
150                 $tmp[] = & $uri['fragment'];
151         }
152
153         return implode('', $tmp);
154 }
155
156 // $array['something'] => $array['wanted']
157 function array_rename_keys(& $array, $keys = array('from' => 'to'), $force = FALSE, $default = '')
158 {
159         if (! is_array($array) || ! is_array($keys)) return FALSE;
160
161         // Nondestructive test
162         if (! $force)
163                 foreach(array_keys($keys) as $from)
164                         if (! isset($array[$from]))
165                                 return FALSE;
166
167         foreach($keys as $from => $to) {
168                 if ($from === $to) continue;
169                 if (! $force || isset($array[$from])) {
170                         $array[$to] = & $array[$from];
171                         unset($array[$from]);
172                 } else  {
173                         $array[$to] = $default;
174                 }
175         }
176
177         return TRUE;
178 }
179
180 // ---------------------
181 // Area pickup
182
183 // Pickup all of markup areas
184 function area_pickup($string = '', $method = array())
185 {
186         $area = array();
187
188         // Anchor tag pair by preg_match_all()
189         // [OK] <a href></a>
190         // [OK] <a href=  >Good site!</a>
191         // [OK] <a href= "#" >test</a>
192         // [OK] <a href="http://nasty.example.com">visit http://nasty.example.com/</a>
193         // [OK] <a href=\'http://nasty.example.com/\' >discount foobar</a> 
194         // [NG] <a href="http://ng.example.com">visit http://ng.example.com _not_ended_
195         if (isset($method['anchor'])) {
196                 $areas = array();
197                 preg_match_all('#<a\b[^>]*\bhref\b[^>]*>.*?</a\b[^>]*(>)#i',
198                          $string, $areas, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
199                 //var_dump(recursive_map('htmlspecialchars', $areas));
200                 foreach(array_keys($areas) as $_area) {
201                         $areas[$_area] =  array(
202                                 $areas[$_area][0][1], // Area start (<a href>)
203                                 $areas[$_area][1][1], // Area end   (</a>)
204                         );
205                 }
206                 if (! empty($areas)) $area['anchor'] = $areas;
207         }
208
209         // phpBB's "BBCode" pair by preg_match_all()
210         // [OK] [url][/url]
211         // [OK] [url]http://nasty.example.com/[/url]
212         // [OK] [link]http://nasty.example.com/[/link]
213         // [OK] [url=http://nasty.example.com]visit http://nasty.example.com/[/url]
214         // [OK] [link http://nasty.example.com/]buy something[/link]
215         if (isset($method['bbcode'])) {
216                 $areas = array();
217                 preg_match_all('#\[(url|link)\b[^\]]*\].*?\[/\1\b[^\]]*(\])#i',
218                          $string, $areas, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
219                 //var_dump(recursive_map('htmlspecialchars', $areas));
220                 foreach(array_keys($areas) as $_area) {
221                         $areas[$_area] = array(
222                                 $areas[$_area][0][1], // Area start ([url])
223                                 $areas[$_area][2][1], // Area end   ([/url])
224                         );
225                 }
226                 if (! empty($areas)) $area['bbcode'] = $areas;
227         }
228
229         // Various Wiki syntax
230         // [text_or_uri>text_or_uri]
231         // [text_or_uri:text_or_uri]
232         // [text_or_uri|text_or_uri]
233         // [text_or_uri->text_or_uri]
234         // [text_or_uri text_or_uri] // MediaWiki
235         // MediaWiki: [http://nasty.example.com/ visit http://nasty.example.com/]
236
237         return $area;
238 }
239
240 // If in doubt, it's a little doubtful
241 // if (Area => inside <= Area) $brief += -1
242 function area_measure($areas, & $array, $belief = -1, $a_key = 'area', $o_key = 'offset')
243 {
244         if (! is_array($areas) || ! is_array($array)) return;
245
246         $areas_keys = array_keys($areas);
247         foreach(array_keys($array) as $u_index) {
248                 $offset = isset($array[$u_index][$o_key]) ?
249                         intval($array[$u_index][$o_key]) : 0;
250                 foreach($areas_keys as $a_index) {
251                         if (isset($array[$u_index][$a_key])) {
252                                 $offset_s = intval($areas[$a_index][0]);
253                                 $offset_e = intval($areas[$a_index][1]);
254                                 // [Area => inside <= Area]
255                                 if ($offset_s < $offset && $offset < $offset_e) {
256                                         $array[$u_index][$a_key] += $belief;
257                                 }
258                         }
259                 }
260         }
261 }
262
263 // ---------------------
264 // Spam-uri pickup
265
266 // Domain exposure callback (See spam_uri_pickup_preprocess())
267 // http://victim.example.org/?foo+site:nasty.example.com+bar
268 // => http://nasty.example.com/?refer=victim.example.org
269 // NOTE: 'refer=' is not so good for (at this time).
270 // Consider about using IP address of the victim, try to avoid that.
271 function _preg_replace_callback_domain_exposure($matches = array())
272 {
273         $result = '';
274
275         // Preserve the victim URI as a complicity or ...
276         if (isset($matches[5])) {
277                 $result =
278                         $matches[1] . '://' .   // scheme
279                         $matches[2] . '/' .             // victim.example.org
280                         $matches[3];                    // The rest of all (before victim)
281         }
282
283         // Flipped URI
284         if (isset($matches[4])) {
285                 $result = 
286                         $matches[1] . '://' .   // scheme
287                         $matches[4] .                   // nasty.example.com
288                         '/?refer=' . strtolower($matches[2]) .  // victim.example.org
289                         ' ' . $result;
290         }
291
292         return $result;
293 }
294
295 // Preprocess: rawurldecode() and adding space(s) and something
296 // to detect/count some URIs _if possible_
297 // NOTE: It's maybe danger to var_dump(result). [e.g. 'javascript:']
298 // [OK] http://victim.example.org/go?http%3A%2F%2Fnasty.example.org
299 // [OK] http://victim.example.org/http://nasty.example.org
300 function spam_uri_pickup_preprocess($string = '')
301 {
302         if (! is_string($string)) return '';
303
304         $string = rawurldecode($string);
305
306         // Domain exposure (See _preg_replace_callback_domain_exposure())
307         $string = preg_replace_callback(
308                 array(
309                         // Something Google: http://www.google.com/supported_domains
310                         '#(http)://([a-z0-9.]+\.google\.[a-z]{2,3}(?:\.[a-z]{2})?)/' .
311                         '([a-z0-9?=&.%_+-]+)' .         // ?query=foo+
312                         '\bsite:([a-z0-9.%_-]+)' .      // site:nasty.example.com
313                         //'()' .        // Preserve or remove?
314                         '#i',
315                 ),
316                 '_preg_replace_callback_domain_exposure',
317                 $string
318         );
319
320         // URI exposure (uriuri => uri uri)
321         $string = preg_replace(
322                 array(
323                         '#(?<! )(?:https?|ftp):/#i',
324                 //      '#[a-z][a-z0-9.+-]{1,8}://#i',
325                 //      '#[a-z][a-z0-9.+-]{1,8}://#i'
326                 ),
327                 ' $0',
328                 $string
329         );
330
331         return $string;
332 }
333
334 // Main function of spam-uri pickup
335 function spam_uri_pickup($string = '', $method = array())
336 {
337         $string = spam_uri_pickup_preprocess($string);
338
339         $array  = uri_pickup($string);
340
341         // Area elevation for '(especially external)link' intension
342         if (! empty($array)) {
343                 $areas = area_pickup($string, $method);
344                 if (! empty($areas)) {
345                         $area_shadow = array();
346                         foreach(array_keys($array) as $key){
347                                 $area_shadow[$key] = & $array[$key]['area'];
348                                 $area_shadow[$key]['anchor'] = 0;
349                                 $area_shadow[$key]['bbcode'] = 0;
350                         }
351                         if (isset($areas['anchor'])) {
352                                 area_measure($areas['anchor'], $area_shadow, 1, 'anchor');
353                         }
354                         if (isset($areas['bbcode'])) {
355                                 area_measure($areas['bbcode'], $area_shadow, 1, 'bbcode');
356                         }
357                 }
358         }
359
360         // Remove 'offset's for area_measure()
361         foreach(array_keys($array) as $key)
362                 unset($array[$key]['area']['offset']);
363
364         return $array;
365 }
366
367
368 // ---------------------
369 // Normalization
370
371 // Scheme normalization: Renaming the schemes
372 // snntp://example.org =>  nntps://example.org
373 // NOTE: Keep the static lists simple. See also port_normalize().
374 function scheme_normalize($scheme = '', $considerd_harmfull = TRUE)
375 {
376         // Abbreviations considerable they don't have link intension
377         static $abbrevs = array(
378                 'ttp'   => 'http',
379                 'ttps'  => 'https',
380         );
381
382         // Alias => normalized
383         static $aliases = array(
384                 'pop'   => 'pop3',
385                 'news'  => 'nntp',
386                 'imap4' => 'imap',
387                 'snntp' => 'nntps',
388                 'snews' => 'nntps',
389                 'spop3' => 'pop3s',
390                 'pops'  => 'pop3s',
391         );
392
393         $scheme = strtolower(trim($scheme));
394         if (isset($abbrevs[$scheme])) {
395                 if ($considerd_harmfull) {
396                         $scheme = $abbrevs[$scheme];
397                 } else {
398                         $scheme = '';
399                 }
400         }
401         if (isset($aliases[$scheme])) $scheme = $aliases[$scheme];
402
403         return $scheme;
404 }
405
406 // Port normalization: Suppress the (redundant) default port
407 // HTTP://example.org:80/ => http://example.org/
408 // HTTP://example.org:8080/ => http://example.org:8080/
409 // HTTPS://example.org:443/ => https://example.org/
410 function port_normalize($port, $scheme, $scheme_normalize = TRUE)
411 {
412         // Schemes that users _maybe_ want to add protocol-handlers
413         // to their web browsers. (and attackers _maybe_ want to use ...)
414         // Reference: http://www.iana.org/assignments/port-numbers
415         static $array = array(
416                 // scheme => default port
417                 'ftp'     =>    21,
418                 'ssh'     =>    22,
419                 'telnet'  =>    23,
420                 'smtp'    =>    25,
421                 'tftp'    =>    69,
422                 'gopher'  =>    70,
423                 'finger'  =>    79,
424                 'http'    =>    80,
425                 'pop3'    =>   110,
426                 'sftp'    =>   115,
427                 'nntp'    =>   119,
428                 'imap'    =>   143,
429                 'irc'     =>   194,
430                 'wais'    =>   210,
431                 'https'   =>   443,
432                 'nntps'   =>   563,
433                 'rsync'   =>   873,
434                 'ftps'    =>   990,
435                 'telnets' =>   992,
436                 'imaps'   =>   993,
437                 'ircs'    =>   994,
438                 'pop3s'   =>   995,
439                 'mysql'   =>  3306,
440         );
441
442         $port = trim($port);
443         if ($port === '') return $port;
444
445         if ($scheme_normalize) $scheme = scheme_normalize($scheme);
446         if (isset($array[$scheme]) && $port == $array[$scheme])
447                 $port = ''; // Ignore the defaults
448
449         return $port;
450 }
451
452 // Path normalization
453 // http://example.org => http://example.org/
454 // http://example.org#hoge => http://example.org/#hoge
455 // http://example.org/path/a/b/./c////./d => http://example.org/path/a/b/c/d
456 // http://example.org/path/../../a/../back => http://example.org/back
457 function path_normalize($path = '', $divider = '/', $addroot = TRUE)
458 {
459         if (! is_string($path) || $path == '')
460                 return $addroot ? $divider : '';
461
462         $path = trim($path);
463         $last = ($path[strlen($path) - 1] == $divider) ? $divider : '';
464         $array = explode($divider, $path);
465
466         // Remove paddings
467         foreach(array_keys($array) as $key) {
468                 if ($array[$key] == '' || $array[$key] == '.')
469                          unset($array[$key]);
470         }
471         // Back-track
472         $tmp = array();
473         foreach($array as $value) {
474                 if ($value == '..') {
475                         array_pop($tmp);
476                 } else {
477                         array_push($tmp, $value);
478                 }
479         }
480         $array = & $tmp;
481
482         $path = $addroot ? $divider : '';
483         if (! empty($array)) $path .= implode($divider, $array) . $last;
484
485         return $path;
486 }
487
488 // DirectoryIndex normalize (Destructive and rough)
489 function file_normalize($string = 'index.html.en')
490 {
491         static $array = array(
492                 'index'                 => TRUE,        // Some system can omit the suffix
493                 'index.htm'             => TRUE,
494                 'index.html'    => TRUE,
495                 'index.shtml'   => TRUE,
496                 'index.jsp'             => TRUE,
497                 'index.php'             => TRUE,
498                 'index.php3'    => TRUE,
499                 'index.php4'    => TRUE,
500                 //'index.pl'    => TRUE,
501                 //'index.py'    => TRUE,
502                 //'index.rb'    => TRUE,
503                 'index.cgi'             => TRUE,
504                 'default.htm'   => TRUE,
505                 'default.html'  => TRUE,
506                 'default.asp'   => TRUE,
507                 'default.aspx'  => TRUE,
508         );
509
510         // Content-negothiation filter:
511         // Roughly removing ISO 639 -like
512         // 2-letter suffixes (See RFC3066)
513         $matches = array();
514         if (preg_match('/(.*)\.[a-z][a-z](?:-[a-z][a-z])?$/i', $string, $matches)) {
515                 $_string = $matches[1];
516         } else {
517                 $_string = & $string;
518         }
519
520         if (isset($array[strtolower($_string)])) {
521                 return '';
522         } else {
523                 return $string;
524         }
525 }
526
527 // Sort query-strings if possible (Destructive and rough)
528 // [OK] &&&&f=d&b&d&c&a=0dd  =>  a=0dd&b&c&d&f=d
529 // [OK] nothing==&eg=dummy&eg=padding&eg=foobar  =>  eg=foobar
530 function query_normalize($string = '', $equal = FALSE, $equal_cutempty = TRUE)
531 {
532         $array = explode('&', $string);
533
534         // Remove '&' paddings
535         foreach(array_keys($array) as $key) {
536                 if ($array[$key] == '') {
537                          unset($array[$key]);
538                 }
539         }
540
541         // Consider '='-sepalated input and paddings
542         if ($equal) {
543                 $equals = $not_equals = array();
544                 foreach ($array as $part) {
545                         if (strpos($part, '=') === FALSE) {
546                                  $not_equals[] = $part;
547                         } else {
548                                 list($key, $value) = explode('=', $part, 2);
549                                 $value = ltrim($value, '=');
550                                 if (! $equal_cutempty || $value != '') {
551                                         $equals[$key] = $value;
552                                 }
553                         }
554                 }
555
556                 $array = & $not_equals;
557                 foreach ($equals as $key => $value) {
558                         $array[] = $key . '=' . $value;
559                 }
560                 unset($equals);
561         }
562
563         natsort($array);
564         return implode('&', $array);
565 }
566
567 // ---------------------
568 // Part One : Checker
569
570 function generate_glob_regex($string = '', $divider = '/')
571 {
572         static $from = array(
573                          1 => '*',
574                         11 => '?',
575         //              22 => '[',      // Maybe cause regex compilation error (e.g. '[]')
576         //              23 => ']',      //
577                 );
578         static $mid = array(
579                          1 => '_AST_',
580                         11 => '_QUE_',
581         //              22 => '_RBR_',
582         //              23 => '_LBR_',
583                 );
584         static $to = array(
585                          1 => '.*',
586                         11 => '.',
587         //              22 => '[',
588         //              23 => ']',
589                 );
590
591         if (is_array($string)) {
592                 // Recurse
593                 return '(?:' .
594                         implode('|',    // OR
595                                 array_map('generate_glob_regex',
596                                         $string,
597                                         array_pad(array(), count($string), $divider)
598                                 )
599                         ) .
600                 ')';
601         } else {
602                 $string = str_replace($from, $mid, $string); // Hide
603                 $string = preg_quote($string, $divider);
604                 $string = str_replace($mid, $to, $string);   // Unhide
605                 return $string;
606         }
607 }
608
609 // TODO: Ignore list
610 // TODO: preg_grep() ?
611 // TODO: Multi list
612 function is_badhost($hosts = '', $asap = TRUE)
613 {
614         static $regex;
615
616         if (! isset($regex)) {
617                 $regex = array();
618                 $regex['badhost'] = array();
619
620                 // Sample
621                 if (TRUE) {
622                         $blocklist['badhost'] = array(
623                                 //'*',                  // Deny all uri
624                                 //'10.20.*.*',  // 10.20.example.com also matches
625                                 //'*.blogspot.com',     // Blog services subdomains
626                                 //array('blogspot.com', '*.blogspot.com')
627                         );
628                         foreach ($blocklist['badhost'] as $part) {
629                                 if (is_array($part)) $part = implode(', ', $part);
630                                 $regex['badhost'][$part] = '/^' . generate_glob_regex($part) . '$/i';
631                         }
632                 }
633
634                 // Load
635                 if (file_exists(SPAM_INI_FILE)) {
636                         $blocklist = array();
637                         require(SPAM_INI_FILE);
638                         foreach ($blocklist['badhost'] as $part) {
639                                 if (is_array($part)) $part = implode(', ', $part);
640                                 $regex['badhost'][$part] = '/^' . generate_glob_regex($part) . '$/i';
641                         }
642                 }
643         }
644         //var_dump($regex);
645
646         $result = array();
647         if (! is_array($hosts)) $hosts = array($hosts);
648
649         foreach($hosts as $host) {
650                 if (! is_string($host)) $host = '';
651                 foreach ($regex['badhost'] as $part => $_regex) {
652                         if (preg_match($_regex, $host)) {
653                                 if (! isset($result[$part]))  $result[$part] = array();
654                                 $result[$part][] = $host;
655                                 if ($asap) {
656                                         return $result;
657                                 } else {
658                                         break;
659                                 }
660                         }
661                 }
662         }
663
664         return $result;
665 }
666
667 // Default (enabled) methods and thresholds
668 function check_uri_spam_method($times = 1, $t_area = 0, $rule = TRUE)
669 {
670         $times  = intval($times);
671         $t_area = intval($t_area);
672
673         // Thresholds
674         $method = array(
675                 'quantity' => 8 * $times,       // Allow N URIs
676                 'non_uniq' => 3 * $times,       // Allow N duped (and normalized) URIs
677         );
678
679         // Areas
680         $area = array(
681                 //'total' => $t_area,   // Allow N areas total, enabled below
682                 'anchor'  => $t_area,   // Inside <a href> HTML tag
683                 'bbcode'  => $t_area,   // Inside [url] or [link] BBCode
684         );
685
686         // Rules
687         $rules = array(
688                 'asap'     => FALSE,    // Quit As Soon As Possible
689                 'uniqhost' => TRUE,     // Show uniq host (at block notification mail)
690                 'badhost'  => TRUE,     // Check badhost
691         );
692
693         // Remove unused
694         foreach (array_keys($method) as $key) {
695                 if ($method[$key] < 0) unset($method[$key]);
696         }
697         foreach (array_keys($area) as $key) {
698                 if ($area[$key] < 0) unset($area[$key]);
699         }
700         $area  = empty($area) ? array() : array('area' => $area);
701         $rules = $rule ? $rules : array();
702
703         return $method + $area + $rules;
704 }
705
706 // Simple/fast spam check
707 function check_uri_spam($target = '', $method = array())
708 {
709         // Init
710         if (! is_array($method) || empty($method)) {
711                 $method = check_uri_spam_method();
712         }
713         $progress = array(
714                 'sum' => array(
715                         'quantity'    => 0,
716                         'uniqhost'    => 0,
717                         'non_uniq'    => 0,
718                         'badhost'     => 0,
719                         'area_total'  => 0,
720                         'area_anchor' => 0,
721                         'area_bbcode' => 0,
722                 ),
723                 'is_spam' => array(),
724                 'method'  => & $method,
725         );
726         $sum     = & $progress['sum'];
727         $is_spam = & $progress['is_spam'];
728         $asap = isset($method['asap']) ? $method['asap'] : TRUE;
729
730         // Return if ...
731         if (is_array($target)) {
732                 foreach($target as $str) {
733                         // Recurse
734                         $_progress = check_uri_spam($str, $method);
735                         foreach (array_keys($_progress['sum']) as $key) {
736                                 $sum[$key] += $_progress['sum'][$key];
737                         }
738                         foreach(array_keys($_progress['is_spam']) as $key) {
739                                 $is_spam[$key] = TRUE;
740                         }
741                         if ($asap && $is_spam) break;
742                 }
743                 return $progress;
744         }
745         $pickups = spam_uri_pickup($target);
746         if (empty($pickups)) {
747                 return $progress;
748         }
749
750         // Check quantity
751         $sum['quantity'] += count($pickups);
752                 // URI quantity
753         if ((! $asap || ! $is_spam) && isset($method['quantity']) &&
754                 $sum['quantity'] > $method['quantity']) {
755                 $is_spam['quantity'] = TRUE;
756         }
757         //var_dump($method['quantity'], $is_spam);
758
759         // Using invalid area
760         if ((! $asap || ! $is_spam) && isset($method['area'])) {
761                 foreach($pickups as $pickup) {
762                         foreach ($pickup['area'] as $key => $value) {
763                                 if ($key == 'offset') continue;
764                                 // Total
765                                 $sum['area_total'] += $value;
766                                 if (isset($method['area']['total']) &&
767                                         $sum['area_total'] > $method['area']['total']) {
768                                         $is_spam['area_total'] = TRUE;
769                                         if ($asap && $is_spam) break;
770                                 }
771                                 // Each area
772                                 $p_key = 'area_' . $key;
773                                 $sum[$p_key] += $value;
774                                 if(isset($method['area'][$key]) &&
775                                         $sum[$p_key] > $method['area'][$key]) {
776                                         $is_spam[$p_key] = TRUE;
777                                         if ($asap && $is_spam) break;
778                                 }
779                         }
780                         if ($asap && $is_spam) break;
781                 }
782         }
783         //var_dump($method['area'], $is_spam);
784
785         // URI uniqueness (and removing non-uniques)
786         if ((! $asap || ! $is_spam) && isset($method['non_uniq'])) {
787
788                 // Destructive normalize of URIs
789                 uri_array_normalize($pickups);
790
791                 $uris = array();
792                 foreach (array_keys($pickups) as $key) {
793                         $uris[$key] = uri_array_implode($pickups[$key]);
794                         }
795                 $count = count($uris);
796                 $uris  = array_unique($uris);
797                 $sum['non_uniq'] += $count - count($uris);
798                 if ($sum['non_uniq'] > $method['non_uniq']) {
799                         $is_spam['non_uniq'] = TRUE;
800                 }
801                 if (! $asap || ! $is_spam) {
802                         foreach (array_diff(array_keys($pickups),
803                                 array_keys($uris)) as $remove) {
804                                 unset($pickups[$remove]);
805                         }
806                 }
807                 unset($uris);
808         }
809         //var_dump($method['non_uniq'], $is_spam);
810
811         // Unique host
812         $hosts = array();
813         foreach ($pickups as $pickup) $hosts[] = & $pickup['host'];
814         $hosts = array_unique($hosts);
815         $sum['uniqhost'] += count($hosts);
816         //var_dump($method['uniqhost'], $is_spam);
817
818         // Bad host
819         if ((! $asap || ! $is_spam) && isset($method['badhost'])) {
820                 $count = array_count_leaves(is_badhost($hosts, $asap));
821                 $sum['badhost'] += $count;
822                 if ($count != 0) $is_spam['badhost'] = TRUE;
823         }
824         //var_dump($method['badhost'], $is_spam);
825
826         return $progress;
827 }
828
829 // Count leaves
830 function array_count_leaves($array = array(), $count_empty_array = FALSE)
831 {
832         if (! is_array($array) || (empty($array) && $count_empty_array))
833                 return 1;
834
835         // Recurse
836         $result = 0;
837         foreach ($array as $part) {
838                 $result += array_count_leaves($part, $count_empty_array);
839         }
840         return $result;
841 }
842
843 // ---------------------
844 // Reporting
845
846 // TODO: Don't show unused $method!
847 // Summarize $progress (blocked only)
848 function summarize_spam_progress($progress = array(), $blockedonly = FALSE)
849 {
850         $method = $progress['method'];
851         if (isset($method['area'])) {
852                 foreach(array_keys($method['area']) as $key) {
853                         $method['area_' . $key] = TRUE;
854                 }
855         }
856
857         if ($blockedonly) {
858                 $tmp = array_keys($progress['is_spam']);
859         } else {
860                 $tmp = array();
861                 foreach ($progress['sum'] as $key => $value) {
862                         if (isset($method[$key])) {
863                                 $tmp[] = $key . '(' . $value . ')';
864                         }
865                 }
866         }
867
868         return implode(', ', $tmp);
869 }
870
871 // ---------------------
872 // Exit
873
874 // Common bahavior for blocking
875 // NOTE: Call this function from various blocking feature, to disgueise the reason 'why blocked'
876 function spam_exit()
877 {
878         die("\n");
879 }
880
881
882 // ---------------------
883 // Simple filtering
884
885 // TODO: Record them
886 // Simple/fast spam filter ($target: 'a string' or an array())
887 function pkwk_spamfilter($action, $page, $target = array('title' => ''), $method = array())
888 {
889         global $notify;
890
891         $progress = check_uri_spam($target, $method);
892
893         if (! empty($progress['is_spam'])) {
894                 // Mail to administrator(s)
895                 if ($notify) pkwk_spamnotify($action, $page, $target, $progress, $method);
896                 // End
897                 spam_exit();
898         }
899 }
900
901 // ---------------------
902 // PukiWiki original
903
904 // Mail to administrator(s)
905 function pkwk_spamnotify($action, $page, $target = array('title' => ''), $progress = array(), $method = array())
906 {
907         global $notify_subject;
908
909         $asap = isset($method['asap']) ? $method['asap'] : TRUE;
910
911         $footer['ACTION']  = 'Blocked by: ' . summarize_spam_progress($progress, TRUE);
912
913         if (! $asap) {
914                 $footer['METRICS'] = summarize_spam_progress($progress);
915         }
916         $footer['COMMENT'] = $action;
917         $footer['PAGE']    = '[blocked] ' . $page;
918         $footer['URI']     = get_script_uri() . '?' . rawurlencode($page);
919         $footer['USER_AGENT']  = TRUE;
920         $footer['REMOTE_ADDR'] = TRUE;
921         pkwk_mail_notify($notify_subject,  var_export($target, TRUE), $footer);
922 }
923
924 ?>