OSDN Git Service

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