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