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