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