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