OSDN Git Service

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