OSDN Git Service

Corret comments only
[pukiwiki/pukiwiki_sandbox.git] / spam / spam.php
1 <?php
2 // $Id: spam.php,v 1.18 2006/11/18 01:15:41 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 // Return an array of URIs in the $string
9 // [OK] http://nasty.example.org#nasty_string
10 // [OK] http://nasty.example.org/foo/xxx#nasty_string/bar
11 // [OK] ftp://dfshodfs:80/dfsdfs
12 function uri_pickup($string = '', $normalize = TRUE)
13 {
14         // Not available for: user@password, IDN, Fragment(=ignored)
15         $array = array();
16         preg_match_all(
17                 // Refer RFC3986
18                 '#(\b[a-z][a-z0-9.+-]{1,8})://' .       // 1: Scheme
19                 '(' .
20                         // 2: Host
21                         '\[[0-9a-f:.]+\]' . '|' .                               // IPv6([colon-hex and dot]): RFC2732
22                         '(?:[0-9]{1-3}\.){3}[0-9]{1-3}' . '|' . // IPv4(dot-decimal): 001.22.3.44
23                         '[^\s<>"\'\[\]:/\#?]+' .                                // FQDN: foo.example.org
24                 ')' .
25                 '(?::([a-z0-9]{2,}))?' .                        // 3: Port
26                 '((?:/+[^\s<>"\'\[\]/\#]+)*/+)?' .      // 4: Directory path or path-info
27                 '([^\s<>"\'\[\]\#]+)?' .                        // 5: File and query string
28                                                                                         // #: Fragment(ignored)
29                 '#i',
30                  $string, $array, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
31         //var_dump(recursive_map('htmlspecialchars', $array));
32
33         // Shrink $array
34         $parts = array(1 => 'scheme', 2 => 'host', 3 => 'port',
35                 4 => 'path', 5 => 'file');
36         $default = array('');
37         foreach(array_keys($array) as $uri) {
38                 unset($array[$uri][0]); // Matched string itself
39                 array_rename_keys($array[$uri], $parts, TRUE, $default);
40                 $offset = $array[$uri]['scheme'][1]; // Scheme's offset
41
42                 // Remove offsets for each part
43                 if ($normalize) {
44                         foreach(array_keys($array[$uri]) as $part) {
45                                 $array[$uri][$part] = strtolower($array[$uri][$part][0]);
46                         }
47                         $array[$uri]['path'] = path_normalize($array[$uri]['path']);
48                 } else {
49                         foreach(array_keys($array[$uri]) as $part) {
50                                 $array[$uri][$part] = & $array[$uri][$part][0];
51                         }
52                 }
53                 $array[$uri]['offset'] = $offset;
54                 $array[$uri]['area']   = 0;
55         }
56
57         return $array;
58 }
59
60 // Preprocess: rawurldecode() and adding space(s) to detect/count some URIs _if possible_
61 // NOTE: It's maybe danger to var_dump(result). [e.g. 'javascript:']
62 // [OK] http://victim.example.org/go?http%3A%2F%2Fnasty.example.org
63 // [OK] http://victim.example.org/http://nasty.example.org
64 function spam_uri_pickup_preprocess($string = '')
65 {
66         if (is_string($string)) {
67                 return preg_replace(
68                         array(
69                                 '#(?:https?|ftp):/#',
70                                 '#\b[a-z][a-z0-9.+-]{1,8}://#i',
71                                 '#[a-z][a-z0-9.+-]{1,8}://#i'
72                         ),
73                         ' $0',
74                         rawurldecode($string)
75                         );
76         } else {
77                 return '';
78         }
79 }
80
81 // TODO: Area selection (Check BBCode only, check anchor only, check ...)
82 // Main function of spam-uri pickup
83 function spam_uri_pickup($string = '')
84 {
85         $string = spam_uri_pickup_preprocess($string);
86
87         $array  = uri_pickup($string);
88
89         // Area elevation for '(especially external)link' intension
90         if (! empty($array)) {
91                 // Anchor tags by preg_match_all()
92                 // [OK] <a href="http://nasty.example.com">visit http://nasty.example.com/</a>
93                 // [OK] <a href=\'http://nasty.example.com/\' >discount foobar</a> 
94                 // [NG] <a href="http://ng.example.com">visit http://ng.example.com _not_ended_
95                 // [NG] <a href=  >Good site!</a> <a href= "#" >test</a>
96                 $areas = array();
97                 preg_match_all('#<a\b[^>]*href[^>]*>.*?</a\b[^>]*(>)#i',
98                          $string, $areas, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
99                 //var_dump(recursive_map('htmlspecialchars', $areas));
100                 foreach(array_keys($areas) as $area) {
101                         $areas[$area] =  array(
102                                 $areas[$area][0][1], // Area start (<a href>)
103                                 $areas[$area][1][1], // Area end   (</a>)
104                         );
105                 }
106                 area_measure($areas, $array);
107
108                 // phpBB's "BBCode" by preg_match_all()
109                 // [url]http://nasty.example.com/[/url]
110                 // [link]http://nasty.example.com/[/link]
111                 // [url=http://nasty.example.com]visit http://nasty.example.com/[/url]
112                 // [link http://nasty.example.com/]buy something[/link]
113                 // ?? [url=][/url]
114                 $areas = array();
115                 preg_match_all('#\[(url|link)\b[^\]]*\].*?\[/\1\b[^\]]*(\])#i',
116                          $string, $areas, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
117                 //var_dump(recursive_map('htmlspecialchars', $areas));
118                 foreach(array_keys($areas) as $area) {
119                         $areas[$area] = array(
120                                 $areas[$area][0][1], // Area start ([url])
121                                 $areas[$area][2][1], // Area end   ([/url])
122                         );
123                 }
124                 area_measure($areas, $array);
125
126                 // Various Wiki syntax
127                 // [text_or_uri>text_or_uri]
128                 // [text_or_uri:text_or_uri]
129                 // [text_or_uri|text_or_uri]
130                 // [text_or_uri->text_or_uri]
131                 // [text_or_uri text_or_uri] // MediaWiki
132                 // MediaWiki: [http://nasty.example.com/ visit http://nasty.example.com/]
133
134                 // Remove 'offset's for area_measure()
135                 //foreach(array_keys($array) as $key)
136                 //      unset($array[$key]['offset']);
137         }
138
139         return $array;
140 }
141
142 // $array['something'] => $array['wanted']
143 function array_rename_keys(& $array, $keys = array('from' => 'to'), $force = FALSE, $default = '')
144 {
145         if (! is_array($array) || ! is_array($keys))
146                 return FALSE;
147
148         // Nondestructive test
149         if (! $force)
150                 foreach(array_keys($keys) as $from)
151                         if (! isset($array[$from]))
152                                 return FALSE;
153
154         foreach($keys as $from => $to) {
155                 if ($from === $to) continue;
156                 if (! $force || isset($array[$from])) {
157                         $array[$to] = & $array[$from];
158                         unset($array[$from]);
159                 } else  {
160                         $array[$to] = $default;
161                 }
162         }
163
164         return TRUE;
165 }
166
167 // If in doubt, it's a little doubtful
168 function area_measure($areas, & $array, $belief = -1, $a_key = 'area', $o_key = 'offset')
169 {
170         if (! is_array($areas) || ! is_array($array)) return;
171
172         $areas_keys = array_keys($areas);
173         foreach(array_keys($array) as $u_index) {
174                 $offset = isset($array[$u_index][$o_key]) ?
175                         intval($array[$u_index][$o_key]) : 0;
176                 foreach($areas_keys as $a_index) {
177                         if (isset($array[$u_index][$a_key])) {
178                                 $offset_s = intval($areas[$a_index][0]);
179                                 $offset_e = intval($areas[$a_index][1]);
180                                 // [Area => inside <= Area]
181                                 if ($offset_s < $offset && $offset < $offset_e) {
182                                         $array[$u_index][$a_key] += $belief;
183                                 }
184                         }
185                 }
186         }
187 }
188
189
190 // ---------------------
191 // Part Two
192
193 // Path normalization
194 // '' => '/'
195 // #hoge => /#hoge
196 // /path/a/b/./c////./d => /path/a/b/c/d
197 // /path/../../a/../back => /back
198 function path_normalize($path = '', $divider = '/', $addroot = TRUE)
199 {
200         if (! is_string($path) || $path == '') {
201                 $path = $addroot ? $divider : '';
202         } else {
203                 $path = trim($path);
204                 $last = ($path[strlen($path) - 1] == $divider) ? $divider : '';
205                 $array = explode($divider, $path);
206
207                 // Remove paddings
208                 foreach(array_keys($array) as $key) {
209                         if ($array[$key] == '' || $array[$key] == '.')
210                                  unset($array[$key]);
211                 }
212                 // Back-track
213                 $tmp = array();
214                 foreach($array as $value) {
215                         if ($value == '..') {
216                                 array_pop($tmp);
217                         } else {
218                                 array_push($tmp, $value);
219                         }
220                 }
221                 $array = & $tmp;
222
223                 $path = $addroot ? $divider : '';
224                 if (! empty($array)) $path .= implode($divider, $array) . $last;
225         }
226
227         return $path;
228 }
229
230 // Input: '/a/b'
231 // Output: array('' => array('a' => array('b' => NULL)))
232 function array_tree($string, $delimiter = '/', $reverse = FALSE)
233 {
234         // Create a branch
235         $tree = NULL;
236         $tmps = explode($delimiter, $string);
237         if (! $reverse) $tmps = array_reverse($tmps);
238         foreach ($tmps as $tmp) {
239                 $tree = array($tmp => $tree);
240         }
241         return $tree;
242 }
243
244
245 // ---------------------
246 // Part One : Checker
247
248 // Simple/fast spam check
249 function is_uri_spam($target = '')
250 {
251         $is_spam = FALSE;
252         $urinum = 0;
253
254         if (is_array($target)) {
255                 foreach($target as $str) {
256                         // Recurse
257                         list($is_spam, $_urinum) = is_uri_spam($str);
258                         $urinum += $_urinum;
259                         if ($is_spam) break;
260                 }
261         } else {
262                 $pickups = spam_uri_pickup($target);
263                 $urinum += count($pickups);
264                 if (! empty($pickups)) {
265                         // Some users want to post some URLs, but ...
266                         if ($urinum > 8) {
267                                 $is_spam = TRUE;        // Too many!
268                         } else {
269                                 foreach($pickups as $pickup) {
270                                         if ($pickup['area'] < 0) {
271                                                 $is_spam = TRUE;
272                                                 break;
273                                         }
274                                 }
275                         }
276                 }
277         }
278
279         return array($is_spam, $urinum);
280 }
281
282 // ---------------------
283
284 // Check User-Agent (not testing yet)
285 function is_invalid_useragent($ua_name = '' /*, $ua_vars = ''*/ )
286 {
287         return $ua_name === '';
288 }
289
290 // ---------------------
291
292 // TODO: Multi-metrics (uri, host, user-agent, ...)
293 // TODO: Mail to administrator with more measurement data?
294 // Simple/fast spam filter ($target: 'a string' or an array())
295 function pkwk_spamfilter($action, $page, $target = array('title' => ''))
296 {
297         $is_spam = FALSE;
298
299         //$is_spam =  is_invalid_useragent('NOTYET');
300         if ($is_spam) {
301                 $action .= ' (Invalid User-Agent)';
302         } else {
303                 list($is_spam) = is_uri_spam($target);
304         }
305
306         if ($is_spam) {
307                 // Mail to administrator(s)
308                 global $notify, $notify_subject;
309                 if ($notify) {
310                         $footer['ACTION'] = $action;
311                         $footer['PAGE']   = '[blocked] ' . $page;
312                         $footer['URI']    = get_script_uri() . '?' . rawurlencode($page);
313                         $footer['USER_AGENT']  = TRUE;
314                         $footer['REMOTE_ADDR'] = TRUE;
315                         pkwk_mail_notify($notify_subject,  var_export($target, TRUE), $footer);
316                         unset($footer);
317                 }
318         }
319
320         if ($is_spam) spam_exit();
321 }
322
323 // ---------------------
324
325 // Common bahavior for blocking
326 // NOTE: Call this function from various blocking feature, to disgueise the reason 'why blocked'
327 function spam_exit()
328 {
329         die("\n");
330 }
331
332 ?>