]> sipb.mit.edu Git - ikiwiki.git/blob - IkiWiki/CGI.pm
Merge commit '1609da8f00e29c580e92fd1d3c2b093cbc41d20e' into sipb
[ikiwiki.git] / IkiWiki / CGI.pm
1 #!/usr/bin/perl
2
3 package IkiWiki;
4
5 use warnings;
6 use strict;
7 use IkiWiki;
8 use IkiWiki::UserInfo;
9 use open qw{:utf8 :std};
10 use Encode;
11
12 sub printheader ($) {
13         my $session=shift;
14         
15         if ($config{sslcookie}) {
16                 print $session->header(-charset => 'utf-8',
17                         -cookie => $session->cookie(-httponly => 1, -secure => 1));
18         }
19         else {
20                 print $session->header(-charset => 'utf-8',
21                         -cookie => $session->cookie(-httponly => 1));
22         }
23 }
24
25 sub prepform {
26         my $form=shift;
27         my $buttons=shift;
28         my $session=shift;
29         my $cgi=shift;
30
31         if (exists $hooks{formbuilder}) {
32                 run_hooks(formbuilder => sub {
33                         shift->(form => $form, cgi => $cgi, session => $session,
34                                 buttons => $buttons);
35                 });
36         }
37
38         return $form;
39 }
40
41 sub showform ($$$$;@) {
42         my $form=prepform(@_);
43         shift;
44         my $buttons=shift;
45         my $session=shift;
46         my $cgi=shift;
47
48         printheader($session);
49         print misctemplate($form->title, $form->render(submit => $buttons), @_);
50 }
51
52 sub redirect ($$) {
53         my $q=shift;
54         eval q{use URI};
55         my $url=URI->new(shift);
56         if (! $config{w3mmode}) {
57                 print $q->redirect($url);
58         }
59         else {
60                 print "Content-type: text/plain\n";
61                 print "W3m-control: GOTO $url\n\n";
62         }
63 }
64
65 sub decode_cgi_utf8 ($) {
66         # decode_form_utf8 method is needed for 5.01
67         if ($] < 5.01) {
68                 my $cgi = shift;
69                 foreach my $f ($cgi->param) {
70                         $cgi->param($f, map { decode_utf8 $_ } $cgi->param($f));
71                 }
72         }
73 }
74
75 sub decode_form_utf8 ($) {
76         if ($] >= 5.01) {
77                 my $form = shift;
78                 foreach my $f ($form->field) {
79                         my @value=map { decode_utf8($_) } $form->field($f);
80                         $form->field(name  => $f,
81                                      value => \@value,
82                                      force => 1,
83                         );
84                 }
85         }
86 }
87
88 # Check if the user is signed in. If not, redirect to the signin form and
89 # save their place to return to later.
90 sub needsignin ($$) {
91         my $q=shift;
92         my $session=shift;
93
94         if (! defined $session->param("name") ||
95             ! userinfo_get($session->param("name"), "regdate")) {
96                 $session->param(postsignin => $ENV{QUERY_STRING});
97                 cgi_signin($q, $session);
98                 cgi_savesession($session);
99                 exit;
100         }
101 }
102
103 sub cgi_signin ($$;$) {
104         my $q=shift;
105         my $session=shift;
106         my $returnhtml=shift;
107
108         decode_cgi_utf8($q);
109         eval q{use CGI::FormBuilder};
110         error($@) if $@;
111         my $form = CGI::FormBuilder->new(
112                 title => "signin",
113                 name => "signin",
114                 charset => "utf-8",
115                 method => 'POST',
116                 required => 'NONE',
117                 javascript => 0,
118                 params => $q,
119                 action => $config{cgiurl},
120                 header => 0,
121                 template => {type => 'div'},
122                 stylesheet => 1,
123         );
124         # MITLOGIN: These should be restored when logins are allowed again.
125         #my $buttons=["Login"];
126         my $buttons=[];
127         
128         $form->field(name => "do", type => "hidden", value => "signin",
129                 force => 1);
130         
131         decode_form_utf8($form);
132         run_hooks(formbuilder_setup => sub {
133                 shift->(form => $form, cgi => $q, session => $session,
134                         buttons => $buttons);
135         });
136         decode_form_utf8($form);
137
138         if ($form->submitted) {
139                 $form->validate;
140         }
141
142         if ($returnhtml) {
143                 $form=prepform($form, $buttons, $session, $q);
144                 return $form->render(submit => $buttons);
145         }
146
147         showform($form, $buttons, $session, $q);
148 }
149
150 sub cgi_postsignin ($$) {
151         my $q=shift;
152         my $session=shift;
153         
154         # Continue with whatever was being done before the signin process.
155         if (defined $session->param("postsignin")) {
156                 my $postsignin=CGI->new($session->param("postsignin"));
157                 $session->clear("postsignin");
158                 cgi($postsignin, $session);
159                 cgi_savesession($session);
160                 exit;
161         }
162         else {
163                 if ($config{sslcookie} && ! $q->https()) {
164                         error(gettext("probable misconfiguration: sslcookie is set, but you are attempting to login via http, not https"));
165                 }
166                 else {
167                         error(gettext("login failed, perhaps you need to turn on cookies?"));
168                 }
169         }
170 }
171
172 sub cgi_prefs ($$) {
173         my $q=shift;
174         my $session=shift;
175
176         needsignin($q, $session);
177         decode_cgi_utf8($q);
178         
179         # The session id is stored on the form and checked to
180         # guard against CSRF.
181         my $sid=$q->param('sid');
182         if (! defined $sid) {
183                 $q->delete_all;
184         }
185         elsif ($sid ne $session->id) {
186                 error(gettext("Your login session has expired."));
187         }
188
189         eval q{use CGI::FormBuilder};
190         error($@) if $@;
191         my $form = CGI::FormBuilder->new(
192                 title => "preferences",
193                 name => "preferences",
194                 header => 0,
195                 charset => "utf-8",
196                 method => 'POST',
197                 validate => {
198                         email => 'EMAIL',
199                 },
200                 required => 'NONE',
201                 javascript => 0,
202                 params => $q,
203                 action => $config{cgiurl},
204                 template => {type => 'div'},
205                 stylesheet => 1,
206                 fieldsets => [
207                         [login => gettext("Login")],
208                         [preferences => gettext("Preferences")],
209                         [admin => gettext("Admin")]
210                 ],
211         );
212         my $buttons=["Save Preferences", "Logout", "Cancel"];
213         
214         decode_form_utf8($form);
215         run_hooks(formbuilder_setup => sub {
216                 shift->(form => $form, cgi => $q, session => $session,
217                         buttons => $buttons);
218         });
219         decode_form_utf8($form);
220         
221         $form->field(name => "do", type => "hidden", value => "prefs",
222                 force => 1);
223         $form->field(name => "sid", type => "hidden", value => $session->id,
224                 force => 1);
225             #$form->field(name => "email", size => 50, fieldset => "preferences");
226         $form->field(name => "realname", size => 50, fieldset => "preferences");
227         
228         my $user_name=$session->param("name");
229
230         if (! $form->submitted) {
231             #$form->field(name => "email", force => 1,
232             #value => userinfo_get($user_name, "email"));
233                 $form->field(name => "realname", force => 1,
234                         value => userinfo_get($user_name, "realname"));
235         }
236         
237         if ($form->submitted eq 'Logout') {
238                 $session->delete();
239                 redirect($q, $config{url});
240                 return;
241         }
242         elsif ($form->submitted eq 'Cancel') {
243                 redirect($q, $config{url});
244                 return;
245         }
246         elsif ($form->submitted eq 'Save Preferences' && $form->validate) {
247                 if (defined $form->field('email')) {
248                         userinfo_set($user_name, 'email', $form->field('email')) ||
249                                 error("failed to set email");
250                 }
251                 if (defined $form->field('realname')) {
252                         userinfo_set($user_name, 'realname', $form->field('realname')) ||
253                                 error("failed to set realname");
254                 }
255                 $form->text(gettext("Preferences saved."));
256         }
257         
258         showform($form, $buttons, $session, $q,
259                 prefsurl => "", # avoid showing the preferences link
260         );
261 }
262
263 sub cgi_custom_failure ($$$) {
264         my $q=shift;
265         my $httpstatus=shift;
266         my $message=shift;
267
268         print $q->header(
269                 -status => $httpstatus,
270                 -charset => 'utf-8',
271         );
272         print $message;
273
274         # Internet Explod^Hrer won't show custom 404 responses
275         # unless they're >= 512 bytes
276         print ' ' x 512;
277
278         exit;
279 }
280
281 sub check_banned ($$) {
282         my $q=shift;
283         my $session=shift;
284
285         my $banned=0;
286         my $name=$session->param("name");
287         if (defined $name && 
288             grep { $name eq $_ } @{$config{banned_users}}) {
289                 $banned=1;
290         }
291
292         foreach my $b (@{$config{banned_users}}) {
293                 if (pagespec_match("", $b,
294                         ip => $ENV{REMOTE_ADDR},
295                         name => defined $name ? $name : "",
296                 )) {
297                         $banned=1;
298                         last;
299                 }
300         }
301
302         if ($banned) {
303                 $session->delete();
304                 cgi_savesession($session);
305                 cgi_custom_failure(
306                         $q, "403 Forbidden",
307                         gettext("You are banned."));
308         }
309 }
310
311 sub cgi_getsession ($) {
312         my $q=shift;
313
314         eval q{use CGI::Session; use HTML::Entities};
315         error($@) if $@;
316         CGI::Session->name("ikiwiki_session_".encode_entities($config{wikiname}));
317         
318         my $oldmask=umask(077);
319         my $session = eval {
320                 CGI::Session->new("driver:DB_File", $q,
321                         { FileName => "$config{wikistatedir}/sessions.db" })
322         };
323         if (! $session || $@) {
324                 error($@." ".CGI::Session->errstr());
325         }
326         
327         umask($oldmask);
328
329         return $session;
330 }
331
332 # To guard against CSRF, the user's session id (sid)
333 # can be stored on a form. This function will check
334 # (for logged in users) that the sid on the form matches
335 # the session id in the cookie.
336 sub checksessionexpiry ($$) {
337         my $q=shift;
338         my $session = shift;
339
340         if (defined $session->param("name")) {
341                 my $sid=$q->param('sid');
342                 if (! defined $sid || $sid ne $session->id) {
343                         error(gettext("Your login session has expired."));
344                 }
345         }
346 }
347
348 sub cgi_savesession ($) {
349         my $session=shift;
350
351         # Force session flush with safe umask.
352         my $oldmask=umask(077);
353         $session->flush;
354         umask($oldmask);
355 }
356
357 sub cgi (;$$) {
358         my $q=shift;
359         my $session=shift;
360
361         eval q{use CGI};
362         error($@) if $@;
363         $CGI::DISABLE_UPLOADS=$config{cgi_disable_uploads};
364
365         if (! $q) {
366                 binmode(STDIN);
367                 $q=CGI->new;
368                 binmode(STDIN, ":utf8");
369         
370                 run_hooks(cgi => sub { shift->($q) });
371         }
372
373         my $do=$q->param('do');
374         if (! defined $do || ! length $do) {
375                 my $error = $q->cgi_error;
376                 if ($error) {
377                         error("Request not processed: $error");
378                 }
379                 else {
380                         error("\"do\" parameter missing");
381                 }
382         }
383
384         # Need to lock the wiki before getting a session.
385         lockwiki();
386         loadindex();
387         
388         if (! $session) {
389                 $session=cgi_getsession($q);
390         }
391         
392         # Auth hooks can sign a user in.
393         if ($do ne 'signin' && ! defined $session->param("name")) {
394                 run_hooks(auth => sub {
395                         shift->($q, $session)
396                 });
397                 if (defined $session->param("name")) {
398                         # Make sure whatever user was authed is in the
399                         # userinfo db.
400                         if (! userinfo_get($session->param("name"), "regdate")) {
401                                 userinfo_setall($session->param("name"), {
402                                         email => "",
403                                         password => "",
404                                         regdate => time,
405                                 }) || error("failed adding user");
406                         }
407                 }
408         }
409         
410         check_banned($q, $session);
411         
412         run_hooks(sessioncgi => sub { shift->($q, $session) });
413
414         if ($do eq 'signin') {
415                 cgi_signin($q, $session);
416                 cgi_savesession($session);
417         }
418         elsif ($do eq 'prefs') {
419                 cgi_prefs($q, $session);
420         }
421         elsif (defined $session->param("postsignin") || $do eq 'postsignin') {
422                 cgi_postsignin($q, $session);
423         }
424         else {
425                 error("unknown do parameter");
426         }
427 }
428
429 # Does not need to be called directly; all errors will go through here.
430 sub cgierror ($) {
431         my $message=shift;
432
433         print "Content-type: text/html\n\n";
434         print misctemplate(gettext("Error"),
435                 "<p class=\"error\">".gettext("Error").": $message</p>");
436         die $@;
437 }
438
439 1