git: Fix bug involving attempting to web revert a commit that included changes to...
[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 ($ENV{HTTPS} || $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 => cgiurl(),
120                 header => 0,
121                 template => {type => 'div'},
122                 stylesheet => 1,
123         );
124         my $buttons=["Login"];
125         
126         $form->field(name => "do", type => "hidden", value => "signin",
127                 force => 1);
128         
129         decode_form_utf8($form);
130         run_hooks(formbuilder_setup => sub {
131                 shift->(form => $form, cgi => $q, session => $session,
132                         buttons => $buttons);
133         });
134         decode_form_utf8($form);
135
136         if ($form->submitted) {
137                 $form->validate;
138         }
139
140         if ($returnhtml) {
141                 $form=prepform($form, $buttons, $session, $q);
142                 return $form->render(submit => $buttons);
143         }
144
145         showform($form, $buttons, $session, $q);
146 }
147
148 sub cgi_postsignin ($$) {
149         my $q=shift;
150         my $session=shift;
151         
152         # Continue with whatever was being done before the signin process.
153         if (defined $session->param("postsignin")) {
154                 my $postsignin=CGI->new($session->param("postsignin"));
155                 $session->clear("postsignin");
156                 cgi($postsignin, $session);
157                 cgi_savesession($session);
158                 exit;
159         }
160         else {
161                 if ($config{sslcookie} && ! $q->https()) {
162                         error(gettext("probable misconfiguration: sslcookie is set, but you are attempting to login via http, not https"));
163                 }
164                 else {
165                         error(gettext("login failed, perhaps you need to turn on cookies?"));
166                 }
167         }
168 }
169
170 sub cgi_prefs ($$) {
171         my $q=shift;
172         my $session=shift;
173
174         needsignin($q, $session);
175         decode_cgi_utf8($q);
176         
177         # The session id is stored on the form and checked to
178         # guard against CSRF.
179         my $sid=$q->param('sid');
180         if (! defined $sid) {
181                 $q->delete_all;
182         }
183         elsif ($sid ne $session->id) {
184                 error(gettext("Your login session has expired."));
185         }
186
187         eval q{use CGI::FormBuilder};
188         error($@) if $@;
189         my $form = CGI::FormBuilder->new(
190                 title => "preferences",
191                 name => "preferences",
192                 header => 0,
193                 charset => "utf-8",
194                 method => 'POST',
195                 validate => {
196                         email => 'EMAIL',
197                 },
198                 required => 'NONE',
199                 javascript => 0,
200                 params => $q,
201                 action => cgiurl(),
202                 template => {type => 'div'},
203                 stylesheet => 1,
204                 fieldsets => [
205                         [login => gettext("Login")],
206                         [preferences => gettext("Preferences")],
207                         [admin => gettext("Admin")]
208                 ],
209         );
210         my $buttons=["Save Preferences", "Logout", "Cancel"];
211         
212         decode_form_utf8($form);
213         run_hooks(formbuilder_setup => sub {
214                 shift->(form => $form, cgi => $q, session => $session,
215                         buttons => $buttons);
216         });
217         decode_form_utf8($form);
218         
219         $form->field(name => "do", type => "hidden", value => "prefs",
220                 force => 1);
221         $form->field(name => "sid", type => "hidden", value => $session->id,
222                 force => 1);
223         $form->field(name => "email", size => 50, fieldset => "preferences");
224         
225         my $user_name=$session->param("name");
226
227         if (! $form->submitted) {
228                 $form->field(name => "email", force => 1,
229                         value => userinfo_get($user_name, "email"));
230         }
231         
232         if ($form->submitted eq 'Logout') {
233                 $session->delete();
234                 redirect($q, baseurl(undef));
235                 return;
236         }
237         elsif ($form->submitted eq 'Cancel') {
238                 redirect($q, baseurl(undef));
239                 return;
240         }
241         elsif ($form->submitted eq 'Save Preferences' && $form->validate) {
242                 if (defined $form->field('email')) {
243                         userinfo_set($user_name, 'email', $form->field('email')) ||
244                                 error("failed to set email");
245                 }
246
247                 $form->text(gettext("Preferences saved."));
248         }
249         
250         showform($form, $buttons, $session, $q,
251                 prefsurl => "", # avoid showing the preferences link
252         );
253 }
254
255 sub cgi_custom_failure ($$$) {
256         my $q=shift;
257         my $httpstatus=shift;
258         my $message=shift;
259
260         print $q->header(
261                 -status => $httpstatus,
262                 -charset => 'utf-8',
263         );
264         print $message;
265
266         # Internet Explod^Hrer won't show custom 404 responses
267         # unless they're >= 512 bytes
268         print ' ' x 512;
269
270         exit;
271 }
272
273 sub check_banned ($$) {
274         my $q=shift;
275         my $session=shift;
276
277         my $banned=0;
278         my $name=$session->param("name");
279         if (defined $name && 
280             grep { $name eq $_ } @{$config{banned_users}}) {
281                 $banned=1;
282         }
283
284         foreach my $b (@{$config{banned_users}}) {
285                 if (pagespec_match("", $b,
286                         ip => $session->remote_addr(),
287                         name => defined $name ? $name : "",
288                 )) {
289                         $banned=1;
290                         last;
291                 }
292         }
293
294         if ($banned) {
295                 $session->delete();
296                 cgi_savesession($session);
297                 cgi_custom_failure(
298                         $q, "403 Forbidden",
299                         gettext("You are banned."));
300         }
301 }
302
303 sub cgi_getsession ($) {
304         my $q=shift;
305
306         eval q{use CGI::Session; use HTML::Entities};
307         error($@) if $@;
308         CGI::Session->name("ikiwiki_session_".encode_entities($config{wikiname}));
309         
310         my $oldmask=umask(077);
311         my $session = eval {
312                 CGI::Session->new("driver:DB_File", $q,
313                         { FileName => "$config{wikistatedir}/sessions.db" })
314         };
315         if (! $session || $@) {
316                 error($@." ".CGI::Session->errstr());
317         }
318         
319         umask($oldmask);
320
321         return $session;
322 }
323
324 # To guard against CSRF, the user's session id (sid)
325 # can be stored on a form. This function will check
326 # (for logged in users) that the sid on the form matches
327 # the session id in the cookie.
328 sub checksessionexpiry ($$) {
329         my $q=shift;
330         my $session = shift;
331
332         if (defined $session->param("name")) {
333                 my $sid=$q->param('sid');
334                 if (! defined $sid || $sid ne $session->id) {
335                         error(gettext("Your login session has expired."));
336                 }
337         }
338 }
339
340 sub cgi_savesession ($) {
341         my $session=shift;
342
343         # Force session flush with safe umask.
344         my $oldmask=umask(077);
345         $session->flush;
346         umask($oldmask);
347 }
348
349 sub cgi (;$$) {
350         my $q=shift;
351         my $session=shift;
352
353         eval q{use CGI};
354         error($@) if $@;
355         $CGI::DISABLE_UPLOADS=$config{cgi_disable_uploads};
356
357         if (! $q) {
358                 binmode(STDIN);
359                 $q=CGI->new;
360                 binmode(STDIN, ":utf8");
361         
362                 run_hooks(cgi => sub { shift->($q) });
363         }
364
365         my $do=$q->param('do');
366         if (! defined $do || ! length $do) {
367                 my $error = $q->cgi_error;
368                 if ($error) {
369                         error("Request not processed: $error");
370                 }
371                 else {
372                         error("\"do\" parameter missing");
373                 }
374         }
375
376         # Need to lock the wiki before getting a session.
377         lockwiki();
378         loadindex();
379         
380         if (! $session) {
381                 $session=cgi_getsession($q);
382         }
383         
384         # Auth hooks can sign a user in.
385         if ($do ne 'signin' && ! defined $session->param("name")) {
386                 run_hooks(auth => sub {
387                         shift->($q, $session)
388                 });
389                 if (defined $session->param("name")) {
390                         # Make sure whatever user was authed is in the
391                         # userinfo db.
392                         if (! userinfo_get($session->param("name"), "regdate")) {
393                                 userinfo_setall($session->param("name"), {
394                                         email => "",
395                                         password => "",
396                                         regdate => time,
397                                 }) || error("failed adding user");
398                         }
399                 }
400         }
401         
402         check_banned($q, $session);
403         
404         run_hooks(sessioncgi => sub { shift->($q, $session) });
405
406         if ($do eq 'signin') {
407                 cgi_signin($q, $session);
408                 cgi_savesession($session);
409         }
410         elsif ($do eq 'prefs') {
411                 cgi_prefs($q, $session);
412         }
413         elsif (defined $session->param("postsignin") || $do eq 'postsignin') {
414                 cgi_postsignin($q, $session);
415         }
416         else {
417                 error("unknown do parameter");
418         }
419 }
420
421 # Does not need to be called directly; all errors will go through here.
422 sub cgierror ($) {
423         my $message=shift;
424
425         print "Content-type: text/html\n\n";
426         print misctemplate(gettext("Error"),
427                 "<p class=\"error\">".gettext("Error").": $message</p>");
428         die $@;
429 }
430
431 1