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