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