put back recentchangesurl
[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         }
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 => $config{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 => $config{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, $config{url});
235                 return;
236         }
237         elsif ($form->submitted eq 'Cancel') {
238                 redirect($q, $config{url});
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 }
252
253 sub cgi_custom_failure ($$$) {
254         my $q=shift;
255         my $httpstatus=shift;
256         my $message=shift;
257
258         print $q->header(
259                 -status => $httpstatus,
260                 -charset => 'utf-8',
261         );
262         print $message;
263
264         # Internet Explod^Hrer won't show custom 404 responses
265         # unless they're >= 512 bytes
266         print ' ' x 512;
267
268         exit;
269 }
270
271 sub check_banned ($$) {
272         my $q=shift;
273         my $session=shift;
274
275         my $banned=0;
276         my $name=$session->param("name");
277         if (defined $name && 
278             grep { $name eq $_ } @{$config{banned_users}}) {
279                 $banned=1;
280         }
281
282         foreach my $b (@{$config{banned_users}}) {
283                 if (pagespec_match("", $b,
284                         ip => $ENV{REMOTE_ADDR},
285                         name => defined $name ? $name : "",
286                 )) {
287                         $banned=1;
288                         last;
289                 }
290         }
291
292         if ($banned) {
293                 $session->delete();
294                 cgi_savesession($session);
295                 cgi_custom_failure(
296                         $q, "403 Forbidden",
297                         gettext("You are banned."));
298         }
299 }
300
301 sub cgi_getsession ($) {
302         my $q=shift;
303
304         eval q{use CGI::Session; use HTML::Entities};
305         error($@) if $@;
306         CGI::Session->name("ikiwiki_session_".encode_entities($config{wikiname}));
307         
308         my $oldmask=umask(077);
309         my $session = eval {
310                 CGI::Session->new("driver:DB_File", $q,
311                         { FileName => "$config{wikistatedir}/sessions.db" })
312         };
313         if (! $session || $@) {
314                 error($@." ".CGI::Session->errstr());
315         }
316         
317         umask($oldmask);
318
319         return $session;
320 }
321
322 # To guard against CSRF, the user's session id (sid)
323 # can be stored on a form. This function will check
324 # (for logged in users) that the sid on the form matches
325 # the session id in the cookie.
326 sub checksessionexpiry ($$) {
327         my $q=shift;
328         my $session = shift;
329
330         if (defined $session->param("name")) {
331                 my $sid=$q->param('sid');
332                 if (! defined $sid || $sid ne $session->id) {
333                         error(gettext("Your login session has expired."));
334                 }
335         }
336 }
337
338 sub cgi_savesession ($) {
339         my $session=shift;
340
341         # Force session flush with safe umask.
342         my $oldmask=umask(077);
343         $session->flush;
344         umask($oldmask);
345 }
346
347 sub cgi (;$$) {
348         my $q=shift;
349         my $session=shift;
350
351         eval q{use CGI};
352         error($@) if $@;
353         $CGI::DISABLE_UPLOADS=$config{cgi_disable_uploads};
354
355         if (! $q) {
356                 binmode(STDIN);
357                 $q=CGI->new;
358                 binmode(STDIN, ":utf8");
359         
360                 run_hooks(cgi => sub { shift->($q) });
361         }
362
363         my $do=$q->param('do');
364         if (! defined $do || ! length $do) {
365                 my $error = $q->cgi_error;
366                 if ($error) {
367                         error("Request not processed: $error");
368                 }
369                 else {
370                         error("\"do\" parameter missing");
371                 }
372         }
373
374         # Need to lock the wiki before getting a session.
375         lockwiki();
376         loadindex();
377         
378         if (! $session) {
379                 $session=cgi_getsession($q);
380         }
381         
382         # Auth hooks can sign a user in.
383         if ($do ne 'signin' && ! defined $session->param("name")) {
384                 run_hooks(auth => sub {
385                         shift->($q, $session)
386                 });
387                 if (defined $session->param("name")) {
388                         # Make sure whatever user was authed is in the
389                         # userinfo db.
390                         if (! userinfo_get($session->param("name"), "regdate")) {
391                                 userinfo_setall($session->param("name"), {
392                                         email => "",
393                                         password => "",
394                                         regdate => time,
395                                 }) || error("failed adding user");
396                         }
397                 }
398         }
399         
400         check_banned($q, $session);
401         
402         run_hooks(sessioncgi => sub { shift->($q, $session) });
403
404         if ($do eq 'signin') {
405                 cgi_signin($q, $session);
406                 cgi_savesession($session);
407         }
408         elsif ($do eq 'prefs') {
409                 cgi_prefs($q, $session);
410         }
411         elsif (defined $session->param("postsignin") || $do eq 'postsignin') {
412                 cgi_postsignin($q, $session);
413         }
414         else {
415                 error("unknown do parameter");
416         }
417 }
418
419 # Does not need to be called directly; all errors will go through here.
420 sub cgierror ($) {
421         my $message=shift;
422
423         print "Content-type: text/html\n\n";
424         print misctemplate(gettext("Error"),
425                 "<p class=\"error\">".gettext("Error").": $message</p>");
426         die $@;
427 }
428
429 1