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