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