OSDN Git Service

Simplify check_uri_spam()
[pukiwiki/pukiwiki_sandbox.git] / spam / spam.php
1 <?php
2 // $Id: spam.php,v 1.66 2006/12/10 05:56:32 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 = '', $area = array())
336 {
337         if (! is_array($area) || empty($area)) {
338                 $area = array(
339                         'anchor' => TRUE,
340                         'bbcode' => TRUE,
341                 );
342         }
343
344         $string = spam_uri_pickup_preprocess($string);
345
346         $array  = uri_pickup($string);
347
348         // Area elevation for '(especially external)link' intension
349         if (! empty($array)) {
350                 $areas = area_pickup($string, $area);
351                 if (! empty($areas)) {
352                         $area_shadow = array();
353                         foreach(array_keys($array) as $key){
354                                 $area_shadow[$key] = & $array[$key]['area'];
355                                 $area_shadow[$key]['anchor'] = 0;
356                                 $area_shadow[$key]['bbcode'] = 0;
357                         }
358                         if (isset($areas['anchor'])) {
359                                 area_measure($areas['anchor'], $area_shadow, 1, 'anchor');
360                         }
361                         if (isset($areas['bbcode'])) {
362                                 area_measure($areas['bbcode'], $area_shadow, 1, 'bbcode');
363                         }
364                 }
365         }
366
367         // Remove 'offset's for area_measure()
368         foreach(array_keys($array) as $key)
369                 unset($array[$key]['area']['offset']);
370
371         return $array;
372 }
373
374
375 // ---------------------
376 // Normalization
377
378 // Scheme normalization: Renaming the schemes
379 // snntp://example.org =>  nntps://example.org
380 // NOTE: Keep the static lists simple. See also port_normalize().
381 function scheme_normalize($scheme = '', $considerd_harmfull = TRUE)
382 {
383         // Abbreviations considerable they don't have link intension
384         static $abbrevs = array(
385                 'ttp'   => 'http',
386                 'ttps'  => 'https',
387         );
388
389         // Alias => normalized
390         static $aliases = array(
391                 'pop'   => 'pop3',
392                 'news'  => 'nntp',
393                 'imap4' => 'imap',
394                 'snntp' => 'nntps',
395                 'snews' => 'nntps',
396                 'spop3' => 'pop3s',
397                 'pops'  => 'pop3s',
398         );
399
400         $scheme = strtolower(trim($scheme));
401         if (isset($abbrevs[$scheme])) {
402                 if ($considerd_harmfull) {
403                         $scheme = $abbrevs[$scheme];
404                 } else {
405                         $scheme = '';
406                 }
407         }
408         if (isset($aliases[$scheme])) $scheme = $aliases[$scheme];
409
410         return $scheme;
411 }
412
413 // Port normalization: Suppress the (redundant) default port
414 // HTTP://example.org:80/ => http://example.org/
415 // HTTP://example.org:8080/ => http://example.org:8080/
416 // HTTPS://example.org:443/ => https://example.org/
417 function port_normalize($port, $scheme, $scheme_normalize = TRUE)
418 {
419         // Schemes that users _maybe_ want to add protocol-handlers
420         // to their web browsers. (and attackers _maybe_ want to use ...)
421         // Reference: http://www.iana.org/assignments/port-numbers
422         static $array = array(
423                 // scheme => default port
424                 'ftp'     =>    21,
425                 'ssh'     =>    22,
426                 'telnet'  =>    23,
427                 'smtp'    =>    25,
428                 'tftp'    =>    69,
429                 'gopher'  =>    70,
430                 'finger'  =>    79,
431                 'http'    =>    80,
432                 'pop3'    =>   110,
433                 'sftp'    =>   115,
434                 'nntp'    =>   119,
435                 'imap'    =>   143,
436                 'irc'     =>   194,
437                 'wais'    =>   210,
438                 'https'   =>   443,
439                 'nntps'   =>   563,
440                 'rsync'   =>   873,
441                 'ftps'    =>   990,
442                 'telnets' =>   992,
443                 'imaps'   =>   993,
444                 'ircs'    =>   994,
445                 'pop3s'   =>   995,
446                 'mysql'   =>  3306,
447         );
448
449         $port = trim($port);
450         if ($port === '') return $port;
451
452         if ($scheme_normalize) $scheme = scheme_normalize($scheme);
453         if (isset($array[$scheme]) && $port == $array[$scheme])
454                 $port = ''; // Ignore the defaults
455
456         return $port;
457 }
458
459 // Path normalization
460 // http://example.org => http://example.org/
461 // http://example.org#hoge => http://example.org/#hoge
462 // http://example.org/path/a/b/./c////./d => http://example.org/path/a/b/c/d
463 // http://example.org/path/../../a/../back => http://example.org/back
464 function path_normalize($path = '', $divider = '/', $addroot = TRUE)
465 {
466         if (! is_string($path) || $path == '')
467                 return $addroot ? $divider : '';
468
469         $path = trim($path);
470         $last = ($path[strlen($path) - 1] == $divider) ? $divider : '';
471         $array = explode($divider, $path);
472
473         // Remove paddings
474         foreach(array_keys($array) as $key) {
475                 if ($array[$key] == '' || $array[$key] == '.')
476                          unset($array[$key]);
477         }
478         // Back-track
479         $tmp = array();
480         foreach($array as $value) {
481                 if ($value == '..') {
482                         array_pop($tmp);
483                 } else {
484                         array_push($tmp, $value);
485                 }
486         }
487         $array = & $tmp;
488
489         $path = $addroot ? $divider : '';
490         if (! empty($array)) $path .= implode($divider, $array) . $last;
491
492         return $path;
493 }
494
495 // DirectoryIndex normalize (Destructive and rough)
496 function file_normalize($string = 'index.html.en')
497 {
498         static $array = array(
499                 'index'                 => TRUE,        // Some system can omit the suffix
500                 'index.htm'             => TRUE,
501                 'index.html'    => TRUE,
502                 'index.shtml'   => TRUE,
503                 'index.jsp'             => TRUE,
504                 'index.php'             => TRUE,
505                 'index.php3'    => TRUE,
506                 'index.php4'    => TRUE,
507                 //'index.pl'    => TRUE,
508                 //'index.py'    => TRUE,
509                 //'index.rb'    => TRUE,
510                 'index.cgi'             => TRUE,
511                 'default.htm'   => TRUE,
512                 'default.html'  => TRUE,
513                 'default.asp'   => TRUE,
514                 'default.aspx'  => TRUE,
515         );
516
517         // Content-negothiation filter:
518         // Roughly removing ISO 639 -like
519         // 2-letter suffixes (See RFC3066)
520         $matches = array();
521         if (preg_match('/(.*)\.[a-z][a-z](?:-[a-z][a-z])?$/i', $string, $matches)) {
522                 $_string = $matches[1];
523         } else {
524                 $_string = & $string;
525         }
526
527         if (isset($array[strtolower($_string)])) {
528                 return '';
529         } else {
530                 return $string;
531         }
532 }
533
534 // Sort query-strings if possible (Destructive and rough)
535 // [OK] &&&&f=d&b&d&c&a=0dd  =>  a=0dd&b&c&d&f=d
536 // [OK] nothing==&eg=dummy&eg=padding&eg=foobar  =>  eg=foobar
537 function query_normalize($string = '', $equal = FALSE, $equal_cutempty = TRUE)
538 {
539         $array = explode('&', $string);
540
541         // Remove '&' paddings
542         foreach(array_keys($array) as $key) {
543                 if ($array[$key] == '') {
544                          unset($array[$key]);
545                 }
546         }
547
548         // Consider '='-sepalated input and paddings
549         if ($equal) {
550                 $equals = $not_equals = array();
551                 foreach ($array as $part) {
552                         if (strpos($part, '=') === FALSE) {
553                                  $not_equals[] = $part;
554                         } else {
555                                 list($key, $value) = explode('=', $part, 2);
556                                 $value = ltrim($value, '=');
557                                 if (! $equal_cutempty || $value != '') {
558                                         $equals[$key] = $value;
559                                 }
560                         }
561                 }
562
563                 $array = & $not_equals;
564                 foreach ($equals as $key => $value) {
565                         $array[] = $key . '=' . $value;
566                 }
567                 unset($equals);
568         }
569
570         natsort($array);
571         return implode('&', $array);
572 }
573
574 // ---------------------
575 // Part One : Checker
576
577 function generate_glob_regex($string = '', $divider = '/')
578 {
579         static $from = array(
580                          1 => '*',
581                         11 => '?',
582         //              22 => '[',      // Maybe cause regex compilation error (e.g. '[]')
583         //              23 => ']',      //
584                 );
585         static $mid = array(
586                          1 => '_AST_',
587                         11 => '_QUE_',
588         //              22 => '_RBR_',
589         //              23 => '_LBR_',
590                 );
591         static $to = array(
592                          1 => '.*',
593                         11 => '.',
594         //              22 => '[',
595         //              23 => ']',
596                 );
597
598         if (is_array($string)) {
599                 // Recurse
600                 return '(?:' .
601                         implode('|',    // OR
602                                 array_map('generate_glob_regex',
603                                         $string,
604                                         array_pad(array(), count($string), $divider)
605                                 )
606                         ) .
607                 ')';
608         } else {
609                 $string = str_replace($from, $mid, $string); // Hide
610                 $string = preg_quote($string, $divider);
611                 $string = str_replace($mid, $to, $string);   // Unhide
612                 return $string;
613         }
614 }
615
616 // TODO: Ignore list
617 // TODO: preg_grep() ?
618 // TODO: Multi list
619 function is_badhost($hosts = '', $asap = TRUE)
620 {
621         static $regex;
622
623         if (! isset($regex)) {
624                 $regex = array();
625                 $regex['badhost'] = array();
626
627                 // Sample
628                 if (TRUE) {
629                         $blocklist['badhost'] = array(
630                                 //'*',                  // Deny all uri
631                                 //'10.20.*.*',  // 10.20.example.com also matches
632                                 //'*.blogspot.com',     // Blog services subdomains
633                                 //array('blogspot.com', '*.blogspot.com')
634                         );
635                         foreach ($blocklist['badhost'] as $part) {
636                                 $regex['badhost'][$part] = '/^' . generate_glob_regex($part) . '$/i';
637                         }
638                 }
639
640                 // Load
641                 if (file_exists(SPAM_INI_FILE)) {
642                         $blocklist = array();
643                         require(SPAM_INI_FILE);
644                         foreach ($blocklist['badhost'] as $part) {
645                                 $regex['badhost'][$part] = '/^' . generate_glob_regex($part) . '$/i';
646                         }
647                 }
648         }
649         //var_dump($regex);
650
651         $result = array();
652         if (! is_array($hosts)) $hosts = array($hosts);
653
654         foreach($hosts as $host) {
655                 if (! is_string($host)) $host = '';
656                 foreach ($regex['badhost'] as $part => $_regex) {
657                         if (preg_match($_regex, $host)) {
658                                 if (! isset($result[$part]))  $result[$part] = array();
659                                 $result[$part][] = $host;
660                                 if ($asap) {
661                                         return $result;
662                                 } else {
663                                         break;
664                                 }
665                         }
666                 }
667         }
668
669         return $result;
670 }
671
672 // Default (enabled) methods and thresholds
673 function check_uri_spam_method($times = 1, $t_area = 0, $rule = TRUE)
674 {
675         $times  = intval($times);
676         $t_area = intval($t_area);
677
678         // Thresholds
679         $method = array(
680                 'quantity' => 8 * $times,       // Allow N URIs
681                 'non_uniq' => 3 * $times,       // Allow N duped (and normalized) URIs
682         );
683
684         // Areas
685         $area = array(
686                 //'total' => $t_area,   // Allow N areas total, enabled below
687                 'anchor'  => $t_area,   // Inside <a href> HTML tag
688                 'bbcode'  => $t_area,   // Inside [url] or [link] BBCode
689         );
690
691         // Rules
692         $rules = array(
693                 'asap'     => FALSE,    // Quit As Soon As Possible
694                 'uniqhost' => TRUE,     // Show uniq host (at block notification mail)
695                 'badhost'  => TRUE,     // Check badhost
696         );
697
698         // Remove unused
699         foreach (array_keys($method) as $key) {
700                 if ($method[$key] < 0) unset($method[$key]);
701         }
702         foreach (array_keys($area) as $key) {
703                 if ($area[$key] < 0) unset($area[$key]);
704         }
705         $area  = empty($area) ? array() : array('area' => $area);
706         $rules = $rule ? $rules : array();
707
708         return $method + $area + $rules;
709 }
710
711 // Simple/fast spam check
712 function check_uri_spam($target = '', $method = array())
713 {
714         // Init
715         if (! is_array($method) || empty($method)) {
716                 $method = check_uri_spam_method();
717         }
718         $progress = array(
719                 'sum' => array(
720                         'quantity'    => 0,
721                         'uniqhost'    => 0,
722                         'non_uniq'    => 0,
723                         'badhost'     => 0,
724                         'area_total'  => 0,
725                         'area_anchor' => 0,
726                         'area_bbcode' => 0,
727                 ),
728                 'is_spam' => array(),
729                 'method'  => & $method,
730         );
731         $sum     = & $progress['sum'];
732         $is_spam = & $progress['is_spam'];
733         $asap = isset($method['asap']) ? $method['asap'] : TRUE;
734
735         // Return if ...
736         if (is_array($target)) {
737                 foreach($target as $str) {
738                         // Recurse
739                         $_progress = check_uri_spam($str, $method);
740                         foreach (array_keys($_progress['sum']) as $key) {
741                                 $sum[$key] += $_progress['sum'][$key];
742                         }
743                         foreach(array_keys($_progress['is_spam']) as $key) {
744                                 $is_spam[$key] = TRUE;
745                         }
746                         if ($asap && $is_spam) break;
747                 }
748                 return $progress;
749         }
750         $pickups = spam_uri_pickup($target);
751         if (empty($pickups)) {
752                 return $progress;
753         }
754
755         // Check quantity
756         $sum['quantity'] += count($pickups);
757                 // URI quantity
758         if ((! $asap || ! $is_spam) && isset($method['quantity']) &&
759                 $sum['quantity'] > $method['quantity']) {
760                 $is_spam['quantity'] = TRUE;
761         }
762         //var_dump($method['quantity'], $is_spam);
763
764         // Using invalid area
765         if ((! $asap || ! $is_spam) && isset($method['area'])) {
766                 foreach($pickups as $pickup) {
767                         foreach ($pickup['area'] as $key => $value) {
768                                 if ($key == 'offset') continue;
769                                 // Total
770                                 $sum['area_total'] += $value;
771                                 if (isset($method['area']['total']) &&
772                                         $sum['area_total'] > $method['area']['total']) {
773                                         $is_spam['area_total'] = TRUE;
774                                         if ($asap && $is_spam) break;
775                                 }
776                                 // Each area
777                                 $p_key = 'area_' . $key;
778                                 $sum[$p_key] += $value;
779                                 if(isset($method['area'][$key]) &&
780                                         $sum[$p_key] > $method['area'][$key]) {
781                                         $is_spam[$p_key] = TRUE;
782                                         if ($asap && $is_spam) break;
783                                 }
784                         }
785                         if ($asap && $is_spam) break;
786                 }
787         }
788         //var_dump($method['area'], $is_spam);
789
790         // URI uniqueness (and removing non-uniques)
791         if ((! $asap || ! $is_spam) && isset($method['non_uniq'])) {
792
793                 // Destructive normalize of URIs
794                 uri_array_normalize($pickups);
795
796                 $uris = array();
797                 foreach (array_keys($pickups) as $key) {
798                         $uris[$key] = uri_array_implode($pickups[$key]);
799                         }
800                 $count = count($uris);
801                 $uris  = array_unique($uris);
802                 $sum['non_uniq'] += $count - count($uris);
803                 if ($sum['non_uniq'] > $method['non_uniq']) {
804                         $is_spam['non_uniq'] = TRUE;
805                 }
806                 if (! $asap || ! $is_spam) {
807                         foreach (array_diff(array_keys($pickups),
808                                 array_keys($uris)) as $remove) {
809                                 unset($pickups[$remove]);
810                         }
811                 }
812                 unset($uris);
813         }
814         //var_dump($method['non_uniq'], $is_spam);
815
816         // Unique host
817         $hosts = array();
818         foreach ($pickups as $pickup) $hosts[] = & $pickup['host'];
819         $hosts = array_unique($hosts);
820         $sum['uniqhost'] += count($hosts);
821         //var_dump($method['uniqhost'], $is_spam);
822
823         // Bad host
824         if ((! $asap || ! $is_spam) && isset($method['badhost'])) {
825                 $count = array_count_leaves(is_badhost($hosts, $asap));
826                 $sum['badhost'] += $count;
827                 if ($count != 0) $is_spam['badhost'] = TRUE;
828         }
829         //var_dump($method['badhost'], $is_spam);
830
831         return $progress;
832 }
833
834 // Count leaves
835 function array_count_leaves($array = array(), $count_empty_array = FALSE)
836 {
837         if (! is_array($array) || (empty($array) && $count_empty_array))
838                 return 1;
839
840         // Recurse
841         $result = 0;
842         foreach ($array as $part) {
843                 $result += array_count_leaves($part, $count_empty_array);
844         }
845         return $result;
846 }
847
848 // ---------------------
849 // Reporting
850
851 // TODO: Don't show unused $method!
852 // Summarize $progress (blocked only)
853 function summarize_spam_progress($progress = array(), $blockedonly = FALSE)
854 {
855         $method = $progress['method'];
856         if (isset($method['area'])) {
857                 foreach(array_keys($method['area']) as $key) {
858                         $method['area_' . $key] = TRUE;
859                 }
860         }
861
862         if ($blockedonly) {
863                 $tmp = array_keys($progress['is_spam']);
864         } else {
865                 $tmp = array();
866                 foreach ($progress['sum'] as $key => $value) {
867                         if (isset($method[$key])) {
868                                 $tmp[] = $key . '(' . $value . ')';
869                         }
870                 }
871         }
872
873         return implode(', ', $tmp);
874 }
875
876 // ---------------------
877 // Exit
878
879 // Common bahavior for blocking
880 // NOTE: Call this function from various blocking feature, to disgueise the reason 'why blocked'
881 function spam_exit()
882 {
883         die("\n");
884 }
885
886
887 // ---------------------
888 // Simple filtering
889
890 // TODO: Record them
891 // Simple/fast spam filter ($target: 'a string' or an array())
892 function pkwk_spamfilter($action, $page, $target = array('title' => ''), $method = array())
893 {
894         global $notify;
895
896         $progress = check_uri_spam($target, $method);
897
898         if (! empty($progress['is_spam'])) {
899                 // Mail to administrator(s)
900                 if ($notify) pkwk_spamnotify($action, $page, $target, $progress, $method);
901                 // End
902                 spam_exit();
903         }
904 }
905
906 // ---------------------
907 // PukiWiki original
908
909 // Mail to administrator(s)
910 function pkwk_spamnotify($action, $page, $target = array('title' => ''), $progress = array(), $method = array())
911 {
912         global $notify_subject;
913
914         $asap = isset($method['asap']) ? $method['asap'] : TRUE;
915
916         $footer['ACTION']  = 'Blocked by: ' . summarize_spam_progress($progress, TRUE);
917
918         if (! $asap) {
919                 $footer['METRICS'] = summarize_spam_progress($progress);
920         }
921         $footer['COMMENT'] = $action;
922         $footer['PAGE']    = '[blocked] ' . $page;
923         $footer['URI']     = get_script_uri() . '?' . rawurlencode($page);
924         $footer['USER_AGENT']  = TRUE;
925         $footer['REMOTE_ADDR'] = TRUE;
926         pkwk_mail_notify($notify_subject,  var_export($target, TRUE), $footer);
927 }
928
929 ?>